editor.rs

    1#![allow(rustdoc::private_intra_doc_links)]
    2//! This is the place where everything editor-related is stored (data-wise) and displayed (ui-wise).
    3//! The main point of interest in this crate is [`Editor`] type, which is used in every other Zed part as a user input element.
    4//! It comes in different flavors: single line, multiline and a fixed height one.
    5//!
    6//! Editor contains of multiple large submodules:
    7//! * [`element`] — the place where all rendering happens
    8//! * [`display_map`] - chunks up text in the editor into the logical blocks, establishes coordinates and mapping between each of them.
    9//!   Contains all metadata related to text transformations (folds, fake inlay text insertions, soft wraps, tab markup, etc.).
   10//! * [`inlay_hint_cache`] - is a storage of inlay hints out of LSP requests, responsible for querying LSP and updating `display_map`'s state accordingly.
   11//!
   12//! All other submodules and structs are mostly concerned with holding editor data about the way it displays current buffer region(s).
   13//!
   14//! If you're looking to improve Vim mode, you should check out Vim crate that wraps Editor and overrides its behavior.
   15pub mod actions;
   16mod blink_manager;
   17mod clangd_ext;
   18mod code_context_menus;
   19pub mod display_map;
   20mod editor_settings;
   21mod editor_settings_controls;
   22mod element;
   23mod git;
   24mod highlight_matching_bracket;
   25mod hover_links;
   26pub mod hover_popover;
   27mod indent_guides;
   28mod inlay_hint_cache;
   29pub mod items;
   30mod jsx_tag_auto_close;
   31mod linked_editing_ranges;
   32mod lsp_ext;
   33mod mouse_context_menu;
   34pub mod movement;
   35mod persistence;
   36mod proposed_changes_editor;
   37mod rust_analyzer_ext;
   38pub mod scroll;
   39mod selections_collection;
   40pub mod tasks;
   41
   42#[cfg(test)]
   43mod code_completion_tests;
   44#[cfg(test)]
   45mod editor_tests;
   46#[cfg(test)]
   47mod inline_completion_tests;
   48mod signature_help;
   49#[cfg(any(test, feature = "test-support"))]
   50pub mod test;
   51
   52pub(crate) use actions::*;
   53pub use actions::{AcceptEditPrediction, OpenExcerpts, OpenExcerptsSplit};
   54use aho_corasick::AhoCorasick;
   55use anyhow::{Context as _, Result, anyhow};
   56use blink_manager::BlinkManager;
   57use buffer_diff::DiffHunkStatus;
   58use client::{Collaborator, ParticipantIndex};
   59use clock::{AGENT_REPLICA_ID, ReplicaId};
   60use collections::{BTreeMap, HashMap, HashSet, VecDeque};
   61use convert_case::{Case, Casing};
   62use display_map::*;
   63pub use display_map::{ChunkRenderer, ChunkRendererContext, DisplayPoint, FoldPlaceholder};
   64pub use editor_settings::{
   65    CurrentLineHighlight, EditorSettings, HideMouseMode, ScrollBeyondLastLine, SearchSettings,
   66    ShowScrollbar,
   67};
   68use editor_settings::{GoToDefinitionFallback, Minimap as MinimapSettings};
   69pub use editor_settings_controls::*;
   70use element::{AcceptEditPredictionBinding, LineWithInvisibles, PositionMap, layout_line};
   71pub use element::{
   72    CursorLayout, EditorElement, HighlightedRange, HighlightedRangeLine, PointForPosition,
   73};
   74use feature_flags::{DebuggerFeatureFlag, FeatureFlagAppExt};
   75use futures::{
   76    FutureExt,
   77    future::{self, Shared, join},
   78};
   79use fuzzy::StringMatchCandidate;
   80
   81use ::git::blame::BlameEntry;
   82use ::git::{Restore, blame::ParsedCommitMessage};
   83use code_context_menus::{
   84    AvailableCodeAction, CodeActionContents, CodeActionsItem, CodeActionsMenu, CodeContextMenu,
   85    CompletionsMenu, ContextMenuOrigin,
   86};
   87use git::blame::{GitBlame, GlobalBlameRenderer};
   88use gpui::{
   89    Action, Animation, AnimationExt, AnyElement, App, AppContext, AsyncWindowContext,
   90    AvailableSpace, Background, Bounds, ClickEvent, ClipboardEntry, ClipboardItem, Context,
   91    DispatchPhase, Edges, Entity, EntityInputHandler, EventEmitter, FocusHandle, FocusOutEvent,
   92    Focusable, FontId, FontWeight, Global, HighlightStyle, Hsla, KeyContext, Modifiers,
   93    MouseButton, MouseDownEvent, PaintQuad, ParentElement, Pixels, Render, ScrollHandle,
   94    SharedString, Size, Stateful, Styled, Subscription, Task, TextStyle, TextStyleRefinement,
   95    UTF16Selection, UnderlineStyle, UniformListScrollHandle, WeakEntity, WeakFocusHandle, Window,
   96    div, impl_actions, point, prelude::*, pulsating_between, px, relative, size,
   97};
   98use highlight_matching_bracket::refresh_matching_bracket_highlights;
   99use hover_links::{HoverLink, HoveredLinkState, InlayHighlight, find_file};
  100pub use hover_popover::hover_markdown_style;
  101use hover_popover::{HoverState, hide_hover};
  102use indent_guides::ActiveIndentGuidesState;
  103use inlay_hint_cache::{InlayHintCache, InlaySplice, InvalidationStrategy};
  104pub use inline_completion::Direction;
  105use inline_completion::{EditPredictionProvider, InlineCompletionProviderHandle};
  106pub use items::MAX_TAB_TITLE_LEN;
  107use itertools::Itertools;
  108use language::{
  109    AutoindentMode, BracketMatch, BracketPair, Buffer, Capability, CharKind, CodeLabel,
  110    CursorShape, DiagnosticEntry, DiffOptions, EditPredictionsMode, EditPreview, HighlightedText,
  111    IndentKind, IndentSize, Language, OffsetRangeExt, Point, Selection, SelectionGoal, TextObject,
  112    TransactionId, TreeSitterOptions, WordsQuery,
  113    language_settings::{
  114        self, InlayHintSettings, LspInsertMode, RewrapBehavior, WordsCompletionMode,
  115        all_language_settings, language_settings,
  116    },
  117    point_from_lsp, text_diff_with_options,
  118};
  119use language::{BufferRow, CharClassifier, Runnable, RunnableRange, point_to_lsp};
  120use linked_editing_ranges::refresh_linked_ranges;
  121use markdown::Markdown;
  122use mouse_context_menu::MouseContextMenu;
  123use persistence::DB;
  124use project::{
  125    ProjectPath,
  126    debugger::{
  127        breakpoint_store::{
  128            BreakpointEditAction, BreakpointState, BreakpointStore, BreakpointStoreEvent,
  129        },
  130        session::{Session, SessionEvent},
  131    },
  132    project_settings::DiagnosticSeverity,
  133};
  134
  135pub use git::blame::BlameRenderer;
  136pub use proposed_changes_editor::{
  137    ProposedChangeLocation, ProposedChangesEditor, ProposedChangesEditorToolbar,
  138};
  139use smallvec::smallvec;
  140use std::{cell::OnceCell, iter::Peekable, ops::Not};
  141use task::{ResolvedTask, RunnableTag, TaskTemplate, TaskVariables};
  142
  143pub use lsp::CompletionContext;
  144use lsp::{
  145    CodeActionKind, CompletionItemKind, CompletionTriggerKind, InsertTextFormat, InsertTextMode,
  146    LanguageServerId, LanguageServerName,
  147};
  148
  149use language::BufferSnapshot;
  150pub use lsp_ext::lsp_tasks;
  151use movement::TextLayoutDetails;
  152pub use multi_buffer::{
  153    Anchor, AnchorRangeExt, ExcerptId, ExcerptRange, MultiBuffer, MultiBufferSnapshot, PathKey,
  154    RowInfo, ToOffset, ToPoint,
  155};
  156use multi_buffer::{
  157    ExcerptInfo, ExpandExcerptDirection, MultiBufferDiffHunk, MultiBufferPoint, MultiBufferRow,
  158    MultiOrSingleBufferOffsetRange, ToOffsetUtf16,
  159};
  160use parking_lot::Mutex;
  161use project::{
  162    CodeAction, Completion, CompletionIntent, CompletionSource, DocumentHighlight, InlayHint,
  163    Location, LocationLink, PrepareRenameResponse, Project, ProjectItem, ProjectTransaction,
  164    TaskSourceKind,
  165    debugger::breakpoint_store::Breakpoint,
  166    lsp_store::{CompletionDocumentation, FormatTrigger, LspFormatTarget, OpenLspBufferHandle},
  167    project_settings::{GitGutterSetting, ProjectSettings},
  168};
  169use rand::prelude::*;
  170use rpc::{ErrorExt, proto::*};
  171use scroll::{Autoscroll, OngoingScroll, ScrollAnchor, ScrollManager, ScrollbarAutoHide};
  172use selections_collection::{
  173    MutableSelectionsCollection, SelectionsCollection, resolve_selections,
  174};
  175use serde::{Deserialize, Serialize};
  176use settings::{Settings, SettingsLocation, SettingsStore, update_settings_file};
  177use smallvec::SmallVec;
  178use snippet::Snippet;
  179use std::sync::Arc;
  180use std::{
  181    any::TypeId,
  182    borrow::Cow,
  183    cell::RefCell,
  184    cmp::{self, Ordering, Reverse},
  185    mem,
  186    num::NonZeroU32,
  187    ops::{ControlFlow, Deref, DerefMut, Range, RangeInclusive},
  188    path::{Path, PathBuf},
  189    rc::Rc,
  190    time::{Duration, Instant},
  191};
  192pub use sum_tree::Bias;
  193use sum_tree::TreeMap;
  194use text::{BufferId, FromAnchor, OffsetUtf16, Rope};
  195use theme::{
  196    ActiveTheme, PlayerColor, StatusColors, SyntaxTheme, ThemeColors, ThemeSettings,
  197    observe_buffer_font_size_adjustment,
  198};
  199use ui::{
  200    ButtonSize, ButtonStyle, ContextMenu, Disclosure, IconButton, IconButtonShape, IconName,
  201    IconSize, Key, Tooltip, h_flex, prelude::*,
  202};
  203use util::{RangeExt, ResultExt, TryFutureExt, maybe, post_inc};
  204use workspace::{
  205    CollaboratorId, Item as WorkspaceItem, ItemId, ItemNavHistory, OpenInTerminal, OpenTerminal,
  206    RestoreOnStartupBehavior, SERIALIZATION_THROTTLE_TIME, SplitDirection, TabBarSettings, Toast,
  207    ViewId, Workspace, WorkspaceId, WorkspaceSettings,
  208    item::{ItemHandle, PreviewTabsSettings},
  209    notifications::{DetachAndPromptErr, NotificationId, NotifyTaskExt},
  210    searchable::SearchEvent,
  211};
  212
  213use crate::hover_links::{find_url, find_url_from_range};
  214use crate::signature_help::{SignatureHelpHiddenBy, SignatureHelpState};
  215
  216pub const FILE_HEADER_HEIGHT: u32 = 2;
  217pub const MULTI_BUFFER_EXCERPT_HEADER_HEIGHT: u32 = 1;
  218pub const DEFAULT_MULTIBUFFER_CONTEXT: u32 = 2;
  219const CURSOR_BLINK_INTERVAL: Duration = Duration::from_millis(500);
  220const MAX_LINE_LEN: usize = 1024;
  221const MIN_NAVIGATION_HISTORY_ROW_DELTA: i64 = 10;
  222const MAX_SELECTION_HISTORY_LEN: usize = 1024;
  223pub(crate) const CURSORS_VISIBLE_FOR: Duration = Duration::from_millis(2000);
  224#[doc(hidden)]
  225pub const CODE_ACTIONS_DEBOUNCE_TIMEOUT: Duration = Duration::from_millis(250);
  226const SELECTION_HIGHLIGHT_DEBOUNCE_TIMEOUT: Duration = Duration::from_millis(100);
  227
  228pub(crate) const CODE_ACTION_TIMEOUT: Duration = Duration::from_secs(5);
  229pub(crate) const FORMAT_TIMEOUT: Duration = Duration::from_secs(5);
  230pub(crate) const SCROLL_CENTER_TOP_BOTTOM_DEBOUNCE_TIMEOUT: Duration = Duration::from_secs(1);
  231
  232pub(crate) const EDIT_PREDICTION_KEY_CONTEXT: &str = "edit_prediction";
  233pub(crate) const EDIT_PREDICTION_CONFLICT_KEY_CONTEXT: &str = "edit_prediction_conflict";
  234pub(crate) const MIN_LINE_NUMBER_DIGITS: u32 = 4;
  235pub(crate) const MINIMAP_FONT_SIZE: AbsoluteLength = AbsoluteLength::Pixels(px(2.));
  236
  237pub type RenderDiffHunkControlsFn = Arc<
  238    dyn Fn(
  239        u32,
  240        &DiffHunkStatus,
  241        Range<Anchor>,
  242        bool,
  243        Pixels,
  244        &Entity<Editor>,
  245        &mut Window,
  246        &mut App,
  247    ) -> AnyElement,
  248>;
  249
  250const COLUMNAR_SELECTION_MODIFIERS: Modifiers = Modifiers {
  251    alt: true,
  252    shift: true,
  253    control: false,
  254    platform: false,
  255    function: false,
  256};
  257
  258struct InlineValueCache {
  259    enabled: bool,
  260    inlays: Vec<InlayId>,
  261    refresh_task: Task<Option<()>>,
  262}
  263
  264impl InlineValueCache {
  265    fn new(enabled: bool) -> Self {
  266        Self {
  267            enabled,
  268            inlays: Vec::new(),
  269            refresh_task: Task::ready(None),
  270        }
  271    }
  272}
  273
  274#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
  275pub enum InlayId {
  276    InlineCompletion(usize),
  277    Hint(usize),
  278    DebuggerValue(usize),
  279}
  280
  281impl InlayId {
  282    fn id(&self) -> usize {
  283        match self {
  284            Self::InlineCompletion(id) => *id,
  285            Self::Hint(id) => *id,
  286            Self::DebuggerValue(id) => *id,
  287        }
  288    }
  289}
  290
  291pub enum ActiveDebugLine {}
  292pub enum DebugStackFrameLine {}
  293enum DocumentHighlightRead {}
  294enum DocumentHighlightWrite {}
  295enum InputComposition {}
  296enum SelectedTextHighlight {}
  297
  298pub enum ConflictsOuter {}
  299pub enum ConflictsOurs {}
  300pub enum ConflictsTheirs {}
  301pub enum ConflictsOursMarker {}
  302pub enum ConflictsTheirsMarker {}
  303
  304#[derive(Debug, Copy, Clone, PartialEq, Eq)]
  305pub enum Navigated {
  306    Yes,
  307    No,
  308}
  309
  310impl Navigated {
  311    pub fn from_bool(yes: bool) -> Navigated {
  312        if yes { Navigated::Yes } else { Navigated::No }
  313    }
  314}
  315
  316#[derive(Debug, Clone, PartialEq, Eq)]
  317enum DisplayDiffHunk {
  318    Folded {
  319        display_row: DisplayRow,
  320    },
  321    Unfolded {
  322        is_created_file: bool,
  323        diff_base_byte_range: Range<usize>,
  324        display_row_range: Range<DisplayRow>,
  325        multi_buffer_range: Range<Anchor>,
  326        status: DiffHunkStatus,
  327    },
  328}
  329
  330pub enum HideMouseCursorOrigin {
  331    TypingAction,
  332    MovementAction,
  333}
  334
  335pub fn init_settings(cx: &mut App) {
  336    EditorSettings::register(cx);
  337}
  338
  339pub fn init(cx: &mut App) {
  340    init_settings(cx);
  341
  342    cx.set_global(GlobalBlameRenderer(Arc::new(())));
  343
  344    workspace::register_project_item::<Editor>(cx);
  345    workspace::FollowableViewRegistry::register::<Editor>(cx);
  346    workspace::register_serializable_item::<Editor>(cx);
  347
  348    cx.observe_new(
  349        |workspace: &mut Workspace, _: Option<&mut Window>, _cx: &mut Context<Workspace>| {
  350            workspace.register_action(Editor::new_file);
  351            workspace.register_action(Editor::new_file_vertical);
  352            workspace.register_action(Editor::new_file_horizontal);
  353            workspace.register_action(Editor::cancel_language_server_work);
  354        },
  355    )
  356    .detach();
  357
  358    cx.on_action(move |_: &workspace::NewFile, cx| {
  359        let app_state = workspace::AppState::global(cx);
  360        if let Some(app_state) = app_state.upgrade() {
  361            workspace::open_new(
  362                Default::default(),
  363                app_state,
  364                cx,
  365                |workspace, window, cx| {
  366                    Editor::new_file(workspace, &Default::default(), window, cx)
  367                },
  368            )
  369            .detach();
  370        }
  371    });
  372    cx.on_action(move |_: &workspace::NewWindow, cx| {
  373        let app_state = workspace::AppState::global(cx);
  374        if let Some(app_state) = app_state.upgrade() {
  375            workspace::open_new(
  376                Default::default(),
  377                app_state,
  378                cx,
  379                |workspace, window, cx| {
  380                    cx.activate(true);
  381                    Editor::new_file(workspace, &Default::default(), window, cx)
  382                },
  383            )
  384            .detach();
  385        }
  386    });
  387}
  388
  389pub fn set_blame_renderer(renderer: impl BlameRenderer + 'static, cx: &mut App) {
  390    cx.set_global(GlobalBlameRenderer(Arc::new(renderer)));
  391}
  392
  393pub trait DiagnosticRenderer {
  394    fn render_group(
  395        &self,
  396        diagnostic_group: Vec<DiagnosticEntry<Point>>,
  397        buffer_id: BufferId,
  398        snapshot: EditorSnapshot,
  399        editor: WeakEntity<Editor>,
  400        cx: &mut App,
  401    ) -> Vec<BlockProperties<Anchor>>;
  402
  403    fn render_hover(
  404        &self,
  405        diagnostic_group: Vec<DiagnosticEntry<Point>>,
  406        range: Range<Point>,
  407        buffer_id: BufferId,
  408        cx: &mut App,
  409    ) -> Option<Entity<markdown::Markdown>>;
  410
  411    fn open_link(
  412        &self,
  413        editor: &mut Editor,
  414        link: SharedString,
  415        window: &mut Window,
  416        cx: &mut Context<Editor>,
  417    );
  418}
  419
  420pub(crate) struct GlobalDiagnosticRenderer(pub Arc<dyn DiagnosticRenderer>);
  421
  422impl GlobalDiagnosticRenderer {
  423    fn global(cx: &App) -> Option<Arc<dyn DiagnosticRenderer>> {
  424        cx.try_global::<Self>().map(|g| g.0.clone())
  425    }
  426}
  427
  428impl gpui::Global for GlobalDiagnosticRenderer {}
  429pub fn set_diagnostic_renderer(renderer: impl DiagnosticRenderer + 'static, cx: &mut App) {
  430    cx.set_global(GlobalDiagnosticRenderer(Arc::new(renderer)));
  431}
  432
  433pub struct SearchWithinRange;
  434
  435trait InvalidationRegion {
  436    fn ranges(&self) -> &[Range<Anchor>];
  437}
  438
  439#[derive(Clone, Debug, PartialEq)]
  440pub enum SelectPhase {
  441    Begin {
  442        position: DisplayPoint,
  443        add: bool,
  444        click_count: usize,
  445    },
  446    BeginColumnar {
  447        position: DisplayPoint,
  448        reset: bool,
  449        goal_column: u32,
  450    },
  451    Extend {
  452        position: DisplayPoint,
  453        click_count: usize,
  454    },
  455    Update {
  456        position: DisplayPoint,
  457        goal_column: u32,
  458        scroll_delta: gpui::Point<f32>,
  459    },
  460    End,
  461}
  462
  463#[derive(Clone, Debug)]
  464pub enum SelectMode {
  465    Character,
  466    Word(Range<Anchor>),
  467    Line(Range<Anchor>),
  468    All,
  469}
  470
  471#[derive(Clone, PartialEq, Eq, Debug)]
  472pub enum EditorMode {
  473    SingleLine {
  474        auto_width: bool,
  475    },
  476    AutoHeight {
  477        max_lines: usize,
  478    },
  479    Full {
  480        /// When set to `true`, the editor will scale its UI elements with the buffer font size.
  481        scale_ui_elements_with_buffer_font_size: bool,
  482        /// When set to `true`, the editor will render a background for the active line.
  483        show_active_line_background: bool,
  484        /// When set to `true`, the editor's height will be determined by its content.
  485        sized_by_content: bool,
  486    },
  487    Minimap {
  488        parent: WeakEntity<Editor>,
  489    },
  490}
  491
  492impl EditorMode {
  493    pub fn full() -> Self {
  494        Self::Full {
  495            scale_ui_elements_with_buffer_font_size: true,
  496            show_active_line_background: true,
  497            sized_by_content: false,
  498        }
  499    }
  500
  501    pub fn is_full(&self) -> bool {
  502        matches!(self, Self::Full { .. })
  503    }
  504
  505    fn is_minimap(&self) -> bool {
  506        matches!(self, Self::Minimap { .. })
  507    }
  508}
  509
  510#[derive(Copy, Clone, Debug)]
  511pub enum SoftWrap {
  512    /// Prefer not to wrap at all.
  513    ///
  514    /// Note: this is currently internal, as actually limited by [`crate::MAX_LINE_LEN`] until it wraps.
  515    /// The mode is used inside git diff hunks, where it's seems currently more useful to not wrap as much as possible.
  516    GitDiff,
  517    /// Prefer a single line generally, unless an overly long line is encountered.
  518    None,
  519    /// Soft wrap lines that exceed the editor width.
  520    EditorWidth,
  521    /// Soft wrap lines at the preferred line length.
  522    Column(u32),
  523    /// Soft wrap line at the preferred line length or the editor width (whichever is smaller).
  524    Bounded(u32),
  525}
  526
  527#[derive(Clone)]
  528pub struct EditorStyle {
  529    pub background: Hsla,
  530    pub local_player: PlayerColor,
  531    pub text: TextStyle,
  532    pub scrollbar_width: Pixels,
  533    pub syntax: Arc<SyntaxTheme>,
  534    pub status: StatusColors,
  535    pub inlay_hints_style: HighlightStyle,
  536    pub inline_completion_styles: InlineCompletionStyles,
  537    pub unnecessary_code_fade: f32,
  538    pub show_underlines: bool,
  539}
  540
  541impl Default for EditorStyle {
  542    fn default() -> Self {
  543        Self {
  544            background: Hsla::default(),
  545            local_player: PlayerColor::default(),
  546            text: TextStyle::default(),
  547            scrollbar_width: Pixels::default(),
  548            syntax: Default::default(),
  549            // HACK: Status colors don't have a real default.
  550            // We should look into removing the status colors from the editor
  551            // style and retrieve them directly from the theme.
  552            status: StatusColors::dark(),
  553            inlay_hints_style: HighlightStyle::default(),
  554            inline_completion_styles: InlineCompletionStyles {
  555                insertion: HighlightStyle::default(),
  556                whitespace: HighlightStyle::default(),
  557            },
  558            unnecessary_code_fade: Default::default(),
  559            show_underlines: true,
  560        }
  561    }
  562}
  563
  564pub fn make_inlay_hints_style(cx: &mut App) -> HighlightStyle {
  565    let show_background = language_settings::language_settings(None, None, cx)
  566        .inlay_hints
  567        .show_background;
  568
  569    HighlightStyle {
  570        color: Some(cx.theme().status().hint),
  571        background_color: show_background.then(|| cx.theme().status().hint_background),
  572        ..HighlightStyle::default()
  573    }
  574}
  575
  576pub fn make_suggestion_styles(cx: &mut App) -> InlineCompletionStyles {
  577    InlineCompletionStyles {
  578        insertion: HighlightStyle {
  579            color: Some(cx.theme().status().predictive),
  580            ..HighlightStyle::default()
  581        },
  582        whitespace: HighlightStyle {
  583            background_color: Some(cx.theme().status().created_background),
  584            ..HighlightStyle::default()
  585        },
  586    }
  587}
  588
  589type CompletionId = usize;
  590
  591pub(crate) enum EditDisplayMode {
  592    TabAccept,
  593    DiffPopover,
  594    Inline,
  595}
  596
  597enum InlineCompletion {
  598    Edit {
  599        edits: Vec<(Range<Anchor>, String)>,
  600        edit_preview: Option<EditPreview>,
  601        display_mode: EditDisplayMode,
  602        snapshot: BufferSnapshot,
  603    },
  604    Move {
  605        target: Anchor,
  606        snapshot: BufferSnapshot,
  607    },
  608}
  609
  610struct InlineCompletionState {
  611    inlay_ids: Vec<InlayId>,
  612    completion: InlineCompletion,
  613    completion_id: Option<SharedString>,
  614    invalidation_range: Range<Anchor>,
  615}
  616
  617enum EditPredictionSettings {
  618    Disabled,
  619    Enabled {
  620        show_in_menu: bool,
  621        preview_requires_modifier: bool,
  622    },
  623}
  624
  625enum InlineCompletionHighlight {}
  626
  627#[derive(Debug, Clone)]
  628struct InlineDiagnostic {
  629    message: SharedString,
  630    group_id: usize,
  631    is_primary: bool,
  632    start: Point,
  633    severity: lsp::DiagnosticSeverity,
  634}
  635
  636pub enum MenuInlineCompletionsPolicy {
  637    Never,
  638    ByProvider,
  639}
  640
  641pub enum EditPredictionPreview {
  642    /// Modifier is not pressed
  643    Inactive { released_too_fast: bool },
  644    /// Modifier pressed
  645    Active {
  646        since: Instant,
  647        previous_scroll_position: Option<ScrollAnchor>,
  648    },
  649}
  650
  651impl EditPredictionPreview {
  652    pub fn released_too_fast(&self) -> bool {
  653        match self {
  654            EditPredictionPreview::Inactive { released_too_fast } => *released_too_fast,
  655            EditPredictionPreview::Active { .. } => false,
  656        }
  657    }
  658
  659    pub fn set_previous_scroll_position(&mut self, scroll_position: Option<ScrollAnchor>) {
  660        if let EditPredictionPreview::Active {
  661            previous_scroll_position,
  662            ..
  663        } = self
  664        {
  665            *previous_scroll_position = scroll_position;
  666        }
  667    }
  668}
  669
  670pub struct ContextMenuOptions {
  671    pub min_entries_visible: usize,
  672    pub max_entries_visible: usize,
  673    pub placement: Option<ContextMenuPlacement>,
  674}
  675
  676#[derive(Debug, Clone, PartialEq, Eq)]
  677pub enum ContextMenuPlacement {
  678    Above,
  679    Below,
  680}
  681
  682#[derive(Copy, Clone, Eq, PartialEq, PartialOrd, Ord, Debug, Default)]
  683struct EditorActionId(usize);
  684
  685impl EditorActionId {
  686    pub fn post_inc(&mut self) -> Self {
  687        let answer = self.0;
  688
  689        *self = Self(answer + 1);
  690
  691        Self(answer)
  692    }
  693}
  694
  695// type GetFieldEditorTheme = dyn Fn(&theme::Theme) -> theme::FieldEditor;
  696// type OverrideTextStyle = dyn Fn(&EditorStyle) -> Option<HighlightStyle>;
  697
  698type BackgroundHighlight = (fn(&ThemeColors) -> Hsla, Arc<[Range<Anchor>]>);
  699type GutterHighlight = (fn(&App) -> Hsla, Arc<[Range<Anchor>]>);
  700
  701#[derive(Default)]
  702struct ScrollbarMarkerState {
  703    scrollbar_size: Size<Pixels>,
  704    dirty: bool,
  705    markers: Arc<[PaintQuad]>,
  706    pending_refresh: Option<Task<Result<()>>>,
  707}
  708
  709impl ScrollbarMarkerState {
  710    fn should_refresh(&self, scrollbar_size: Size<Pixels>) -> bool {
  711        self.pending_refresh.is_none() && (self.scrollbar_size != scrollbar_size || self.dirty)
  712    }
  713}
  714
  715#[derive(Clone, Copy, PartialEq, Eq)]
  716pub enum MinimapVisibility {
  717    Disabled,
  718    Enabled(bool),
  719}
  720
  721impl MinimapVisibility {
  722    fn for_mode(mode: &EditorMode, cx: &App) -> Self {
  723        if mode.is_full() {
  724            Self::Enabled(EditorSettings::get_global(cx).minimap.minimap_enabled())
  725        } else {
  726            Self::Disabled
  727        }
  728    }
  729
  730    fn disabled(&self) -> bool {
  731        match *self {
  732            Self::Disabled => true,
  733            _ => false,
  734        }
  735    }
  736
  737    fn visible(&self) -> bool {
  738        match *self {
  739            Self::Enabled(visible) => visible,
  740            _ => false,
  741        }
  742    }
  743
  744    fn toggle_visibility(&self) -> Self {
  745        match *self {
  746            Self::Enabled(visible) => Self::Enabled(!visible),
  747            Self::Disabled => Self::Disabled,
  748        }
  749    }
  750}
  751
  752#[derive(Clone, Debug)]
  753struct RunnableTasks {
  754    templates: Vec<(TaskSourceKind, TaskTemplate)>,
  755    offset: multi_buffer::Anchor,
  756    // We need the column at which the task context evaluation should take place (when we're spawning it via gutter).
  757    column: u32,
  758    // Values of all named captures, including those starting with '_'
  759    extra_variables: HashMap<String, String>,
  760    // Full range of the tagged region. We use it to determine which `extra_variables` to grab for context resolution in e.g. a modal.
  761    context_range: Range<BufferOffset>,
  762}
  763
  764impl RunnableTasks {
  765    fn resolve<'a>(
  766        &'a self,
  767        cx: &'a task::TaskContext,
  768    ) -> impl Iterator<Item = (TaskSourceKind, ResolvedTask)> + 'a {
  769        self.templates.iter().filter_map(|(kind, template)| {
  770            template
  771                .resolve_task(&kind.to_id_base(), cx)
  772                .map(|task| (kind.clone(), task))
  773        })
  774    }
  775}
  776
  777#[derive(Clone)]
  778struct ResolvedTasks {
  779    templates: SmallVec<[(TaskSourceKind, ResolvedTask); 1]>,
  780    position: Anchor,
  781}
  782
  783#[derive(Copy, Clone, Debug, PartialEq, PartialOrd)]
  784struct BufferOffset(usize);
  785
  786// Addons allow storing per-editor state in other crates (e.g. Vim)
  787pub trait Addon: 'static {
  788    fn extend_key_context(&self, _: &mut KeyContext, _: &App) {}
  789
  790    fn render_buffer_header_controls(
  791        &self,
  792        _: &ExcerptInfo,
  793        _: &Window,
  794        _: &App,
  795    ) -> Option<AnyElement> {
  796        None
  797    }
  798
  799    fn to_any(&self) -> &dyn std::any::Any;
  800
  801    fn to_any_mut(&mut self) -> Option<&mut dyn std::any::Any> {
  802        None
  803    }
  804}
  805
  806/// A set of caret positions, registered when the editor was edited.
  807pub struct ChangeList {
  808    changes: Vec<Vec<Anchor>>,
  809    /// Currently "selected" change.
  810    position: Option<usize>,
  811}
  812
  813impl ChangeList {
  814    pub fn new() -> Self {
  815        Self {
  816            changes: Vec::new(),
  817            position: None,
  818        }
  819    }
  820
  821    /// Moves to the next change in the list (based on the direction given) and returns the caret positions for the next change.
  822    /// If reaches the end of the list in the direction, returns the corresponding change until called for a different direction.
  823    pub fn next_change(&mut self, count: usize, direction: Direction) -> Option<&[Anchor]> {
  824        if self.changes.is_empty() {
  825            return None;
  826        }
  827
  828        let prev = self.position.unwrap_or(self.changes.len());
  829        let next = if direction == Direction::Prev {
  830            prev.saturating_sub(count)
  831        } else {
  832            (prev + count).min(self.changes.len() - 1)
  833        };
  834        self.position = Some(next);
  835        self.changes.get(next).map(|anchors| anchors.as_slice())
  836    }
  837
  838    /// Adds a new change to the list, resetting the change list position.
  839    pub fn push_to_change_list(&mut self, pop_state: bool, new_positions: Vec<Anchor>) {
  840        self.position.take();
  841        if pop_state {
  842            self.changes.pop();
  843        }
  844        self.changes.push(new_positions.clone());
  845    }
  846
  847    pub fn last(&self) -> Option<&[Anchor]> {
  848        self.changes.last().map(|anchors| anchors.as_slice())
  849    }
  850}
  851
  852#[derive(Clone)]
  853struct InlineBlamePopoverState {
  854    scroll_handle: ScrollHandle,
  855    commit_message: Option<ParsedCommitMessage>,
  856    markdown: Entity<Markdown>,
  857}
  858
  859struct InlineBlamePopover {
  860    position: gpui::Point<Pixels>,
  861    show_task: Option<Task<()>>,
  862    hide_task: Option<Task<()>>,
  863    popover_bounds: Option<Bounds<Pixels>>,
  864    popover_state: InlineBlamePopoverState,
  865}
  866
  867/// Represents a breakpoint indicator that shows up when hovering over lines in the gutter that don't have
  868/// a breakpoint on them.
  869#[derive(Clone, Copy, Debug)]
  870struct PhantomBreakpointIndicator {
  871    display_row: DisplayRow,
  872    /// There's a small debounce between hovering over the line and showing the indicator.
  873    /// We don't want to show the indicator when moving the mouse from editor to e.g. project panel.
  874    is_active: bool,
  875    collides_with_existing_breakpoint: bool,
  876}
  877/// Zed's primary implementation of text input, allowing users to edit a [`MultiBuffer`].
  878///
  879/// See the [module level documentation](self) for more information.
  880pub struct Editor {
  881    focus_handle: FocusHandle,
  882    last_focused_descendant: Option<WeakFocusHandle>,
  883    /// The text buffer being edited
  884    buffer: Entity<MultiBuffer>,
  885    /// Map of how text in the buffer should be displayed.
  886    /// Handles soft wraps, folds, fake inlay text insertions, etc.
  887    pub display_map: Entity<DisplayMap>,
  888    pub selections: SelectionsCollection,
  889    pub scroll_manager: ScrollManager,
  890    /// When inline assist editors are linked, they all render cursors because
  891    /// typing enters text into each of them, even the ones that aren't focused.
  892    pub(crate) show_cursor_when_unfocused: bool,
  893    columnar_selection_tail: Option<Anchor>,
  894    add_selections_state: Option<AddSelectionsState>,
  895    select_next_state: Option<SelectNextState>,
  896    select_prev_state: Option<SelectNextState>,
  897    selection_history: SelectionHistory,
  898    autoclose_regions: Vec<AutocloseRegion>,
  899    snippet_stack: InvalidationStack<SnippetState>,
  900    select_syntax_node_history: SelectSyntaxNodeHistory,
  901    ime_transaction: Option<TransactionId>,
  902    pub diagnostics_max_severity: DiagnosticSeverity,
  903    active_diagnostics: ActiveDiagnostic,
  904    show_inline_diagnostics: bool,
  905    inline_diagnostics_update: Task<()>,
  906    inline_diagnostics_enabled: bool,
  907    inline_diagnostics: Vec<(Anchor, InlineDiagnostic)>,
  908    soft_wrap_mode_override: Option<language_settings::SoftWrap>,
  909    hard_wrap: Option<usize>,
  910
  911    // TODO: make this a access method
  912    pub project: Option<Entity<Project>>,
  913    semantics_provider: Option<Rc<dyn SemanticsProvider>>,
  914    completion_provider: Option<Box<dyn CompletionProvider>>,
  915    collaboration_hub: Option<Box<dyn CollaborationHub>>,
  916    blink_manager: Entity<BlinkManager>,
  917    show_cursor_names: bool,
  918    hovered_cursors: HashMap<HoveredCursor, Task<()>>,
  919    pub show_local_selections: bool,
  920    mode: EditorMode,
  921    show_breadcrumbs: bool,
  922    show_gutter: bool,
  923    show_scrollbars: bool,
  924    minimap_visibility: MinimapVisibility,
  925    disable_expand_excerpt_buttons: bool,
  926    show_line_numbers: Option<bool>,
  927    use_relative_line_numbers: Option<bool>,
  928    show_git_diff_gutter: Option<bool>,
  929    show_code_actions: Option<bool>,
  930    show_runnables: Option<bool>,
  931    show_breakpoints: Option<bool>,
  932    show_wrap_guides: Option<bool>,
  933    show_indent_guides: Option<bool>,
  934    placeholder_text: Option<Arc<str>>,
  935    highlight_order: usize,
  936    highlighted_rows: HashMap<TypeId, Vec<RowHighlight>>,
  937    background_highlights: TreeMap<TypeId, BackgroundHighlight>,
  938    gutter_highlights: TreeMap<TypeId, GutterHighlight>,
  939    scrollbar_marker_state: ScrollbarMarkerState,
  940    active_indent_guides_state: ActiveIndentGuidesState,
  941    nav_history: Option<ItemNavHistory>,
  942    context_menu: RefCell<Option<CodeContextMenu>>,
  943    context_menu_options: Option<ContextMenuOptions>,
  944    mouse_context_menu: Option<MouseContextMenu>,
  945    completion_tasks: Vec<(CompletionId, Task<Option<()>>)>,
  946    inline_blame_popover: Option<InlineBlamePopover>,
  947    signature_help_state: SignatureHelpState,
  948    auto_signature_help: Option<bool>,
  949    find_all_references_task_sources: Vec<Anchor>,
  950    next_completion_id: CompletionId,
  951    available_code_actions: Option<(Location, Rc<[AvailableCodeAction]>)>,
  952    code_actions_task: Option<Task<Result<()>>>,
  953    quick_selection_highlight_task: Option<(Range<Anchor>, Task<()>)>,
  954    debounced_selection_highlight_task: Option<(Range<Anchor>, Task<()>)>,
  955    document_highlights_task: Option<Task<()>>,
  956    linked_editing_range_task: Option<Task<Option<()>>>,
  957    linked_edit_ranges: linked_editing_ranges::LinkedEditingRanges,
  958    pending_rename: Option<RenameState>,
  959    searchable: bool,
  960    cursor_shape: CursorShape,
  961    current_line_highlight: Option<CurrentLineHighlight>,
  962    collapse_matches: bool,
  963    autoindent_mode: Option<AutoindentMode>,
  964    workspace: Option<(WeakEntity<Workspace>, Option<WorkspaceId>)>,
  965    input_enabled: bool,
  966    use_modal_editing: bool,
  967    read_only: bool,
  968    leader_id: Option<CollaboratorId>,
  969    remote_id: Option<ViewId>,
  970    pub hover_state: HoverState,
  971    pending_mouse_down: Option<Rc<RefCell<Option<MouseDownEvent>>>>,
  972    gutter_hovered: bool,
  973    hovered_link_state: Option<HoveredLinkState>,
  974    edit_prediction_provider: Option<RegisteredInlineCompletionProvider>,
  975    code_action_providers: Vec<Rc<dyn CodeActionProvider>>,
  976    active_inline_completion: Option<InlineCompletionState>,
  977    /// Used to prevent flickering as the user types while the menu is open
  978    stale_inline_completion_in_menu: Option<InlineCompletionState>,
  979    edit_prediction_settings: EditPredictionSettings,
  980    inline_completions_hidden_for_vim_mode: bool,
  981    show_inline_completions_override: Option<bool>,
  982    menu_inline_completions_policy: MenuInlineCompletionsPolicy,
  983    edit_prediction_preview: EditPredictionPreview,
  984    edit_prediction_indent_conflict: bool,
  985    edit_prediction_requires_modifier_in_indent_conflict: bool,
  986    inlay_hint_cache: InlayHintCache,
  987    next_inlay_id: usize,
  988    _subscriptions: Vec<Subscription>,
  989    pixel_position_of_newest_cursor: Option<gpui::Point<Pixels>>,
  990    gutter_dimensions: GutterDimensions,
  991    style: Option<EditorStyle>,
  992    text_style_refinement: Option<TextStyleRefinement>,
  993    next_editor_action_id: EditorActionId,
  994    editor_actions:
  995        Rc<RefCell<BTreeMap<EditorActionId, Box<dyn Fn(&mut Window, &mut Context<Self>)>>>>,
  996    use_autoclose: bool,
  997    use_auto_surround: bool,
  998    auto_replace_emoji_shortcode: bool,
  999    jsx_tag_auto_close_enabled_in_any_buffer: bool,
 1000    show_git_blame_gutter: bool,
 1001    show_git_blame_inline: bool,
 1002    show_git_blame_inline_delay_task: Option<Task<()>>,
 1003    git_blame_inline_enabled: bool,
 1004    render_diff_hunk_controls: RenderDiffHunkControlsFn,
 1005    serialize_dirty_buffers: bool,
 1006    show_selection_menu: Option<bool>,
 1007    blame: Option<Entity<GitBlame>>,
 1008    blame_subscription: Option<Subscription>,
 1009    custom_context_menu: Option<
 1010        Box<
 1011            dyn 'static
 1012                + Fn(
 1013                    &mut Self,
 1014                    DisplayPoint,
 1015                    &mut Window,
 1016                    &mut Context<Self>,
 1017                ) -> Option<Entity<ui::ContextMenu>>,
 1018        >,
 1019    >,
 1020    last_bounds: Option<Bounds<Pixels>>,
 1021    last_position_map: Option<Rc<PositionMap>>,
 1022    expect_bounds_change: Option<Bounds<Pixels>>,
 1023    tasks: BTreeMap<(BufferId, BufferRow), RunnableTasks>,
 1024    tasks_update_task: Option<Task<()>>,
 1025    breakpoint_store: Option<Entity<BreakpointStore>>,
 1026    gutter_breakpoint_indicator: (Option<PhantomBreakpointIndicator>, Option<Task<()>>),
 1027    in_project_search: bool,
 1028    previous_search_ranges: Option<Arc<[Range<Anchor>]>>,
 1029    breadcrumb_header: Option<String>,
 1030    focused_block: Option<FocusedBlock>,
 1031    next_scroll_position: NextScrollCursorCenterTopBottom,
 1032    addons: HashMap<TypeId, Box<dyn Addon>>,
 1033    registered_buffers: HashMap<BufferId, OpenLspBufferHandle>,
 1034    load_diff_task: Option<Shared<Task<()>>>,
 1035    /// Whether we are temporarily displaying a diff other than git's
 1036    temporary_diff_override: bool,
 1037    selection_mark_mode: bool,
 1038    toggle_fold_multiple_buffers: Task<()>,
 1039    _scroll_cursor_center_top_bottom_task: Task<()>,
 1040    serialize_selections: Task<()>,
 1041    serialize_folds: Task<()>,
 1042    mouse_cursor_hidden: bool,
 1043    minimap: Option<Entity<Self>>,
 1044    hide_mouse_mode: HideMouseMode,
 1045    pub change_list: ChangeList,
 1046    inline_value_cache: InlineValueCache,
 1047}
 1048
 1049#[derive(Copy, Clone, Debug, PartialEq, Eq, Default)]
 1050enum NextScrollCursorCenterTopBottom {
 1051    #[default]
 1052    Center,
 1053    Top,
 1054    Bottom,
 1055}
 1056
 1057impl NextScrollCursorCenterTopBottom {
 1058    fn next(&self) -> Self {
 1059        match self {
 1060            Self::Center => Self::Top,
 1061            Self::Top => Self::Bottom,
 1062            Self::Bottom => Self::Center,
 1063        }
 1064    }
 1065}
 1066
 1067#[derive(Clone)]
 1068pub struct EditorSnapshot {
 1069    pub mode: EditorMode,
 1070    show_gutter: bool,
 1071    show_line_numbers: Option<bool>,
 1072    show_git_diff_gutter: Option<bool>,
 1073    show_runnables: Option<bool>,
 1074    show_breakpoints: Option<bool>,
 1075    git_blame_gutter_max_author_length: Option<usize>,
 1076    pub display_snapshot: DisplaySnapshot,
 1077    pub placeholder_text: Option<Arc<str>>,
 1078    is_focused: bool,
 1079    scroll_anchor: ScrollAnchor,
 1080    ongoing_scroll: OngoingScroll,
 1081    current_line_highlight: CurrentLineHighlight,
 1082    gutter_hovered: bool,
 1083}
 1084
 1085#[derive(Default, Debug, Clone, Copy)]
 1086pub struct GutterDimensions {
 1087    pub left_padding: Pixels,
 1088    pub right_padding: Pixels,
 1089    pub width: Pixels,
 1090    pub margin: Pixels,
 1091    pub git_blame_entries_width: Option<Pixels>,
 1092}
 1093
 1094impl GutterDimensions {
 1095    fn default_with_margin(font_id: FontId, font_size: Pixels, cx: &App) -> Self {
 1096        Self {
 1097            margin: Self::default_gutter_margin(font_id, font_size, cx),
 1098            ..Default::default()
 1099        }
 1100    }
 1101
 1102    fn default_gutter_margin(font_id: FontId, font_size: Pixels, cx: &App) -> Pixels {
 1103        -cx.text_system().descent(font_id, font_size)
 1104    }
 1105    /// The full width of the space taken up by the gutter.
 1106    pub fn full_width(&self) -> Pixels {
 1107        self.margin + self.width
 1108    }
 1109
 1110    /// The width of the space reserved for the fold indicators,
 1111    /// use alongside 'justify_end' and `gutter_width` to
 1112    /// right align content with the line numbers
 1113    pub fn fold_area_width(&self) -> Pixels {
 1114        self.margin + self.right_padding
 1115    }
 1116}
 1117
 1118#[derive(Debug)]
 1119pub struct RemoteSelection {
 1120    pub replica_id: ReplicaId,
 1121    pub selection: Selection<Anchor>,
 1122    pub cursor_shape: CursorShape,
 1123    pub collaborator_id: CollaboratorId,
 1124    pub line_mode: bool,
 1125    pub user_name: Option<SharedString>,
 1126    pub color: PlayerColor,
 1127}
 1128
 1129#[derive(Clone, Debug)]
 1130struct SelectionHistoryEntry {
 1131    selections: Arc<[Selection<Anchor>]>,
 1132    select_next_state: Option<SelectNextState>,
 1133    select_prev_state: Option<SelectNextState>,
 1134    add_selections_state: Option<AddSelectionsState>,
 1135}
 1136
 1137enum SelectionHistoryMode {
 1138    Normal,
 1139    Undoing,
 1140    Redoing,
 1141}
 1142
 1143#[derive(Clone, PartialEq, Eq, Hash)]
 1144struct HoveredCursor {
 1145    replica_id: u16,
 1146    selection_id: usize,
 1147}
 1148
 1149impl Default for SelectionHistoryMode {
 1150    fn default() -> Self {
 1151        Self::Normal
 1152    }
 1153}
 1154
 1155#[derive(Default)]
 1156struct SelectionHistory {
 1157    #[allow(clippy::type_complexity)]
 1158    selections_by_transaction:
 1159        HashMap<TransactionId, (Arc<[Selection<Anchor>]>, Option<Arc<[Selection<Anchor>]>>)>,
 1160    mode: SelectionHistoryMode,
 1161    undo_stack: VecDeque<SelectionHistoryEntry>,
 1162    redo_stack: VecDeque<SelectionHistoryEntry>,
 1163}
 1164
 1165impl SelectionHistory {
 1166    fn insert_transaction(
 1167        &mut self,
 1168        transaction_id: TransactionId,
 1169        selections: Arc<[Selection<Anchor>]>,
 1170    ) {
 1171        self.selections_by_transaction
 1172            .insert(transaction_id, (selections, None));
 1173    }
 1174
 1175    #[allow(clippy::type_complexity)]
 1176    fn transaction(
 1177        &self,
 1178        transaction_id: TransactionId,
 1179    ) -> Option<&(Arc<[Selection<Anchor>]>, Option<Arc<[Selection<Anchor>]>>)> {
 1180        self.selections_by_transaction.get(&transaction_id)
 1181    }
 1182
 1183    #[allow(clippy::type_complexity)]
 1184    fn transaction_mut(
 1185        &mut self,
 1186        transaction_id: TransactionId,
 1187    ) -> Option<&mut (Arc<[Selection<Anchor>]>, Option<Arc<[Selection<Anchor>]>>)> {
 1188        self.selections_by_transaction.get_mut(&transaction_id)
 1189    }
 1190
 1191    fn push(&mut self, entry: SelectionHistoryEntry) {
 1192        if !entry.selections.is_empty() {
 1193            match self.mode {
 1194                SelectionHistoryMode::Normal => {
 1195                    self.push_undo(entry);
 1196                    self.redo_stack.clear();
 1197                }
 1198                SelectionHistoryMode::Undoing => self.push_redo(entry),
 1199                SelectionHistoryMode::Redoing => self.push_undo(entry),
 1200            }
 1201        }
 1202    }
 1203
 1204    fn push_undo(&mut self, entry: SelectionHistoryEntry) {
 1205        if self
 1206            .undo_stack
 1207            .back()
 1208            .map_or(true, |e| e.selections != entry.selections)
 1209        {
 1210            self.undo_stack.push_back(entry);
 1211            if self.undo_stack.len() > MAX_SELECTION_HISTORY_LEN {
 1212                self.undo_stack.pop_front();
 1213            }
 1214        }
 1215    }
 1216
 1217    fn push_redo(&mut self, entry: SelectionHistoryEntry) {
 1218        if self
 1219            .redo_stack
 1220            .back()
 1221            .map_or(true, |e| e.selections != entry.selections)
 1222        {
 1223            self.redo_stack.push_back(entry);
 1224            if self.redo_stack.len() > MAX_SELECTION_HISTORY_LEN {
 1225                self.redo_stack.pop_front();
 1226            }
 1227        }
 1228    }
 1229}
 1230
 1231#[derive(Clone, Copy)]
 1232pub struct RowHighlightOptions {
 1233    pub autoscroll: bool,
 1234    pub include_gutter: bool,
 1235}
 1236
 1237impl Default for RowHighlightOptions {
 1238    fn default() -> Self {
 1239        Self {
 1240            autoscroll: Default::default(),
 1241            include_gutter: true,
 1242        }
 1243    }
 1244}
 1245
 1246struct RowHighlight {
 1247    index: usize,
 1248    range: Range<Anchor>,
 1249    color: Hsla,
 1250    options: RowHighlightOptions,
 1251    type_id: TypeId,
 1252}
 1253
 1254#[derive(Clone, Debug)]
 1255struct AddSelectionsState {
 1256    above: bool,
 1257    stack: Vec<usize>,
 1258}
 1259
 1260#[derive(Clone)]
 1261struct SelectNextState {
 1262    query: AhoCorasick,
 1263    wordwise: bool,
 1264    done: bool,
 1265}
 1266
 1267impl std::fmt::Debug for SelectNextState {
 1268    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
 1269        f.debug_struct(std::any::type_name::<Self>())
 1270            .field("wordwise", &self.wordwise)
 1271            .field("done", &self.done)
 1272            .finish()
 1273    }
 1274}
 1275
 1276#[derive(Debug)]
 1277struct AutocloseRegion {
 1278    selection_id: usize,
 1279    range: Range<Anchor>,
 1280    pair: BracketPair,
 1281}
 1282
 1283#[derive(Debug)]
 1284struct SnippetState {
 1285    ranges: Vec<Vec<Range<Anchor>>>,
 1286    active_index: usize,
 1287    choices: Vec<Option<Vec<String>>>,
 1288}
 1289
 1290#[doc(hidden)]
 1291pub struct RenameState {
 1292    pub range: Range<Anchor>,
 1293    pub old_name: Arc<str>,
 1294    pub editor: Entity<Editor>,
 1295    block_id: CustomBlockId,
 1296}
 1297
 1298struct InvalidationStack<T>(Vec<T>);
 1299
 1300struct RegisteredInlineCompletionProvider {
 1301    provider: Arc<dyn InlineCompletionProviderHandle>,
 1302    _subscription: Subscription,
 1303}
 1304
 1305#[derive(Debug, PartialEq, Eq)]
 1306pub struct ActiveDiagnosticGroup {
 1307    pub active_range: Range<Anchor>,
 1308    pub active_message: String,
 1309    pub group_id: usize,
 1310    pub blocks: HashSet<CustomBlockId>,
 1311}
 1312
 1313#[derive(Debug, PartialEq, Eq)]
 1314#[allow(clippy::large_enum_variant)]
 1315pub(crate) enum ActiveDiagnostic {
 1316    None,
 1317    All,
 1318    Group(ActiveDiagnosticGroup),
 1319}
 1320
 1321#[derive(Serialize, Deserialize, Clone, Debug)]
 1322pub struct ClipboardSelection {
 1323    /// The number of bytes in this selection.
 1324    pub len: usize,
 1325    /// Whether this was a full-line selection.
 1326    pub is_entire_line: bool,
 1327    /// The indentation of the first line when this content was originally copied.
 1328    pub first_line_indent: u32,
 1329}
 1330
 1331// selections, scroll behavior, was newest selection reversed
 1332type SelectSyntaxNodeHistoryState = (
 1333    Box<[Selection<usize>]>,
 1334    SelectSyntaxNodeScrollBehavior,
 1335    bool,
 1336);
 1337
 1338#[derive(Default)]
 1339struct SelectSyntaxNodeHistory {
 1340    stack: Vec<SelectSyntaxNodeHistoryState>,
 1341    // disable temporarily to allow changing selections without losing the stack
 1342    pub disable_clearing: bool,
 1343}
 1344
 1345impl SelectSyntaxNodeHistory {
 1346    pub fn try_clear(&mut self) {
 1347        if !self.disable_clearing {
 1348            self.stack.clear();
 1349        }
 1350    }
 1351
 1352    pub fn push(&mut self, selection: SelectSyntaxNodeHistoryState) {
 1353        self.stack.push(selection);
 1354    }
 1355
 1356    pub fn pop(&mut self) -> Option<SelectSyntaxNodeHistoryState> {
 1357        self.stack.pop()
 1358    }
 1359}
 1360
 1361enum SelectSyntaxNodeScrollBehavior {
 1362    CursorTop,
 1363    FitSelection,
 1364    CursorBottom,
 1365}
 1366
 1367#[derive(Debug)]
 1368pub(crate) struct NavigationData {
 1369    cursor_anchor: Anchor,
 1370    cursor_position: Point,
 1371    scroll_anchor: ScrollAnchor,
 1372    scroll_top_row: u32,
 1373}
 1374
 1375#[derive(Debug, Clone, Copy, PartialEq, Eq)]
 1376pub enum GotoDefinitionKind {
 1377    Symbol,
 1378    Declaration,
 1379    Type,
 1380    Implementation,
 1381}
 1382
 1383#[derive(Debug, Clone)]
 1384enum InlayHintRefreshReason {
 1385    ModifiersChanged(bool),
 1386    Toggle(bool),
 1387    SettingsChange(InlayHintSettings),
 1388    NewLinesShown,
 1389    BufferEdited(HashSet<Arc<Language>>),
 1390    RefreshRequested,
 1391    ExcerptsRemoved(Vec<ExcerptId>),
 1392}
 1393
 1394impl InlayHintRefreshReason {
 1395    fn description(&self) -> &'static str {
 1396        match self {
 1397            Self::ModifiersChanged(_) => "modifiers changed",
 1398            Self::Toggle(_) => "toggle",
 1399            Self::SettingsChange(_) => "settings change",
 1400            Self::NewLinesShown => "new lines shown",
 1401            Self::BufferEdited(_) => "buffer edited",
 1402            Self::RefreshRequested => "refresh requested",
 1403            Self::ExcerptsRemoved(_) => "excerpts removed",
 1404        }
 1405    }
 1406}
 1407
 1408pub enum FormatTarget {
 1409    Buffers,
 1410    Ranges(Vec<Range<MultiBufferPoint>>),
 1411}
 1412
 1413pub(crate) struct FocusedBlock {
 1414    id: BlockId,
 1415    focus_handle: WeakFocusHandle,
 1416}
 1417
 1418#[derive(Clone)]
 1419enum JumpData {
 1420    MultiBufferRow {
 1421        row: MultiBufferRow,
 1422        line_offset_from_top: u32,
 1423    },
 1424    MultiBufferPoint {
 1425        excerpt_id: ExcerptId,
 1426        position: Point,
 1427        anchor: text::Anchor,
 1428        line_offset_from_top: u32,
 1429    },
 1430}
 1431
 1432pub enum MultibufferSelectionMode {
 1433    First,
 1434    All,
 1435}
 1436
 1437#[derive(Clone, Copy, Debug, Default)]
 1438pub struct RewrapOptions {
 1439    pub override_language_settings: bool,
 1440    pub preserve_existing_whitespace: bool,
 1441}
 1442
 1443impl Editor {
 1444    pub fn single_line(window: &mut Window, cx: &mut Context<Self>) -> Self {
 1445        let buffer = cx.new(|cx| Buffer::local("", cx));
 1446        let buffer = cx.new(|cx| MultiBuffer::singleton(buffer, cx));
 1447        Self::new(
 1448            EditorMode::SingleLine { auto_width: false },
 1449            buffer,
 1450            None,
 1451            window,
 1452            cx,
 1453        )
 1454    }
 1455
 1456    pub fn multi_line(window: &mut Window, cx: &mut Context<Self>) -> Self {
 1457        let buffer = cx.new(|cx| Buffer::local("", cx));
 1458        let buffer = cx.new(|cx| MultiBuffer::singleton(buffer, cx));
 1459        Self::new(EditorMode::full(), buffer, None, window, cx)
 1460    }
 1461
 1462    pub fn auto_width(window: &mut Window, cx: &mut Context<Self>) -> Self {
 1463        let buffer = cx.new(|cx| Buffer::local("", cx));
 1464        let buffer = cx.new(|cx| MultiBuffer::singleton(buffer, cx));
 1465        Self::new(
 1466            EditorMode::SingleLine { auto_width: true },
 1467            buffer,
 1468            None,
 1469            window,
 1470            cx,
 1471        )
 1472    }
 1473
 1474    pub fn auto_height(max_lines: usize, window: &mut Window, cx: &mut Context<Self>) -> Self {
 1475        let buffer = cx.new(|cx| Buffer::local("", cx));
 1476        let buffer = cx.new(|cx| MultiBuffer::singleton(buffer, cx));
 1477        Self::new(
 1478            EditorMode::AutoHeight { max_lines },
 1479            buffer,
 1480            None,
 1481            window,
 1482            cx,
 1483        )
 1484    }
 1485
 1486    pub fn for_buffer(
 1487        buffer: Entity<Buffer>,
 1488        project: Option<Entity<Project>>,
 1489        window: &mut Window,
 1490        cx: &mut Context<Self>,
 1491    ) -> Self {
 1492        let buffer = cx.new(|cx| MultiBuffer::singleton(buffer, cx));
 1493        Self::new(EditorMode::full(), buffer, project, window, cx)
 1494    }
 1495
 1496    pub fn for_multibuffer(
 1497        buffer: Entity<MultiBuffer>,
 1498        project: Option<Entity<Project>>,
 1499        window: &mut Window,
 1500        cx: &mut Context<Self>,
 1501    ) -> Self {
 1502        Self::new(EditorMode::full(), buffer, project, window, cx)
 1503    }
 1504
 1505    pub fn clone(&self, window: &mut Window, cx: &mut Context<Self>) -> Self {
 1506        let mut clone = Self::new(
 1507            self.mode.clone(),
 1508            self.buffer.clone(),
 1509            self.project.clone(),
 1510            window,
 1511            cx,
 1512        );
 1513        self.display_map.update(cx, |display_map, cx| {
 1514            let snapshot = display_map.snapshot(cx);
 1515            clone.display_map.update(cx, |display_map, cx| {
 1516                display_map.set_state(&snapshot, cx);
 1517            });
 1518        });
 1519        clone.folds_did_change(cx);
 1520        clone.selections.clone_state(&self.selections);
 1521        clone.scroll_manager.clone_state(&self.scroll_manager);
 1522        clone.searchable = self.searchable;
 1523        clone.read_only = self.read_only;
 1524        clone
 1525    }
 1526
 1527    pub fn new(
 1528        mode: EditorMode,
 1529        buffer: Entity<MultiBuffer>,
 1530        project: Option<Entity<Project>>,
 1531        window: &mut Window,
 1532        cx: &mut Context<Self>,
 1533    ) -> Self {
 1534        Editor::new_internal(mode, buffer, project, None, window, cx)
 1535    }
 1536
 1537    fn new_internal(
 1538        mode: EditorMode,
 1539        buffer: Entity<MultiBuffer>,
 1540        project: Option<Entity<Project>>,
 1541        display_map: Option<Entity<DisplayMap>>,
 1542        window: &mut Window,
 1543        cx: &mut Context<Self>,
 1544    ) -> Self {
 1545        debug_assert!(
 1546            display_map.is_none() || mode.is_minimap(),
 1547            "Providing a display map for a new editor is only intended for the minimap and might have unindended side effects otherwise!"
 1548        );
 1549
 1550        let full_mode = mode.is_full();
 1551        let diagnostics_max_severity = if full_mode {
 1552            EditorSettings::get_global(cx)
 1553                .diagnostics_max_severity
 1554                .unwrap_or(DiagnosticSeverity::Hint)
 1555        } else {
 1556            DiagnosticSeverity::Off
 1557        };
 1558        let style = window.text_style();
 1559        let font_size = style.font_size.to_pixels(window.rem_size());
 1560        let editor = cx.entity().downgrade();
 1561        let fold_placeholder = FoldPlaceholder {
 1562            constrain_width: true,
 1563            render: Arc::new(move |fold_id, fold_range, cx| {
 1564                let editor = editor.clone();
 1565                div()
 1566                    .id(fold_id)
 1567                    .bg(cx.theme().colors().ghost_element_background)
 1568                    .hover(|style| style.bg(cx.theme().colors().ghost_element_hover))
 1569                    .active(|style| style.bg(cx.theme().colors().ghost_element_active))
 1570                    .rounded_xs()
 1571                    .size_full()
 1572                    .cursor_pointer()
 1573                    .child("")
 1574                    .on_mouse_down(MouseButton::Left, |_, _, cx| cx.stop_propagation())
 1575                    .on_click(move |_, _window, cx| {
 1576                        editor
 1577                            .update(cx, |editor, cx| {
 1578                                editor.unfold_ranges(
 1579                                    &[fold_range.start..fold_range.end],
 1580                                    true,
 1581                                    false,
 1582                                    cx,
 1583                                );
 1584                                cx.stop_propagation();
 1585                            })
 1586                            .ok();
 1587                    })
 1588                    .into_any()
 1589            }),
 1590            merge_adjacent: true,
 1591            ..FoldPlaceholder::default()
 1592        };
 1593        let display_map = display_map.unwrap_or_else(|| {
 1594            cx.new(|cx| {
 1595                DisplayMap::new(
 1596                    buffer.clone(),
 1597                    style.font(),
 1598                    font_size,
 1599                    None,
 1600                    FILE_HEADER_HEIGHT,
 1601                    MULTI_BUFFER_EXCERPT_HEADER_HEIGHT,
 1602                    fold_placeholder,
 1603                    diagnostics_max_severity,
 1604                    cx,
 1605                )
 1606            })
 1607        });
 1608
 1609        let selections = SelectionsCollection::new(display_map.clone(), buffer.clone());
 1610
 1611        let blink_manager = cx.new(|cx| BlinkManager::new(CURSOR_BLINK_INTERVAL, cx));
 1612
 1613        let soft_wrap_mode_override = matches!(mode, EditorMode::SingleLine { .. })
 1614            .then(|| language_settings::SoftWrap::None);
 1615
 1616        let mut project_subscriptions = Vec::new();
 1617        if mode.is_full() {
 1618            if let Some(project) = project.as_ref() {
 1619                project_subscriptions.push(cx.subscribe_in(
 1620                    project,
 1621                    window,
 1622                    |editor, _, event, window, cx| match event {
 1623                        project::Event::RefreshCodeLens => {
 1624                            // we always query lens with actions, without storing them, always refreshing them
 1625                        }
 1626                        project::Event::RefreshInlayHints => {
 1627                            editor
 1628                                .refresh_inlay_hints(InlayHintRefreshReason::RefreshRequested, cx);
 1629                        }
 1630                        project::Event::SnippetEdit(id, snippet_edits) => {
 1631                            if let Some(buffer) = editor.buffer.read(cx).buffer(*id) {
 1632                                let focus_handle = editor.focus_handle(cx);
 1633                                if focus_handle.is_focused(window) {
 1634                                    let snapshot = buffer.read(cx).snapshot();
 1635                                    for (range, snippet) in snippet_edits {
 1636                                        let editor_range =
 1637                                            language::range_from_lsp(*range).to_offset(&snapshot);
 1638                                        editor
 1639                                            .insert_snippet(
 1640                                                &[editor_range],
 1641                                                snippet.clone(),
 1642                                                window,
 1643                                                cx,
 1644                                            )
 1645                                            .ok();
 1646                                    }
 1647                                }
 1648                            }
 1649                        }
 1650                        _ => {}
 1651                    },
 1652                ));
 1653                if let Some(task_inventory) = project
 1654                    .read(cx)
 1655                    .task_store()
 1656                    .read(cx)
 1657                    .task_inventory()
 1658                    .cloned()
 1659                {
 1660                    project_subscriptions.push(cx.observe_in(
 1661                        &task_inventory,
 1662                        window,
 1663                        |editor, _, window, cx| {
 1664                            editor.tasks_update_task = Some(editor.refresh_runnables(window, cx));
 1665                        },
 1666                    ));
 1667                };
 1668
 1669                project_subscriptions.push(cx.subscribe_in(
 1670                    &project.read(cx).breakpoint_store(),
 1671                    window,
 1672                    |editor, _, event, window, cx| match event {
 1673                        BreakpointStoreEvent::ClearDebugLines => {
 1674                            editor.clear_row_highlights::<ActiveDebugLine>();
 1675                            editor.refresh_inline_values(cx);
 1676                        }
 1677                        BreakpointStoreEvent::SetDebugLine => {
 1678                            if editor.go_to_active_debug_line(window, cx) {
 1679                                cx.stop_propagation();
 1680                            }
 1681
 1682                            editor.refresh_inline_values(cx);
 1683                        }
 1684                        _ => {}
 1685                    },
 1686                ));
 1687            }
 1688        }
 1689
 1690        let buffer_snapshot = buffer.read(cx).snapshot(cx);
 1691
 1692        let inlay_hint_settings =
 1693            inlay_hint_settings(selections.newest_anchor().head(), &buffer_snapshot, cx);
 1694        let focus_handle = cx.focus_handle();
 1695        cx.on_focus(&focus_handle, window, Self::handle_focus)
 1696            .detach();
 1697        cx.on_focus_in(&focus_handle, window, Self::handle_focus_in)
 1698            .detach();
 1699        cx.on_focus_out(&focus_handle, window, Self::handle_focus_out)
 1700            .detach();
 1701        cx.on_blur(&focus_handle, window, Self::handle_blur)
 1702            .detach();
 1703
 1704        let show_indent_guides = if matches!(mode, EditorMode::SingleLine { .. }) {
 1705            Some(false)
 1706        } else {
 1707            None
 1708        };
 1709
 1710        let breakpoint_store = match (&mode, project.as_ref()) {
 1711            (EditorMode::Full { .. }, Some(project)) => Some(project.read(cx).breakpoint_store()),
 1712            _ => None,
 1713        };
 1714
 1715        let mut code_action_providers = Vec::new();
 1716        let mut load_uncommitted_diff = None;
 1717        if let Some(project) = project.clone() {
 1718            load_uncommitted_diff = Some(
 1719                update_uncommitted_diff_for_buffer(
 1720                    cx.entity(),
 1721                    &project,
 1722                    buffer.read(cx).all_buffers(),
 1723                    buffer.clone(),
 1724                    cx,
 1725                )
 1726                .shared(),
 1727            );
 1728            code_action_providers.push(Rc::new(project) as Rc<_>);
 1729        }
 1730
 1731        let mut this = Self {
 1732            focus_handle,
 1733            show_cursor_when_unfocused: false,
 1734            last_focused_descendant: None,
 1735            buffer: buffer.clone(),
 1736            display_map: display_map.clone(),
 1737            selections,
 1738            scroll_manager: ScrollManager::new(cx),
 1739            columnar_selection_tail: None,
 1740            add_selections_state: None,
 1741            select_next_state: None,
 1742            select_prev_state: None,
 1743            selection_history: SelectionHistory::default(),
 1744            autoclose_regions: Vec::new(),
 1745            snippet_stack: InvalidationStack::default(),
 1746            select_syntax_node_history: SelectSyntaxNodeHistory::default(),
 1747            ime_transaction: None,
 1748            active_diagnostics: ActiveDiagnostic::None,
 1749            show_inline_diagnostics: ProjectSettings::get_global(cx).diagnostics.inline.enabled,
 1750            inline_diagnostics_update: Task::ready(()),
 1751            inline_diagnostics: Vec::new(),
 1752            soft_wrap_mode_override,
 1753            diagnostics_max_severity,
 1754            hard_wrap: None,
 1755            completion_provider: project.clone().map(|project| Box::new(project) as _),
 1756            semantics_provider: project.clone().map(|project| Rc::new(project) as _),
 1757            collaboration_hub: project.clone().map(|project| Box::new(project) as _),
 1758            project,
 1759            blink_manager: blink_manager.clone(),
 1760            show_local_selections: true,
 1761            show_scrollbars: full_mode,
 1762            minimap_visibility: MinimapVisibility::for_mode(&mode, cx),
 1763            show_breadcrumbs: EditorSettings::get_global(cx).toolbar.breadcrumbs,
 1764            show_gutter: mode.is_full(),
 1765            show_line_numbers: None,
 1766            use_relative_line_numbers: None,
 1767            disable_expand_excerpt_buttons: false,
 1768            show_git_diff_gutter: None,
 1769            show_code_actions: None,
 1770            show_runnables: None,
 1771            show_breakpoints: None,
 1772            show_wrap_guides: None,
 1773            show_indent_guides,
 1774            placeholder_text: None,
 1775            highlight_order: 0,
 1776            highlighted_rows: HashMap::default(),
 1777            background_highlights: TreeMap::default(),
 1778            gutter_highlights: TreeMap::default(),
 1779            scrollbar_marker_state: ScrollbarMarkerState::default(),
 1780            active_indent_guides_state: ActiveIndentGuidesState::default(),
 1781            nav_history: None,
 1782            context_menu: RefCell::new(None),
 1783            context_menu_options: None,
 1784            mouse_context_menu: None,
 1785            completion_tasks: Vec::new(),
 1786            inline_blame_popover: None,
 1787            signature_help_state: SignatureHelpState::default(),
 1788            auto_signature_help: None,
 1789            find_all_references_task_sources: Vec::new(),
 1790            next_completion_id: 0,
 1791            next_inlay_id: 0,
 1792            code_action_providers,
 1793            available_code_actions: None,
 1794            code_actions_task: None,
 1795            quick_selection_highlight_task: None,
 1796            debounced_selection_highlight_task: None,
 1797            document_highlights_task: None,
 1798            linked_editing_range_task: None,
 1799            pending_rename: None,
 1800            searchable: true,
 1801            cursor_shape: EditorSettings::get_global(cx)
 1802                .cursor_shape
 1803                .unwrap_or_default(),
 1804            current_line_highlight: None,
 1805            autoindent_mode: Some(AutoindentMode::EachLine),
 1806            collapse_matches: false,
 1807            workspace: None,
 1808            input_enabled: true,
 1809            use_modal_editing: mode.is_full(),
 1810            read_only: mode.is_minimap(),
 1811            use_autoclose: true,
 1812            use_auto_surround: true,
 1813            auto_replace_emoji_shortcode: false,
 1814            jsx_tag_auto_close_enabled_in_any_buffer: false,
 1815            leader_id: None,
 1816            remote_id: None,
 1817            hover_state: HoverState::default(),
 1818            pending_mouse_down: None,
 1819            hovered_link_state: None,
 1820            edit_prediction_provider: None,
 1821            active_inline_completion: None,
 1822            stale_inline_completion_in_menu: None,
 1823            edit_prediction_preview: EditPredictionPreview::Inactive {
 1824                released_too_fast: false,
 1825            },
 1826            inline_diagnostics_enabled: mode.is_full(),
 1827            inline_value_cache: InlineValueCache::new(inlay_hint_settings.show_value_hints),
 1828            inlay_hint_cache: InlayHintCache::new(inlay_hint_settings),
 1829
 1830            gutter_hovered: false,
 1831            pixel_position_of_newest_cursor: None,
 1832            last_bounds: None,
 1833            last_position_map: None,
 1834            expect_bounds_change: None,
 1835            gutter_dimensions: GutterDimensions::default(),
 1836            style: None,
 1837            show_cursor_names: false,
 1838            hovered_cursors: HashMap::default(),
 1839            next_editor_action_id: EditorActionId::default(),
 1840            editor_actions: Rc::default(),
 1841            inline_completions_hidden_for_vim_mode: false,
 1842            show_inline_completions_override: None,
 1843            menu_inline_completions_policy: MenuInlineCompletionsPolicy::ByProvider,
 1844            edit_prediction_settings: EditPredictionSettings::Disabled,
 1845            edit_prediction_indent_conflict: false,
 1846            edit_prediction_requires_modifier_in_indent_conflict: true,
 1847            custom_context_menu: None,
 1848            show_git_blame_gutter: false,
 1849            show_git_blame_inline: false,
 1850            show_selection_menu: None,
 1851            show_git_blame_inline_delay_task: None,
 1852            git_blame_inline_enabled: ProjectSettings::get_global(cx).git.inline_blame_enabled(),
 1853            render_diff_hunk_controls: Arc::new(render_diff_hunk_controls),
 1854            serialize_dirty_buffers: !mode.is_minimap()
 1855                && ProjectSettings::get_global(cx)
 1856                    .session
 1857                    .restore_unsaved_buffers,
 1858            blame: None,
 1859            blame_subscription: None,
 1860            tasks: BTreeMap::default(),
 1861
 1862            breakpoint_store,
 1863            gutter_breakpoint_indicator: (None, None),
 1864            _subscriptions: vec![
 1865                cx.observe(&buffer, Self::on_buffer_changed),
 1866                cx.subscribe_in(&buffer, window, Self::on_buffer_event),
 1867                cx.observe_in(&display_map, window, Self::on_display_map_changed),
 1868                cx.observe(&blink_manager, |_, _, cx| cx.notify()),
 1869                cx.observe_global_in::<SettingsStore>(window, Self::settings_changed),
 1870                observe_buffer_font_size_adjustment(cx, |_, cx| cx.notify()),
 1871                cx.observe_window_activation(window, |editor, window, cx| {
 1872                    let active = window.is_window_active();
 1873                    editor.blink_manager.update(cx, |blink_manager, cx| {
 1874                        if active {
 1875                            blink_manager.enable(cx);
 1876                        } else {
 1877                            blink_manager.disable(cx);
 1878                        }
 1879                    });
 1880                }),
 1881            ],
 1882            tasks_update_task: None,
 1883            linked_edit_ranges: Default::default(),
 1884            in_project_search: false,
 1885            previous_search_ranges: None,
 1886            breadcrumb_header: None,
 1887            focused_block: None,
 1888            next_scroll_position: NextScrollCursorCenterTopBottom::default(),
 1889            addons: HashMap::default(),
 1890            registered_buffers: HashMap::default(),
 1891            _scroll_cursor_center_top_bottom_task: Task::ready(()),
 1892            selection_mark_mode: false,
 1893            toggle_fold_multiple_buffers: Task::ready(()),
 1894            serialize_selections: Task::ready(()),
 1895            serialize_folds: Task::ready(()),
 1896            text_style_refinement: None,
 1897            load_diff_task: load_uncommitted_diff,
 1898            temporary_diff_override: false,
 1899            mouse_cursor_hidden: false,
 1900            minimap: None,
 1901            hide_mouse_mode: EditorSettings::get_global(cx)
 1902                .hide_mouse
 1903                .unwrap_or_default(),
 1904            change_list: ChangeList::new(),
 1905            mode,
 1906        };
 1907        if let Some(breakpoints) = this.breakpoint_store.as_ref() {
 1908            this._subscriptions
 1909                .push(cx.observe(breakpoints, |_, _, cx| {
 1910                    cx.notify();
 1911                }));
 1912        }
 1913        this.tasks_update_task = Some(this.refresh_runnables(window, cx));
 1914        this._subscriptions.extend(project_subscriptions);
 1915
 1916        this._subscriptions.push(cx.subscribe_in(
 1917            &cx.entity(),
 1918            window,
 1919            |editor, _, e: &EditorEvent, window, cx| match e {
 1920                EditorEvent::ScrollPositionChanged { local, .. } => {
 1921                    if *local {
 1922                        let new_anchor = editor.scroll_manager.anchor();
 1923                        let snapshot = editor.snapshot(window, cx);
 1924                        editor.update_restoration_data(cx, move |data| {
 1925                            data.scroll_position = (
 1926                                new_anchor.top_row(&snapshot.buffer_snapshot),
 1927                                new_anchor.offset,
 1928                            );
 1929                        });
 1930                        editor.hide_signature_help(cx, SignatureHelpHiddenBy::Escape);
 1931                        editor.inline_blame_popover.take();
 1932                    }
 1933                }
 1934                EditorEvent::Edited { .. } => {
 1935                    if !vim_enabled(cx) {
 1936                        let (map, selections) = editor.selections.all_adjusted_display(cx);
 1937                        let pop_state = editor
 1938                            .change_list
 1939                            .last()
 1940                            .map(|previous| {
 1941                                previous.len() == selections.len()
 1942                                    && previous.iter().enumerate().all(|(ix, p)| {
 1943                                        p.to_display_point(&map).row()
 1944                                            == selections[ix].head().row()
 1945                                    })
 1946                            })
 1947                            .unwrap_or(false);
 1948                        let new_positions = selections
 1949                            .into_iter()
 1950                            .map(|s| map.display_point_to_anchor(s.head(), Bias::Left))
 1951                            .collect();
 1952                        editor
 1953                            .change_list
 1954                            .push_to_change_list(pop_state, new_positions);
 1955                    }
 1956                }
 1957                _ => (),
 1958            },
 1959        ));
 1960
 1961        if let Some(dap_store) = this
 1962            .project
 1963            .as_ref()
 1964            .map(|project| project.read(cx).dap_store())
 1965        {
 1966            let weak_editor = cx.weak_entity();
 1967
 1968            this._subscriptions
 1969                .push(
 1970                    cx.observe_new::<project::debugger::session::Session>(move |_, _, cx| {
 1971                        let session_entity = cx.entity();
 1972                        weak_editor
 1973                            .update(cx, |editor, cx| {
 1974                                editor._subscriptions.push(
 1975                                    cx.subscribe(&session_entity, Self::on_debug_session_event),
 1976                                );
 1977                            })
 1978                            .ok();
 1979                    }),
 1980                );
 1981
 1982            for session in dap_store.read(cx).sessions().cloned().collect::<Vec<_>>() {
 1983                this._subscriptions
 1984                    .push(cx.subscribe(&session, Self::on_debug_session_event));
 1985            }
 1986        }
 1987
 1988        this.end_selection(window, cx);
 1989        this.scroll_manager.show_scrollbars(window, cx);
 1990        jsx_tag_auto_close::refresh_enabled_in_any_buffer(&mut this, &buffer, cx);
 1991
 1992        if full_mode {
 1993            let should_auto_hide_scrollbars = cx.should_auto_hide_scrollbars();
 1994            cx.set_global(ScrollbarAutoHide(should_auto_hide_scrollbars));
 1995
 1996            if this.git_blame_inline_enabled {
 1997                this.start_git_blame_inline(false, window, cx);
 1998            }
 1999
 2000            this.go_to_active_debug_line(window, cx);
 2001
 2002            if let Some(buffer) = buffer.read(cx).as_singleton() {
 2003                if let Some(project) = this.project.as_ref() {
 2004                    let handle = project.update(cx, |project, cx| {
 2005                        project.register_buffer_with_language_servers(&buffer, cx)
 2006                    });
 2007                    this.registered_buffers
 2008                        .insert(buffer.read(cx).remote_id(), handle);
 2009                }
 2010            }
 2011
 2012            this.minimap = this.create_minimap(EditorSettings::get_global(cx).minimap, window, cx);
 2013        }
 2014
 2015        this.report_editor_event("Editor Opened", None, cx);
 2016        this
 2017    }
 2018
 2019    pub fn deploy_mouse_context_menu(
 2020        &mut self,
 2021        position: gpui::Point<Pixels>,
 2022        context_menu: Entity<ContextMenu>,
 2023        window: &mut Window,
 2024        cx: &mut Context<Self>,
 2025    ) {
 2026        self.mouse_context_menu = Some(MouseContextMenu::new(
 2027            self,
 2028            crate::mouse_context_menu::MenuPosition::PinnedToScreen(position),
 2029            context_menu,
 2030            window,
 2031            cx,
 2032        ));
 2033    }
 2034
 2035    pub fn mouse_menu_is_focused(&self, window: &Window, cx: &App) -> bool {
 2036        self.mouse_context_menu
 2037            .as_ref()
 2038            .is_some_and(|menu| menu.context_menu.focus_handle(cx).is_focused(window))
 2039    }
 2040
 2041    pub fn key_context(&self, window: &Window, cx: &App) -> KeyContext {
 2042        self.key_context_internal(self.has_active_inline_completion(), window, cx)
 2043    }
 2044
 2045    fn key_context_internal(
 2046        &self,
 2047        has_active_edit_prediction: bool,
 2048        window: &Window,
 2049        cx: &App,
 2050    ) -> KeyContext {
 2051        let mut key_context = KeyContext::new_with_defaults();
 2052        key_context.add("Editor");
 2053        let mode = match self.mode {
 2054            EditorMode::SingleLine { .. } => "single_line",
 2055            EditorMode::AutoHeight { .. } => "auto_height",
 2056            EditorMode::Minimap { .. } => "minimap",
 2057            EditorMode::Full { .. } => "full",
 2058        };
 2059
 2060        if EditorSettings::jupyter_enabled(cx) {
 2061            key_context.add("jupyter");
 2062        }
 2063
 2064        key_context.set("mode", mode);
 2065        if self.pending_rename.is_some() {
 2066            key_context.add("renaming");
 2067        }
 2068
 2069        match self.context_menu.borrow().as_ref() {
 2070            Some(CodeContextMenu::Completions(_)) => {
 2071                key_context.add("menu");
 2072                key_context.add("showing_completions");
 2073            }
 2074            Some(CodeContextMenu::CodeActions(_)) => {
 2075                key_context.add("menu");
 2076                key_context.add("showing_code_actions")
 2077            }
 2078            None => {}
 2079        }
 2080
 2081        // Disable vim contexts when a sub-editor (e.g. rename/inline assistant) is focused.
 2082        if !self.focus_handle(cx).contains_focused(window, cx)
 2083            || (self.is_focused(window) || self.mouse_menu_is_focused(window, cx))
 2084        {
 2085            for addon in self.addons.values() {
 2086                addon.extend_key_context(&mut key_context, cx)
 2087            }
 2088        }
 2089
 2090        if let Some(singleton_buffer) = self.buffer.read(cx).as_singleton() {
 2091            if let Some(extension) = singleton_buffer
 2092                .read(cx)
 2093                .file()
 2094                .and_then(|file| file.path().extension()?.to_str())
 2095            {
 2096                key_context.set("extension", extension.to_string());
 2097            }
 2098        } else {
 2099            key_context.add("multibuffer");
 2100        }
 2101
 2102        if has_active_edit_prediction {
 2103            if self.edit_prediction_in_conflict() {
 2104                key_context.add(EDIT_PREDICTION_CONFLICT_KEY_CONTEXT);
 2105            } else {
 2106                key_context.add(EDIT_PREDICTION_KEY_CONTEXT);
 2107                key_context.add("copilot_suggestion");
 2108            }
 2109        }
 2110
 2111        if self.selection_mark_mode {
 2112            key_context.add("selection_mode");
 2113        }
 2114
 2115        key_context
 2116    }
 2117
 2118    pub fn hide_mouse_cursor(&mut self, origin: &HideMouseCursorOrigin) {
 2119        self.mouse_cursor_hidden = match origin {
 2120            HideMouseCursorOrigin::TypingAction => {
 2121                matches!(
 2122                    self.hide_mouse_mode,
 2123                    HideMouseMode::OnTyping | HideMouseMode::OnTypingAndMovement
 2124                )
 2125            }
 2126            HideMouseCursorOrigin::MovementAction => {
 2127                matches!(self.hide_mouse_mode, HideMouseMode::OnTypingAndMovement)
 2128            }
 2129        };
 2130    }
 2131
 2132    pub fn edit_prediction_in_conflict(&self) -> bool {
 2133        if !self.show_edit_predictions_in_menu() {
 2134            return false;
 2135        }
 2136
 2137        let showing_completions = self
 2138            .context_menu
 2139            .borrow()
 2140            .as_ref()
 2141            .map_or(false, |context| {
 2142                matches!(context, CodeContextMenu::Completions(_))
 2143            });
 2144
 2145        showing_completions
 2146            || self.edit_prediction_requires_modifier()
 2147            // Require modifier key when the cursor is on leading whitespace, to allow `tab`
 2148            // bindings to insert tab characters.
 2149            || (self.edit_prediction_requires_modifier_in_indent_conflict && self.edit_prediction_indent_conflict)
 2150    }
 2151
 2152    pub fn accept_edit_prediction_keybind(
 2153        &self,
 2154        window: &Window,
 2155        cx: &App,
 2156    ) -> AcceptEditPredictionBinding {
 2157        let key_context = self.key_context_internal(true, window, cx);
 2158        let in_conflict = self.edit_prediction_in_conflict();
 2159
 2160        AcceptEditPredictionBinding(
 2161            window
 2162                .bindings_for_action_in_context(&AcceptEditPrediction, key_context)
 2163                .into_iter()
 2164                .filter(|binding| {
 2165                    !in_conflict
 2166                        || binding
 2167                            .keystrokes()
 2168                            .first()
 2169                            .map_or(false, |keystroke| keystroke.modifiers.modified())
 2170                })
 2171                .rev()
 2172                .min_by_key(|binding| {
 2173                    binding
 2174                        .keystrokes()
 2175                        .first()
 2176                        .map_or(u8::MAX, |k| k.modifiers.number_of_modifiers())
 2177                }),
 2178        )
 2179    }
 2180
 2181    pub fn new_file(
 2182        workspace: &mut Workspace,
 2183        _: &workspace::NewFile,
 2184        window: &mut Window,
 2185        cx: &mut Context<Workspace>,
 2186    ) {
 2187        Self::new_in_workspace(workspace, window, cx).detach_and_prompt_err(
 2188            "Failed to create buffer",
 2189            window,
 2190            cx,
 2191            |e, _, _| match e.error_code() {
 2192                ErrorCode::RemoteUpgradeRequired => Some(format!(
 2193                "The remote instance of Zed does not support this yet. It must be upgraded to {}",
 2194                e.error_tag("required").unwrap_or("the latest version")
 2195            )),
 2196                _ => None,
 2197            },
 2198        );
 2199    }
 2200
 2201    pub fn new_in_workspace(
 2202        workspace: &mut Workspace,
 2203        window: &mut Window,
 2204        cx: &mut Context<Workspace>,
 2205    ) -> Task<Result<Entity<Editor>>> {
 2206        let project = workspace.project().clone();
 2207        let create = project.update(cx, |project, cx| project.create_buffer(cx));
 2208
 2209        cx.spawn_in(window, async move |workspace, cx| {
 2210            let buffer = create.await?;
 2211            workspace.update_in(cx, |workspace, window, cx| {
 2212                let editor =
 2213                    cx.new(|cx| Editor::for_buffer(buffer, Some(project.clone()), window, cx));
 2214                workspace.add_item_to_active_pane(Box::new(editor.clone()), None, true, window, cx);
 2215                editor
 2216            })
 2217        })
 2218    }
 2219
 2220    fn new_file_vertical(
 2221        workspace: &mut Workspace,
 2222        _: &workspace::NewFileSplitVertical,
 2223        window: &mut Window,
 2224        cx: &mut Context<Workspace>,
 2225    ) {
 2226        Self::new_file_in_direction(workspace, SplitDirection::vertical(cx), window, cx)
 2227    }
 2228
 2229    fn new_file_horizontal(
 2230        workspace: &mut Workspace,
 2231        _: &workspace::NewFileSplitHorizontal,
 2232        window: &mut Window,
 2233        cx: &mut Context<Workspace>,
 2234    ) {
 2235        Self::new_file_in_direction(workspace, SplitDirection::horizontal(cx), window, cx)
 2236    }
 2237
 2238    fn new_file_in_direction(
 2239        workspace: &mut Workspace,
 2240        direction: SplitDirection,
 2241        window: &mut Window,
 2242        cx: &mut Context<Workspace>,
 2243    ) {
 2244        let project = workspace.project().clone();
 2245        let create = project.update(cx, |project, cx| project.create_buffer(cx));
 2246
 2247        cx.spawn_in(window, async move |workspace, cx| {
 2248            let buffer = create.await?;
 2249            workspace.update_in(cx, move |workspace, window, cx| {
 2250                workspace.split_item(
 2251                    direction,
 2252                    Box::new(
 2253                        cx.new(|cx| Editor::for_buffer(buffer, Some(project.clone()), window, cx)),
 2254                    ),
 2255                    window,
 2256                    cx,
 2257                )
 2258            })?;
 2259            anyhow::Ok(())
 2260        })
 2261        .detach_and_prompt_err("Failed to create buffer", window, cx, |e, _, _| {
 2262            match e.error_code() {
 2263                ErrorCode::RemoteUpgradeRequired => Some(format!(
 2264                "The remote instance of Zed does not support this yet. It must be upgraded to {}",
 2265                e.error_tag("required").unwrap_or("the latest version")
 2266            )),
 2267                _ => None,
 2268            }
 2269        });
 2270    }
 2271
 2272    pub fn leader_id(&self) -> Option<CollaboratorId> {
 2273        self.leader_id
 2274    }
 2275
 2276    pub fn buffer(&self) -> &Entity<MultiBuffer> {
 2277        &self.buffer
 2278    }
 2279
 2280    pub fn workspace(&self) -> Option<Entity<Workspace>> {
 2281        self.workspace.as_ref()?.0.upgrade()
 2282    }
 2283
 2284    pub fn title<'a>(&self, cx: &'a App) -> Cow<'a, str> {
 2285        self.buffer().read(cx).title(cx)
 2286    }
 2287
 2288    pub fn snapshot(&self, window: &mut Window, cx: &mut App) -> EditorSnapshot {
 2289        let git_blame_gutter_max_author_length = self
 2290            .render_git_blame_gutter(cx)
 2291            .then(|| {
 2292                if let Some(blame) = self.blame.as_ref() {
 2293                    let max_author_length =
 2294                        blame.update(cx, |blame, cx| blame.max_author_length(cx));
 2295                    Some(max_author_length)
 2296                } else {
 2297                    None
 2298                }
 2299            })
 2300            .flatten();
 2301
 2302        EditorSnapshot {
 2303            mode: self.mode.clone(),
 2304            show_gutter: self.show_gutter,
 2305            show_line_numbers: self.show_line_numbers,
 2306            show_git_diff_gutter: self.show_git_diff_gutter,
 2307            show_runnables: self.show_runnables,
 2308            show_breakpoints: self.show_breakpoints,
 2309            git_blame_gutter_max_author_length,
 2310            display_snapshot: self.display_map.update(cx, |map, cx| map.snapshot(cx)),
 2311            scroll_anchor: self.scroll_manager.anchor(),
 2312            ongoing_scroll: self.scroll_manager.ongoing_scroll(),
 2313            placeholder_text: self.placeholder_text.clone(),
 2314            is_focused: self.focus_handle.is_focused(window),
 2315            current_line_highlight: self
 2316                .current_line_highlight
 2317                .unwrap_or_else(|| EditorSettings::get_global(cx).current_line_highlight),
 2318            gutter_hovered: self.gutter_hovered,
 2319        }
 2320    }
 2321
 2322    pub fn language_at<T: ToOffset>(&self, point: T, cx: &App) -> Option<Arc<Language>> {
 2323        self.buffer.read(cx).language_at(point, cx)
 2324    }
 2325
 2326    pub fn file_at<T: ToOffset>(&self, point: T, cx: &App) -> Option<Arc<dyn language::File>> {
 2327        self.buffer.read(cx).read(cx).file_at(point).cloned()
 2328    }
 2329
 2330    pub fn active_excerpt(
 2331        &self,
 2332        cx: &App,
 2333    ) -> Option<(ExcerptId, Entity<Buffer>, Range<text::Anchor>)> {
 2334        self.buffer
 2335            .read(cx)
 2336            .excerpt_containing(self.selections.newest_anchor().head(), cx)
 2337    }
 2338
 2339    pub fn mode(&self) -> &EditorMode {
 2340        &self.mode
 2341    }
 2342
 2343    pub fn set_mode(&mut self, mode: EditorMode) {
 2344        self.mode = mode;
 2345    }
 2346
 2347    pub fn collaboration_hub(&self) -> Option<&dyn CollaborationHub> {
 2348        self.collaboration_hub.as_deref()
 2349    }
 2350
 2351    pub fn set_collaboration_hub(&mut self, hub: Box<dyn CollaborationHub>) {
 2352        self.collaboration_hub = Some(hub);
 2353    }
 2354
 2355    pub fn set_in_project_search(&mut self, in_project_search: bool) {
 2356        self.in_project_search = in_project_search;
 2357    }
 2358
 2359    pub fn set_custom_context_menu(
 2360        &mut self,
 2361        f: impl 'static
 2362        + Fn(
 2363            &mut Self,
 2364            DisplayPoint,
 2365            &mut Window,
 2366            &mut Context<Self>,
 2367        ) -> Option<Entity<ui::ContextMenu>>,
 2368    ) {
 2369        self.custom_context_menu = Some(Box::new(f))
 2370    }
 2371
 2372    pub fn set_completion_provider(&mut self, provider: Option<Box<dyn CompletionProvider>>) {
 2373        self.completion_provider = provider;
 2374    }
 2375
 2376    pub fn semantics_provider(&self) -> Option<Rc<dyn SemanticsProvider>> {
 2377        self.semantics_provider.clone()
 2378    }
 2379
 2380    pub fn set_semantics_provider(&mut self, provider: Option<Rc<dyn SemanticsProvider>>) {
 2381        self.semantics_provider = provider;
 2382    }
 2383
 2384    pub fn set_edit_prediction_provider<T>(
 2385        &mut self,
 2386        provider: Option<Entity<T>>,
 2387        window: &mut Window,
 2388        cx: &mut Context<Self>,
 2389    ) where
 2390        T: EditPredictionProvider,
 2391    {
 2392        self.edit_prediction_provider =
 2393            provider.map(|provider| RegisteredInlineCompletionProvider {
 2394                _subscription: cx.observe_in(&provider, window, |this, _, window, cx| {
 2395                    if this.focus_handle.is_focused(window) {
 2396                        this.update_visible_inline_completion(window, cx);
 2397                    }
 2398                }),
 2399                provider: Arc::new(provider),
 2400            });
 2401        self.update_edit_prediction_settings(cx);
 2402        self.refresh_inline_completion(false, false, window, cx);
 2403    }
 2404
 2405    pub fn placeholder_text(&self) -> Option<&str> {
 2406        self.placeholder_text.as_deref()
 2407    }
 2408
 2409    pub fn set_placeholder_text(
 2410        &mut self,
 2411        placeholder_text: impl Into<Arc<str>>,
 2412        cx: &mut Context<Self>,
 2413    ) {
 2414        let placeholder_text = Some(placeholder_text.into());
 2415        if self.placeholder_text != placeholder_text {
 2416            self.placeholder_text = placeholder_text;
 2417            cx.notify();
 2418        }
 2419    }
 2420
 2421    pub fn set_cursor_shape(&mut self, cursor_shape: CursorShape, cx: &mut Context<Self>) {
 2422        self.cursor_shape = cursor_shape;
 2423
 2424        // Disrupt blink for immediate user feedback that the cursor shape has changed
 2425        self.blink_manager.update(cx, BlinkManager::show_cursor);
 2426
 2427        cx.notify();
 2428    }
 2429
 2430    pub fn set_current_line_highlight(
 2431        &mut self,
 2432        current_line_highlight: Option<CurrentLineHighlight>,
 2433    ) {
 2434        self.current_line_highlight = current_line_highlight;
 2435    }
 2436
 2437    pub fn set_collapse_matches(&mut self, collapse_matches: bool) {
 2438        self.collapse_matches = collapse_matches;
 2439    }
 2440
 2441    fn register_buffers_with_language_servers(&mut self, cx: &mut Context<Self>) {
 2442        let buffers = self.buffer.read(cx).all_buffers();
 2443        let Some(project) = self.project.as_ref() else {
 2444            return;
 2445        };
 2446        project.update(cx, |project, cx| {
 2447            for buffer in buffers {
 2448                self.registered_buffers
 2449                    .entry(buffer.read(cx).remote_id())
 2450                    .or_insert_with(|| project.register_buffer_with_language_servers(&buffer, cx));
 2451            }
 2452        })
 2453    }
 2454
 2455    pub fn range_for_match<T: std::marker::Copy>(&self, range: &Range<T>) -> Range<T> {
 2456        if self.collapse_matches {
 2457            return range.start..range.start;
 2458        }
 2459        range.clone()
 2460    }
 2461
 2462    pub fn set_clip_at_line_ends(&mut self, clip: bool, cx: &mut Context<Self>) {
 2463        if self.display_map.read(cx).clip_at_line_ends != clip {
 2464            self.display_map
 2465                .update(cx, |map, _| map.clip_at_line_ends = clip);
 2466        }
 2467    }
 2468
 2469    pub fn set_input_enabled(&mut self, input_enabled: bool) {
 2470        self.input_enabled = input_enabled;
 2471    }
 2472
 2473    pub fn set_inline_completions_hidden_for_vim_mode(
 2474        &mut self,
 2475        hidden: bool,
 2476        window: &mut Window,
 2477        cx: &mut Context<Self>,
 2478    ) {
 2479        if hidden != self.inline_completions_hidden_for_vim_mode {
 2480            self.inline_completions_hidden_for_vim_mode = hidden;
 2481            if hidden {
 2482                self.update_visible_inline_completion(window, cx);
 2483            } else {
 2484                self.refresh_inline_completion(true, false, window, cx);
 2485            }
 2486        }
 2487    }
 2488
 2489    pub fn set_menu_inline_completions_policy(&mut self, value: MenuInlineCompletionsPolicy) {
 2490        self.menu_inline_completions_policy = value;
 2491    }
 2492
 2493    pub fn set_autoindent(&mut self, autoindent: bool) {
 2494        if autoindent {
 2495            self.autoindent_mode = Some(AutoindentMode::EachLine);
 2496        } else {
 2497            self.autoindent_mode = None;
 2498        }
 2499    }
 2500
 2501    pub fn read_only(&self, cx: &App) -> bool {
 2502        self.read_only || self.buffer.read(cx).read_only()
 2503    }
 2504
 2505    pub fn set_read_only(&mut self, read_only: bool) {
 2506        self.read_only = read_only;
 2507    }
 2508
 2509    pub fn set_use_autoclose(&mut self, autoclose: bool) {
 2510        self.use_autoclose = autoclose;
 2511    }
 2512
 2513    pub fn set_use_auto_surround(&mut self, auto_surround: bool) {
 2514        self.use_auto_surround = auto_surround;
 2515    }
 2516
 2517    pub fn set_auto_replace_emoji_shortcode(&mut self, auto_replace: bool) {
 2518        self.auto_replace_emoji_shortcode = auto_replace;
 2519    }
 2520
 2521    pub fn toggle_edit_predictions(
 2522        &mut self,
 2523        _: &ToggleEditPrediction,
 2524        window: &mut Window,
 2525        cx: &mut Context<Self>,
 2526    ) {
 2527        if self.show_inline_completions_override.is_some() {
 2528            self.set_show_edit_predictions(None, window, cx);
 2529        } else {
 2530            let show_edit_predictions = !self.edit_predictions_enabled();
 2531            self.set_show_edit_predictions(Some(show_edit_predictions), window, cx);
 2532        }
 2533    }
 2534
 2535    pub fn set_show_edit_predictions(
 2536        &mut self,
 2537        show_edit_predictions: Option<bool>,
 2538        window: &mut Window,
 2539        cx: &mut Context<Self>,
 2540    ) {
 2541        self.show_inline_completions_override = show_edit_predictions;
 2542        self.update_edit_prediction_settings(cx);
 2543
 2544        if let Some(false) = show_edit_predictions {
 2545            self.discard_inline_completion(false, cx);
 2546        } else {
 2547            self.refresh_inline_completion(false, true, window, cx);
 2548        }
 2549    }
 2550
 2551    fn inline_completions_disabled_in_scope(
 2552        &self,
 2553        buffer: &Entity<Buffer>,
 2554        buffer_position: language::Anchor,
 2555        cx: &App,
 2556    ) -> bool {
 2557        let snapshot = buffer.read(cx).snapshot();
 2558        let settings = snapshot.settings_at(buffer_position, cx);
 2559
 2560        let Some(scope) = snapshot.language_scope_at(buffer_position) else {
 2561            return false;
 2562        };
 2563
 2564        scope.override_name().map_or(false, |scope_name| {
 2565            settings
 2566                .edit_predictions_disabled_in
 2567                .iter()
 2568                .any(|s| s == scope_name)
 2569        })
 2570    }
 2571
 2572    pub fn set_use_modal_editing(&mut self, to: bool) {
 2573        self.use_modal_editing = to;
 2574    }
 2575
 2576    pub fn use_modal_editing(&self) -> bool {
 2577        self.use_modal_editing
 2578    }
 2579
 2580    fn selections_did_change(
 2581        &mut self,
 2582        local: bool,
 2583        old_cursor_position: &Anchor,
 2584        show_completions: bool,
 2585        window: &mut Window,
 2586        cx: &mut Context<Self>,
 2587    ) {
 2588        window.invalidate_character_coordinates();
 2589
 2590        // Copy selections to primary selection buffer
 2591        #[cfg(any(target_os = "linux", target_os = "freebsd"))]
 2592        if local {
 2593            let selections = self.selections.all::<usize>(cx);
 2594            let buffer_handle = self.buffer.read(cx).read(cx);
 2595
 2596            let mut text = String::new();
 2597            for (index, selection) in selections.iter().enumerate() {
 2598                let text_for_selection = buffer_handle
 2599                    .text_for_range(selection.start..selection.end)
 2600                    .collect::<String>();
 2601
 2602                text.push_str(&text_for_selection);
 2603                if index != selections.len() - 1 {
 2604                    text.push('\n');
 2605                }
 2606            }
 2607
 2608            if !text.is_empty() {
 2609                cx.write_to_primary(ClipboardItem::new_string(text));
 2610            }
 2611        }
 2612
 2613        if self.focus_handle.is_focused(window) && self.leader_id.is_none() {
 2614            self.buffer.update(cx, |buffer, cx| {
 2615                buffer.set_active_selections(
 2616                    &self.selections.disjoint_anchors(),
 2617                    self.selections.line_mode,
 2618                    self.cursor_shape,
 2619                    cx,
 2620                )
 2621            });
 2622        }
 2623        let display_map = self
 2624            .display_map
 2625            .update(cx, |display_map, cx| display_map.snapshot(cx));
 2626        let buffer = &display_map.buffer_snapshot;
 2627        self.add_selections_state = None;
 2628        self.select_next_state = None;
 2629        self.select_prev_state = None;
 2630        self.select_syntax_node_history.try_clear();
 2631        self.invalidate_autoclose_regions(&self.selections.disjoint_anchors(), buffer);
 2632        self.snippet_stack
 2633            .invalidate(&self.selections.disjoint_anchors(), buffer);
 2634        self.take_rename(false, window, cx);
 2635
 2636        let new_cursor_position = self.selections.newest_anchor().head();
 2637
 2638        self.push_to_nav_history(
 2639            *old_cursor_position,
 2640            Some(new_cursor_position.to_point(buffer)),
 2641            false,
 2642            cx,
 2643        );
 2644
 2645        if local {
 2646            let new_cursor_position = self.selections.newest_anchor().head();
 2647            let mut context_menu = self.context_menu.borrow_mut();
 2648            let completion_menu = match context_menu.as_ref() {
 2649                Some(CodeContextMenu::Completions(menu)) => Some(menu),
 2650                _ => {
 2651                    *context_menu = None;
 2652                    None
 2653                }
 2654            };
 2655            if let Some(buffer_id) = new_cursor_position.buffer_id {
 2656                if !self.registered_buffers.contains_key(&buffer_id) {
 2657                    if let Some(project) = self.project.as_ref() {
 2658                        project.update(cx, |project, cx| {
 2659                            let Some(buffer) = self.buffer.read(cx).buffer(buffer_id) else {
 2660                                return;
 2661                            };
 2662                            self.registered_buffers.insert(
 2663                                buffer_id,
 2664                                project.register_buffer_with_language_servers(&buffer, cx),
 2665                            );
 2666                        })
 2667                    }
 2668                }
 2669            }
 2670
 2671            if let Some(completion_menu) = completion_menu {
 2672                let cursor_position = new_cursor_position.to_offset(buffer);
 2673                let (word_range, kind) =
 2674                    buffer.surrounding_word(completion_menu.initial_position, true);
 2675                if kind == Some(CharKind::Word)
 2676                    && word_range.to_inclusive().contains(&cursor_position)
 2677                {
 2678                    let mut completion_menu = completion_menu.clone();
 2679                    drop(context_menu);
 2680
 2681                    let query = Self::completion_query(buffer, cursor_position);
 2682                    cx.spawn(async move |this, cx| {
 2683                        completion_menu
 2684                            .filter(query.as_deref(), cx.background_executor().clone())
 2685                            .await;
 2686
 2687                        this.update(cx, |this, cx| {
 2688                            let mut context_menu = this.context_menu.borrow_mut();
 2689                            let Some(CodeContextMenu::Completions(menu)) = context_menu.as_ref()
 2690                            else {
 2691                                return;
 2692                            };
 2693
 2694                            if menu.id > completion_menu.id {
 2695                                return;
 2696                            }
 2697
 2698                            *context_menu = Some(CodeContextMenu::Completions(completion_menu));
 2699                            drop(context_menu);
 2700                            cx.notify();
 2701                        })
 2702                    })
 2703                    .detach();
 2704
 2705                    if show_completions {
 2706                        self.show_completions(&ShowCompletions { trigger: None }, window, cx);
 2707                    }
 2708                } else {
 2709                    drop(context_menu);
 2710                    self.hide_context_menu(window, cx);
 2711                }
 2712            } else {
 2713                drop(context_menu);
 2714            }
 2715
 2716            hide_hover(self, cx);
 2717
 2718            if old_cursor_position.to_display_point(&display_map).row()
 2719                != new_cursor_position.to_display_point(&display_map).row()
 2720            {
 2721                self.available_code_actions.take();
 2722            }
 2723            self.refresh_code_actions(window, cx);
 2724            self.refresh_document_highlights(cx);
 2725            self.refresh_selected_text_highlights(false, window, cx);
 2726            refresh_matching_bracket_highlights(self, window, cx);
 2727            self.update_visible_inline_completion(window, cx);
 2728            self.edit_prediction_requires_modifier_in_indent_conflict = true;
 2729            linked_editing_ranges::refresh_linked_ranges(self, window, cx);
 2730            self.inline_blame_popover.take();
 2731            if self.git_blame_inline_enabled {
 2732                self.start_inline_blame_timer(window, cx);
 2733            }
 2734        }
 2735
 2736        self.blink_manager.update(cx, BlinkManager::pause_blinking);
 2737        cx.emit(EditorEvent::SelectionsChanged { local });
 2738
 2739        let selections = &self.selections.disjoint;
 2740        if selections.len() == 1 {
 2741            cx.emit(SearchEvent::ActiveMatchChanged)
 2742        }
 2743        if local {
 2744            if let Some((_, _, buffer_snapshot)) = buffer.as_singleton() {
 2745                let inmemory_selections = selections
 2746                    .iter()
 2747                    .map(|s| {
 2748                        text::ToPoint::to_point(&s.range().start.text_anchor, buffer_snapshot)
 2749                            ..text::ToPoint::to_point(&s.range().end.text_anchor, buffer_snapshot)
 2750                    })
 2751                    .collect();
 2752                self.update_restoration_data(cx, |data| {
 2753                    data.selections = inmemory_selections;
 2754                });
 2755
 2756                if WorkspaceSettings::get(None, cx).restore_on_startup
 2757                    != RestoreOnStartupBehavior::None
 2758                {
 2759                    if let Some(workspace_id) =
 2760                        self.workspace.as_ref().and_then(|workspace| workspace.1)
 2761                    {
 2762                        let snapshot = self.buffer().read(cx).snapshot(cx);
 2763                        let selections = selections.clone();
 2764                        let background_executor = cx.background_executor().clone();
 2765                        let editor_id = cx.entity().entity_id().as_u64() as ItemId;
 2766                        self.serialize_selections = cx.background_spawn(async move {
 2767                    background_executor.timer(SERIALIZATION_THROTTLE_TIME).await;
 2768                    let db_selections = selections
 2769                        .iter()
 2770                        .map(|selection| {
 2771                            (
 2772                                selection.start.to_offset(&snapshot),
 2773                                selection.end.to_offset(&snapshot),
 2774                            )
 2775                        })
 2776                        .collect();
 2777
 2778                    DB.save_editor_selections(editor_id, workspace_id, db_selections)
 2779                        .await
 2780                        .with_context(|| format!("persisting editor selections for editor {editor_id}, workspace {workspace_id:?}"))
 2781                        .log_err();
 2782                });
 2783                    }
 2784                }
 2785            }
 2786        }
 2787
 2788        cx.notify();
 2789    }
 2790
 2791    fn folds_did_change(&mut self, cx: &mut Context<Self>) {
 2792        use text::ToOffset as _;
 2793        use text::ToPoint as _;
 2794
 2795        if self.mode.is_minimap()
 2796            || WorkspaceSettings::get(None, cx).restore_on_startup == RestoreOnStartupBehavior::None
 2797        {
 2798            return;
 2799        }
 2800
 2801        let Some(singleton) = self.buffer().read(cx).as_singleton() else {
 2802            return;
 2803        };
 2804
 2805        let snapshot = singleton.read(cx).snapshot();
 2806        let inmemory_folds = self.display_map.update(cx, |display_map, cx| {
 2807            let display_snapshot = display_map.snapshot(cx);
 2808
 2809            display_snapshot
 2810                .folds_in_range(0..display_snapshot.buffer_snapshot.len())
 2811                .map(|fold| {
 2812                    fold.range.start.text_anchor.to_point(&snapshot)
 2813                        ..fold.range.end.text_anchor.to_point(&snapshot)
 2814                })
 2815                .collect()
 2816        });
 2817        self.update_restoration_data(cx, |data| {
 2818            data.folds = inmemory_folds;
 2819        });
 2820
 2821        let Some(workspace_id) = self.workspace.as_ref().and_then(|workspace| workspace.1) else {
 2822            return;
 2823        };
 2824        let background_executor = cx.background_executor().clone();
 2825        let editor_id = cx.entity().entity_id().as_u64() as ItemId;
 2826        let db_folds = self.display_map.update(cx, |display_map, cx| {
 2827            display_map
 2828                .snapshot(cx)
 2829                .folds_in_range(0..snapshot.len())
 2830                .map(|fold| {
 2831                    (
 2832                        fold.range.start.text_anchor.to_offset(&snapshot),
 2833                        fold.range.end.text_anchor.to_offset(&snapshot),
 2834                    )
 2835                })
 2836                .collect()
 2837        });
 2838        self.serialize_folds = cx.background_spawn(async move {
 2839            background_executor.timer(SERIALIZATION_THROTTLE_TIME).await;
 2840            DB.save_editor_folds(editor_id, workspace_id, db_folds)
 2841                .await
 2842                .with_context(|| {
 2843                    format!(
 2844                        "persisting editor folds for editor {editor_id}, workspace {workspace_id:?}"
 2845                    )
 2846                })
 2847                .log_err();
 2848        });
 2849    }
 2850
 2851    pub fn sync_selections(
 2852        &mut self,
 2853        other: Entity<Editor>,
 2854        cx: &mut Context<Self>,
 2855    ) -> gpui::Subscription {
 2856        let other_selections = other.read(cx).selections.disjoint.to_vec();
 2857        self.selections.change_with(cx, |selections| {
 2858            selections.select_anchors(other_selections);
 2859        });
 2860
 2861        let other_subscription =
 2862            cx.subscribe(&other, |this, other, other_evt, cx| match other_evt {
 2863                EditorEvent::SelectionsChanged { local: true } => {
 2864                    let other_selections = other.read(cx).selections.disjoint.to_vec();
 2865                    if other_selections.is_empty() {
 2866                        return;
 2867                    }
 2868                    this.selections.change_with(cx, |selections| {
 2869                        selections.select_anchors(other_selections);
 2870                    });
 2871                }
 2872                _ => {}
 2873            });
 2874
 2875        let this_subscription =
 2876            cx.subscribe_self::<EditorEvent>(move |this, this_evt, cx| match this_evt {
 2877                EditorEvent::SelectionsChanged { local: true } => {
 2878                    let these_selections = this.selections.disjoint.to_vec();
 2879                    if these_selections.is_empty() {
 2880                        return;
 2881                    }
 2882                    other.update(cx, |other_editor, cx| {
 2883                        other_editor.selections.change_with(cx, |selections| {
 2884                            selections.select_anchors(these_selections);
 2885                        })
 2886                    });
 2887                }
 2888                _ => {}
 2889            });
 2890
 2891        Subscription::join(other_subscription, this_subscription)
 2892    }
 2893
 2894    pub fn change_selections<R>(
 2895        &mut self,
 2896        autoscroll: Option<Autoscroll>,
 2897        window: &mut Window,
 2898        cx: &mut Context<Self>,
 2899        change: impl FnOnce(&mut MutableSelectionsCollection<'_>) -> R,
 2900    ) -> R {
 2901        self.change_selections_inner(autoscroll, true, window, cx, change)
 2902    }
 2903
 2904    fn change_selections_inner<R>(
 2905        &mut self,
 2906        autoscroll: Option<Autoscroll>,
 2907        request_completions: bool,
 2908        window: &mut Window,
 2909        cx: &mut Context<Self>,
 2910        change: impl FnOnce(&mut MutableSelectionsCollection<'_>) -> R,
 2911    ) -> R {
 2912        let old_cursor_position = self.selections.newest_anchor().head();
 2913        self.push_to_selection_history();
 2914
 2915        let (changed, result) = self.selections.change_with(cx, change);
 2916
 2917        if changed {
 2918            if let Some(autoscroll) = autoscroll {
 2919                self.request_autoscroll(autoscroll, cx);
 2920            }
 2921            self.selections_did_change(true, &old_cursor_position, request_completions, window, cx);
 2922
 2923            if self.should_open_signature_help_automatically(
 2924                &old_cursor_position,
 2925                self.signature_help_state.backspace_pressed(),
 2926                cx,
 2927            ) {
 2928                self.show_signature_help(&ShowSignatureHelp, window, cx);
 2929            }
 2930            self.signature_help_state.set_backspace_pressed(false);
 2931        }
 2932
 2933        result
 2934    }
 2935
 2936    pub fn edit<I, S, T>(&mut self, edits: I, cx: &mut Context<Self>)
 2937    where
 2938        I: IntoIterator<Item = (Range<S>, T)>,
 2939        S: ToOffset,
 2940        T: Into<Arc<str>>,
 2941    {
 2942        if self.read_only(cx) {
 2943            return;
 2944        }
 2945
 2946        self.buffer
 2947            .update(cx, |buffer, cx| buffer.edit(edits, None, cx));
 2948    }
 2949
 2950    pub fn edit_with_autoindent<I, S, T>(&mut self, edits: I, cx: &mut Context<Self>)
 2951    where
 2952        I: IntoIterator<Item = (Range<S>, T)>,
 2953        S: ToOffset,
 2954        T: Into<Arc<str>>,
 2955    {
 2956        if self.read_only(cx) {
 2957            return;
 2958        }
 2959
 2960        self.buffer.update(cx, |buffer, cx| {
 2961            buffer.edit(edits, self.autoindent_mode.clone(), cx)
 2962        });
 2963    }
 2964
 2965    pub fn edit_with_block_indent<I, S, T>(
 2966        &mut self,
 2967        edits: I,
 2968        original_indent_columns: Vec<Option<u32>>,
 2969        cx: &mut Context<Self>,
 2970    ) where
 2971        I: IntoIterator<Item = (Range<S>, T)>,
 2972        S: ToOffset,
 2973        T: Into<Arc<str>>,
 2974    {
 2975        if self.read_only(cx) {
 2976            return;
 2977        }
 2978
 2979        self.buffer.update(cx, |buffer, cx| {
 2980            buffer.edit(
 2981                edits,
 2982                Some(AutoindentMode::Block {
 2983                    original_indent_columns,
 2984                }),
 2985                cx,
 2986            )
 2987        });
 2988    }
 2989
 2990    fn select(&mut self, phase: SelectPhase, window: &mut Window, cx: &mut Context<Self>) {
 2991        self.hide_context_menu(window, cx);
 2992
 2993        match phase {
 2994            SelectPhase::Begin {
 2995                position,
 2996                add,
 2997                click_count,
 2998            } => self.begin_selection(position, add, click_count, window, cx),
 2999            SelectPhase::BeginColumnar {
 3000                position,
 3001                goal_column,
 3002                reset,
 3003            } => self.begin_columnar_selection(position, goal_column, reset, window, cx),
 3004            SelectPhase::Extend {
 3005                position,
 3006                click_count,
 3007            } => self.extend_selection(position, click_count, window, cx),
 3008            SelectPhase::Update {
 3009                position,
 3010                goal_column,
 3011                scroll_delta,
 3012            } => self.update_selection(position, goal_column, scroll_delta, window, cx),
 3013            SelectPhase::End => self.end_selection(window, cx),
 3014        }
 3015    }
 3016
 3017    fn extend_selection(
 3018        &mut self,
 3019        position: DisplayPoint,
 3020        click_count: usize,
 3021        window: &mut Window,
 3022        cx: &mut Context<Self>,
 3023    ) {
 3024        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 3025        let tail = self.selections.newest::<usize>(cx).tail();
 3026        self.begin_selection(position, false, click_count, window, cx);
 3027
 3028        let position = position.to_offset(&display_map, Bias::Left);
 3029        let tail_anchor = display_map.buffer_snapshot.anchor_before(tail);
 3030
 3031        let mut pending_selection = self
 3032            .selections
 3033            .pending_anchor()
 3034            .expect("extend_selection not called with pending selection");
 3035        if position >= tail {
 3036            pending_selection.start = tail_anchor;
 3037        } else {
 3038            pending_selection.end = tail_anchor;
 3039            pending_selection.reversed = true;
 3040        }
 3041
 3042        let mut pending_mode = self.selections.pending_mode().unwrap();
 3043        match &mut pending_mode {
 3044            SelectMode::Word(range) | SelectMode::Line(range) => *range = tail_anchor..tail_anchor,
 3045            _ => {}
 3046        }
 3047
 3048        let auto_scroll = EditorSettings::get_global(cx).autoscroll_on_clicks;
 3049
 3050        self.change_selections(auto_scroll.then(Autoscroll::fit), window, cx, |s| {
 3051            s.set_pending(pending_selection, pending_mode)
 3052        });
 3053    }
 3054
 3055    fn begin_selection(
 3056        &mut self,
 3057        position: DisplayPoint,
 3058        add: bool,
 3059        click_count: usize,
 3060        window: &mut Window,
 3061        cx: &mut Context<Self>,
 3062    ) {
 3063        if !self.focus_handle.is_focused(window) {
 3064            self.last_focused_descendant = None;
 3065            window.focus(&self.focus_handle);
 3066        }
 3067
 3068        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 3069        let buffer = &display_map.buffer_snapshot;
 3070        let position = display_map.clip_point(position, Bias::Left);
 3071
 3072        let start;
 3073        let end;
 3074        let mode;
 3075        let mut auto_scroll;
 3076        match click_count {
 3077            1 => {
 3078                start = buffer.anchor_before(position.to_point(&display_map));
 3079                end = start;
 3080                mode = SelectMode::Character;
 3081                auto_scroll = true;
 3082            }
 3083            2 => {
 3084                let range = movement::surrounding_word(&display_map, position);
 3085                start = buffer.anchor_before(range.start.to_point(&display_map));
 3086                end = buffer.anchor_before(range.end.to_point(&display_map));
 3087                mode = SelectMode::Word(start..end);
 3088                auto_scroll = true;
 3089            }
 3090            3 => {
 3091                let position = display_map
 3092                    .clip_point(position, Bias::Left)
 3093                    .to_point(&display_map);
 3094                let line_start = display_map.prev_line_boundary(position).0;
 3095                let next_line_start = buffer.clip_point(
 3096                    display_map.next_line_boundary(position).0 + Point::new(1, 0),
 3097                    Bias::Left,
 3098                );
 3099                start = buffer.anchor_before(line_start);
 3100                end = buffer.anchor_before(next_line_start);
 3101                mode = SelectMode::Line(start..end);
 3102                auto_scroll = true;
 3103            }
 3104            _ => {
 3105                start = buffer.anchor_before(0);
 3106                end = buffer.anchor_before(buffer.len());
 3107                mode = SelectMode::All;
 3108                auto_scroll = false;
 3109            }
 3110        }
 3111        auto_scroll &= EditorSettings::get_global(cx).autoscroll_on_clicks;
 3112
 3113        let point_to_delete: Option<usize> = {
 3114            let selected_points: Vec<Selection<Point>> =
 3115                self.selections.disjoint_in_range(start..end, cx);
 3116
 3117            if !add || click_count > 1 {
 3118                None
 3119            } else if !selected_points.is_empty() {
 3120                Some(selected_points[0].id)
 3121            } else {
 3122                let clicked_point_already_selected =
 3123                    self.selections.disjoint.iter().find(|selection| {
 3124                        selection.start.to_point(buffer) == start.to_point(buffer)
 3125                            || selection.end.to_point(buffer) == end.to_point(buffer)
 3126                    });
 3127
 3128                clicked_point_already_selected.map(|selection| selection.id)
 3129            }
 3130        };
 3131
 3132        let selections_count = self.selections.count();
 3133
 3134        self.change_selections(auto_scroll.then(Autoscroll::newest), window, cx, |s| {
 3135            if let Some(point_to_delete) = point_to_delete {
 3136                s.delete(point_to_delete);
 3137
 3138                if selections_count == 1 {
 3139                    s.set_pending_anchor_range(start..end, mode);
 3140                }
 3141            } else {
 3142                if !add {
 3143                    s.clear_disjoint();
 3144                }
 3145
 3146                s.set_pending_anchor_range(start..end, mode);
 3147            }
 3148        });
 3149    }
 3150
 3151    fn begin_columnar_selection(
 3152        &mut self,
 3153        position: DisplayPoint,
 3154        goal_column: u32,
 3155        reset: bool,
 3156        window: &mut Window,
 3157        cx: &mut Context<Self>,
 3158    ) {
 3159        if !self.focus_handle.is_focused(window) {
 3160            self.last_focused_descendant = None;
 3161            window.focus(&self.focus_handle);
 3162        }
 3163
 3164        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 3165
 3166        if reset {
 3167            let pointer_position = display_map
 3168                .buffer_snapshot
 3169                .anchor_before(position.to_point(&display_map));
 3170
 3171            self.change_selections(Some(Autoscroll::newest()), window, cx, |s| {
 3172                s.clear_disjoint();
 3173                s.set_pending_anchor_range(
 3174                    pointer_position..pointer_position,
 3175                    SelectMode::Character,
 3176                );
 3177            });
 3178        }
 3179
 3180        let tail = self.selections.newest::<Point>(cx).tail();
 3181        self.columnar_selection_tail = Some(display_map.buffer_snapshot.anchor_before(tail));
 3182
 3183        if !reset {
 3184            self.select_columns(
 3185                tail.to_display_point(&display_map),
 3186                position,
 3187                goal_column,
 3188                &display_map,
 3189                window,
 3190                cx,
 3191            );
 3192        }
 3193    }
 3194
 3195    fn update_selection(
 3196        &mut self,
 3197        position: DisplayPoint,
 3198        goal_column: u32,
 3199        scroll_delta: gpui::Point<f32>,
 3200        window: &mut Window,
 3201        cx: &mut Context<Self>,
 3202    ) {
 3203        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 3204
 3205        if let Some(tail) = self.columnar_selection_tail.as_ref() {
 3206            let tail = tail.to_display_point(&display_map);
 3207            self.select_columns(tail, position, goal_column, &display_map, window, cx);
 3208        } else if let Some(mut pending) = self.selections.pending_anchor() {
 3209            let buffer = self.buffer.read(cx).snapshot(cx);
 3210            let head;
 3211            let tail;
 3212            let mode = self.selections.pending_mode().unwrap();
 3213            match &mode {
 3214                SelectMode::Character => {
 3215                    head = position.to_point(&display_map);
 3216                    tail = pending.tail().to_point(&buffer);
 3217                }
 3218                SelectMode::Word(original_range) => {
 3219                    let original_display_range = original_range.start.to_display_point(&display_map)
 3220                        ..original_range.end.to_display_point(&display_map);
 3221                    let original_buffer_range = original_display_range.start.to_point(&display_map)
 3222                        ..original_display_range.end.to_point(&display_map);
 3223                    if movement::is_inside_word(&display_map, position)
 3224                        || original_display_range.contains(&position)
 3225                    {
 3226                        let word_range = movement::surrounding_word(&display_map, position);
 3227                        if word_range.start < original_display_range.start {
 3228                            head = word_range.start.to_point(&display_map);
 3229                        } else {
 3230                            head = word_range.end.to_point(&display_map);
 3231                        }
 3232                    } else {
 3233                        head = position.to_point(&display_map);
 3234                    }
 3235
 3236                    if head <= original_buffer_range.start {
 3237                        tail = original_buffer_range.end;
 3238                    } else {
 3239                        tail = original_buffer_range.start;
 3240                    }
 3241                }
 3242                SelectMode::Line(original_range) => {
 3243                    let original_range = original_range.to_point(&display_map.buffer_snapshot);
 3244
 3245                    let position = display_map
 3246                        .clip_point(position, Bias::Left)
 3247                        .to_point(&display_map);
 3248                    let line_start = display_map.prev_line_boundary(position).0;
 3249                    let next_line_start = buffer.clip_point(
 3250                        display_map.next_line_boundary(position).0 + Point::new(1, 0),
 3251                        Bias::Left,
 3252                    );
 3253
 3254                    if line_start < original_range.start {
 3255                        head = line_start
 3256                    } else {
 3257                        head = next_line_start
 3258                    }
 3259
 3260                    if head <= original_range.start {
 3261                        tail = original_range.end;
 3262                    } else {
 3263                        tail = original_range.start;
 3264                    }
 3265                }
 3266                SelectMode::All => {
 3267                    return;
 3268                }
 3269            };
 3270
 3271            if head < tail {
 3272                pending.start = buffer.anchor_before(head);
 3273                pending.end = buffer.anchor_before(tail);
 3274                pending.reversed = true;
 3275            } else {
 3276                pending.start = buffer.anchor_before(tail);
 3277                pending.end = buffer.anchor_before(head);
 3278                pending.reversed = false;
 3279            }
 3280
 3281            self.change_selections(None, window, cx, |s| {
 3282                s.set_pending(pending, mode);
 3283            });
 3284        } else {
 3285            log::error!("update_selection dispatched with no pending selection");
 3286            return;
 3287        }
 3288
 3289        self.apply_scroll_delta(scroll_delta, window, cx);
 3290        cx.notify();
 3291    }
 3292
 3293    fn end_selection(&mut self, window: &mut Window, cx: &mut Context<Self>) {
 3294        self.columnar_selection_tail.take();
 3295        if self.selections.pending_anchor().is_some() {
 3296            let selections = self.selections.all::<usize>(cx);
 3297            self.change_selections(None, window, cx, |s| {
 3298                s.select(selections);
 3299                s.clear_pending();
 3300            });
 3301        }
 3302    }
 3303
 3304    fn select_columns(
 3305        &mut self,
 3306        tail: DisplayPoint,
 3307        head: DisplayPoint,
 3308        goal_column: u32,
 3309        display_map: &DisplaySnapshot,
 3310        window: &mut Window,
 3311        cx: &mut Context<Self>,
 3312    ) {
 3313        let start_row = cmp::min(tail.row(), head.row());
 3314        let end_row = cmp::max(tail.row(), head.row());
 3315        let start_column = cmp::min(tail.column(), goal_column);
 3316        let end_column = cmp::max(tail.column(), goal_column);
 3317        let reversed = start_column < tail.column();
 3318
 3319        let selection_ranges = (start_row.0..=end_row.0)
 3320            .map(DisplayRow)
 3321            .filter_map(|row| {
 3322                if start_column <= display_map.line_len(row) && !display_map.is_block_line(row) {
 3323                    let start = display_map
 3324                        .clip_point(DisplayPoint::new(row, start_column), Bias::Left)
 3325                        .to_point(display_map);
 3326                    let end = display_map
 3327                        .clip_point(DisplayPoint::new(row, end_column), Bias::Right)
 3328                        .to_point(display_map);
 3329                    if reversed {
 3330                        Some(end..start)
 3331                    } else {
 3332                        Some(start..end)
 3333                    }
 3334                } else {
 3335                    None
 3336                }
 3337            })
 3338            .collect::<Vec<_>>();
 3339
 3340        self.change_selections(None, window, cx, |s| {
 3341            s.select_ranges(selection_ranges);
 3342        });
 3343        cx.notify();
 3344    }
 3345
 3346    pub fn has_non_empty_selection(&self, cx: &mut App) -> bool {
 3347        self.selections
 3348            .all_adjusted(cx)
 3349            .iter()
 3350            .any(|selection| !selection.is_empty())
 3351    }
 3352
 3353    pub fn has_pending_nonempty_selection(&self) -> bool {
 3354        let pending_nonempty_selection = match self.selections.pending_anchor() {
 3355            Some(Selection { start, end, .. }) => start != end,
 3356            None => false,
 3357        };
 3358
 3359        pending_nonempty_selection
 3360            || (self.columnar_selection_tail.is_some() && self.selections.disjoint.len() > 1)
 3361    }
 3362
 3363    pub fn has_pending_selection(&self) -> bool {
 3364        self.selections.pending_anchor().is_some() || self.columnar_selection_tail.is_some()
 3365    }
 3366
 3367    pub fn cancel(&mut self, _: &Cancel, window: &mut Window, cx: &mut Context<Self>) {
 3368        self.selection_mark_mode = false;
 3369
 3370        if self.clear_expanded_diff_hunks(cx) {
 3371            cx.notify();
 3372            return;
 3373        }
 3374        if self.dismiss_menus_and_popups(true, window, cx) {
 3375            return;
 3376        }
 3377
 3378        if self.mode.is_full()
 3379            && self.change_selections(Some(Autoscroll::fit()), window, cx, |s| s.try_cancel())
 3380        {
 3381            return;
 3382        }
 3383
 3384        cx.propagate();
 3385    }
 3386
 3387    pub fn dismiss_menus_and_popups(
 3388        &mut self,
 3389        is_user_requested: bool,
 3390        window: &mut Window,
 3391        cx: &mut Context<Self>,
 3392    ) -> bool {
 3393        if self.take_rename(false, window, cx).is_some() {
 3394            return true;
 3395        }
 3396
 3397        if hide_hover(self, cx) {
 3398            return true;
 3399        }
 3400
 3401        if self.hide_signature_help(cx, SignatureHelpHiddenBy::Escape) {
 3402            return true;
 3403        }
 3404
 3405        if self.hide_context_menu(window, cx).is_some() {
 3406            return true;
 3407        }
 3408
 3409        if self.mouse_context_menu.take().is_some() {
 3410            return true;
 3411        }
 3412
 3413        if is_user_requested && self.discard_inline_completion(true, cx) {
 3414            return true;
 3415        }
 3416
 3417        if self.snippet_stack.pop().is_some() {
 3418            return true;
 3419        }
 3420
 3421        if self.mode.is_full() && matches!(self.active_diagnostics, ActiveDiagnostic::Group(_)) {
 3422            self.dismiss_diagnostics(cx);
 3423            return true;
 3424        }
 3425
 3426        false
 3427    }
 3428
 3429    fn linked_editing_ranges_for(
 3430        &self,
 3431        selection: Range<text::Anchor>,
 3432        cx: &App,
 3433    ) -> Option<HashMap<Entity<Buffer>, Vec<Range<text::Anchor>>>> {
 3434        if self.linked_edit_ranges.is_empty() {
 3435            return None;
 3436        }
 3437        let ((base_range, linked_ranges), buffer_snapshot, buffer) =
 3438            selection.end.buffer_id.and_then(|end_buffer_id| {
 3439                if selection.start.buffer_id != Some(end_buffer_id) {
 3440                    return None;
 3441                }
 3442                let buffer = self.buffer.read(cx).buffer(end_buffer_id)?;
 3443                let snapshot = buffer.read(cx).snapshot();
 3444                self.linked_edit_ranges
 3445                    .get(end_buffer_id, selection.start..selection.end, &snapshot)
 3446                    .map(|ranges| (ranges, snapshot, buffer))
 3447            })?;
 3448        use text::ToOffset as TO;
 3449        // find offset from the start of current range to current cursor position
 3450        let start_byte_offset = TO::to_offset(&base_range.start, &buffer_snapshot);
 3451
 3452        let start_offset = TO::to_offset(&selection.start, &buffer_snapshot);
 3453        let start_difference = start_offset - start_byte_offset;
 3454        let end_offset = TO::to_offset(&selection.end, &buffer_snapshot);
 3455        let end_difference = end_offset - start_byte_offset;
 3456        // Current range has associated linked ranges.
 3457        let mut linked_edits = HashMap::<_, Vec<_>>::default();
 3458        for range in linked_ranges.iter() {
 3459            let start_offset = TO::to_offset(&range.start, &buffer_snapshot);
 3460            let end_offset = start_offset + end_difference;
 3461            let start_offset = start_offset + start_difference;
 3462            if start_offset > buffer_snapshot.len() || end_offset > buffer_snapshot.len() {
 3463                continue;
 3464            }
 3465            if self.selections.disjoint_anchor_ranges().any(|s| {
 3466                if s.start.buffer_id != selection.start.buffer_id
 3467                    || s.end.buffer_id != selection.end.buffer_id
 3468                {
 3469                    return false;
 3470                }
 3471                TO::to_offset(&s.start.text_anchor, &buffer_snapshot) <= end_offset
 3472                    && TO::to_offset(&s.end.text_anchor, &buffer_snapshot) >= start_offset
 3473            }) {
 3474                continue;
 3475            }
 3476            let start = buffer_snapshot.anchor_after(start_offset);
 3477            let end = buffer_snapshot.anchor_after(end_offset);
 3478            linked_edits
 3479                .entry(buffer.clone())
 3480                .or_default()
 3481                .push(start..end);
 3482        }
 3483        Some(linked_edits)
 3484    }
 3485
 3486    pub fn handle_input(&mut self, text: &str, window: &mut Window, cx: &mut Context<Self>) {
 3487        let text: Arc<str> = text.into();
 3488
 3489        if self.read_only(cx) {
 3490            return;
 3491        }
 3492
 3493        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
 3494
 3495        let selections = self.selections.all_adjusted(cx);
 3496        let mut bracket_inserted = false;
 3497        let mut edits = Vec::new();
 3498        let mut linked_edits = HashMap::<_, Vec<_>>::default();
 3499        let mut new_selections = Vec::with_capacity(selections.len());
 3500        let mut new_autoclose_regions = Vec::new();
 3501        let snapshot = self.buffer.read(cx).read(cx);
 3502        let mut clear_linked_edit_ranges = false;
 3503
 3504        for (selection, autoclose_region) in
 3505            self.selections_with_autoclose_regions(selections, &snapshot)
 3506        {
 3507            if let Some(scope) = snapshot.language_scope_at(selection.head()) {
 3508                // Determine if the inserted text matches the opening or closing
 3509                // bracket of any of this language's bracket pairs.
 3510                let mut bracket_pair = None;
 3511                let mut is_bracket_pair_start = false;
 3512                let mut is_bracket_pair_end = false;
 3513                if !text.is_empty() {
 3514                    let mut bracket_pair_matching_end = None;
 3515                    // `text` can be empty when a user is using IME (e.g. Chinese Wubi Simplified)
 3516                    //  and they are removing the character that triggered IME popup.
 3517                    for (pair, enabled) in scope.brackets() {
 3518                        if !pair.close && !pair.surround {
 3519                            continue;
 3520                        }
 3521
 3522                        if enabled && pair.start.ends_with(text.as_ref()) {
 3523                            let prefix_len = pair.start.len() - text.len();
 3524                            let preceding_text_matches_prefix = prefix_len == 0
 3525                                || (selection.start.column >= (prefix_len as u32)
 3526                                    && snapshot.contains_str_at(
 3527                                        Point::new(
 3528                                            selection.start.row,
 3529                                            selection.start.column - (prefix_len as u32),
 3530                                        ),
 3531                                        &pair.start[..prefix_len],
 3532                                    ));
 3533                            if preceding_text_matches_prefix {
 3534                                bracket_pair = Some(pair.clone());
 3535                                is_bracket_pair_start = true;
 3536                                break;
 3537                            }
 3538                        }
 3539                        if pair.end.as_str() == text.as_ref() && bracket_pair_matching_end.is_none()
 3540                        {
 3541                            // take first bracket pair matching end, but don't break in case a later bracket
 3542                            // pair matches start
 3543                            bracket_pair_matching_end = Some(pair.clone());
 3544                        }
 3545                    }
 3546                    if bracket_pair.is_none() && bracket_pair_matching_end.is_some() {
 3547                        bracket_pair = Some(bracket_pair_matching_end.unwrap());
 3548                        is_bracket_pair_end = true;
 3549                    }
 3550                }
 3551
 3552                if let Some(bracket_pair) = bracket_pair {
 3553                    let snapshot_settings = snapshot.language_settings_at(selection.start, cx);
 3554                    let autoclose = self.use_autoclose && snapshot_settings.use_autoclose;
 3555                    let auto_surround =
 3556                        self.use_auto_surround && snapshot_settings.use_auto_surround;
 3557                    if selection.is_empty() {
 3558                        if is_bracket_pair_start {
 3559                            // If the inserted text is a suffix of an opening bracket and the
 3560                            // selection is preceded by the rest of the opening bracket, then
 3561                            // insert the closing bracket.
 3562                            let following_text_allows_autoclose = snapshot
 3563                                .chars_at(selection.start)
 3564                                .next()
 3565                                .map_or(true, |c| scope.should_autoclose_before(c));
 3566
 3567                            let preceding_text_allows_autoclose = selection.start.column == 0
 3568                                || snapshot.reversed_chars_at(selection.start).next().map_or(
 3569                                    true,
 3570                                    |c| {
 3571                                        bracket_pair.start != bracket_pair.end
 3572                                            || !snapshot
 3573                                                .char_classifier_at(selection.start)
 3574                                                .is_word(c)
 3575                                    },
 3576                                );
 3577
 3578                            let is_closing_quote = if bracket_pair.end == bracket_pair.start
 3579                                && bracket_pair.start.len() == 1
 3580                            {
 3581                                let target = bracket_pair.start.chars().next().unwrap();
 3582                                let current_line_count = snapshot
 3583                                    .reversed_chars_at(selection.start)
 3584                                    .take_while(|&c| c != '\n')
 3585                                    .filter(|&c| c == target)
 3586                                    .count();
 3587                                current_line_count % 2 == 1
 3588                            } else {
 3589                                false
 3590                            };
 3591
 3592                            if autoclose
 3593                                && bracket_pair.close
 3594                                && following_text_allows_autoclose
 3595                                && preceding_text_allows_autoclose
 3596                                && !is_closing_quote
 3597                            {
 3598                                let anchor = snapshot.anchor_before(selection.end);
 3599                                new_selections.push((selection.map(|_| anchor), text.len()));
 3600                                new_autoclose_regions.push((
 3601                                    anchor,
 3602                                    text.len(),
 3603                                    selection.id,
 3604                                    bracket_pair.clone(),
 3605                                ));
 3606                                edits.push((
 3607                                    selection.range(),
 3608                                    format!("{}{}", text, bracket_pair.end).into(),
 3609                                ));
 3610                                bracket_inserted = true;
 3611                                continue;
 3612                            }
 3613                        }
 3614
 3615                        if let Some(region) = autoclose_region {
 3616                            // If the selection is followed by an auto-inserted closing bracket,
 3617                            // then don't insert that closing bracket again; just move the selection
 3618                            // past the closing bracket.
 3619                            let should_skip = selection.end == region.range.end.to_point(&snapshot)
 3620                                && text.as_ref() == region.pair.end.as_str();
 3621                            if should_skip {
 3622                                let anchor = snapshot.anchor_after(selection.end);
 3623                                new_selections
 3624                                    .push((selection.map(|_| anchor), region.pair.end.len()));
 3625                                continue;
 3626                            }
 3627                        }
 3628
 3629                        let always_treat_brackets_as_autoclosed = snapshot
 3630                            .language_settings_at(selection.start, cx)
 3631                            .always_treat_brackets_as_autoclosed;
 3632                        if always_treat_brackets_as_autoclosed
 3633                            && is_bracket_pair_end
 3634                            && snapshot.contains_str_at(selection.end, text.as_ref())
 3635                        {
 3636                            // Otherwise, when `always_treat_brackets_as_autoclosed` is set to `true
 3637                            // and the inserted text is a closing bracket and the selection is followed
 3638                            // by the closing bracket then move the selection past the closing bracket.
 3639                            let anchor = snapshot.anchor_after(selection.end);
 3640                            new_selections.push((selection.map(|_| anchor), text.len()));
 3641                            continue;
 3642                        }
 3643                    }
 3644                    // If an opening bracket is 1 character long and is typed while
 3645                    // text is selected, then surround that text with the bracket pair.
 3646                    else if auto_surround
 3647                        && bracket_pair.surround
 3648                        && is_bracket_pair_start
 3649                        && bracket_pair.start.chars().count() == 1
 3650                    {
 3651                        edits.push((selection.start..selection.start, text.clone()));
 3652                        edits.push((
 3653                            selection.end..selection.end,
 3654                            bracket_pair.end.as_str().into(),
 3655                        ));
 3656                        bracket_inserted = true;
 3657                        new_selections.push((
 3658                            Selection {
 3659                                id: selection.id,
 3660                                start: snapshot.anchor_after(selection.start),
 3661                                end: snapshot.anchor_before(selection.end),
 3662                                reversed: selection.reversed,
 3663                                goal: selection.goal,
 3664                            },
 3665                            0,
 3666                        ));
 3667                        continue;
 3668                    }
 3669                }
 3670            }
 3671
 3672            if self.auto_replace_emoji_shortcode
 3673                && selection.is_empty()
 3674                && text.as_ref().ends_with(':')
 3675            {
 3676                if let Some(possible_emoji_short_code) =
 3677                    Self::find_possible_emoji_shortcode_at_position(&snapshot, selection.start)
 3678                {
 3679                    if !possible_emoji_short_code.is_empty() {
 3680                        if let Some(emoji) = emojis::get_by_shortcode(&possible_emoji_short_code) {
 3681                            let emoji_shortcode_start = Point::new(
 3682                                selection.start.row,
 3683                                selection.start.column - possible_emoji_short_code.len() as u32 - 1,
 3684                            );
 3685
 3686                            // Remove shortcode from buffer
 3687                            edits.push((
 3688                                emoji_shortcode_start..selection.start,
 3689                                "".to_string().into(),
 3690                            ));
 3691                            new_selections.push((
 3692                                Selection {
 3693                                    id: selection.id,
 3694                                    start: snapshot.anchor_after(emoji_shortcode_start),
 3695                                    end: snapshot.anchor_before(selection.start),
 3696                                    reversed: selection.reversed,
 3697                                    goal: selection.goal,
 3698                                },
 3699                                0,
 3700                            ));
 3701
 3702                            // Insert emoji
 3703                            let selection_start_anchor = snapshot.anchor_after(selection.start);
 3704                            new_selections.push((selection.map(|_| selection_start_anchor), 0));
 3705                            edits.push((selection.start..selection.end, emoji.to_string().into()));
 3706
 3707                            continue;
 3708                        }
 3709                    }
 3710                }
 3711            }
 3712
 3713            // If not handling any auto-close operation, then just replace the selected
 3714            // text with the given input and move the selection to the end of the
 3715            // newly inserted text.
 3716            let anchor = snapshot.anchor_after(selection.end);
 3717            if !self.linked_edit_ranges.is_empty() {
 3718                let start_anchor = snapshot.anchor_before(selection.start);
 3719
 3720                let is_word_char = text.chars().next().map_or(true, |char| {
 3721                    let classifier = snapshot
 3722                        .char_classifier_at(start_anchor.to_offset(&snapshot))
 3723                        .ignore_punctuation(true);
 3724                    classifier.is_word(char)
 3725                });
 3726
 3727                if is_word_char {
 3728                    if let Some(ranges) = self
 3729                        .linked_editing_ranges_for(start_anchor.text_anchor..anchor.text_anchor, cx)
 3730                    {
 3731                        for (buffer, edits) in ranges {
 3732                            linked_edits
 3733                                .entry(buffer.clone())
 3734                                .or_default()
 3735                                .extend(edits.into_iter().map(|range| (range, text.clone())));
 3736                        }
 3737                    }
 3738                } else {
 3739                    clear_linked_edit_ranges = true;
 3740                }
 3741            }
 3742
 3743            new_selections.push((selection.map(|_| anchor), 0));
 3744            edits.push((selection.start..selection.end, text.clone()));
 3745        }
 3746
 3747        drop(snapshot);
 3748
 3749        self.transact(window, cx, |this, window, cx| {
 3750            if clear_linked_edit_ranges {
 3751                this.linked_edit_ranges.clear();
 3752            }
 3753            let initial_buffer_versions =
 3754                jsx_tag_auto_close::construct_initial_buffer_versions_map(this, &edits, cx);
 3755
 3756            this.buffer.update(cx, |buffer, cx| {
 3757                buffer.edit(edits, this.autoindent_mode.clone(), cx);
 3758            });
 3759            for (buffer, edits) in linked_edits {
 3760                buffer.update(cx, |buffer, cx| {
 3761                    let snapshot = buffer.snapshot();
 3762                    let edits = edits
 3763                        .into_iter()
 3764                        .map(|(range, text)| {
 3765                            use text::ToPoint as TP;
 3766                            let end_point = TP::to_point(&range.end, &snapshot);
 3767                            let start_point = TP::to_point(&range.start, &snapshot);
 3768                            (start_point..end_point, text)
 3769                        })
 3770                        .sorted_by_key(|(range, _)| range.start);
 3771                    buffer.edit(edits, None, cx);
 3772                })
 3773            }
 3774            let new_anchor_selections = new_selections.iter().map(|e| &e.0);
 3775            let new_selection_deltas = new_selections.iter().map(|e| e.1);
 3776            let map = this.display_map.update(cx, |map, cx| map.snapshot(cx));
 3777            let new_selections = resolve_selections::<usize, _>(new_anchor_selections, &map)
 3778                .zip(new_selection_deltas)
 3779                .map(|(selection, delta)| Selection {
 3780                    id: selection.id,
 3781                    start: selection.start + delta,
 3782                    end: selection.end + delta,
 3783                    reversed: selection.reversed,
 3784                    goal: SelectionGoal::None,
 3785                })
 3786                .collect::<Vec<_>>();
 3787
 3788            let mut i = 0;
 3789            for (position, delta, selection_id, pair) in new_autoclose_regions {
 3790                let position = position.to_offset(&map.buffer_snapshot) + delta;
 3791                let start = map.buffer_snapshot.anchor_before(position);
 3792                let end = map.buffer_snapshot.anchor_after(position);
 3793                while let Some(existing_state) = this.autoclose_regions.get(i) {
 3794                    match existing_state.range.start.cmp(&start, &map.buffer_snapshot) {
 3795                        Ordering::Less => i += 1,
 3796                        Ordering::Greater => break,
 3797                        Ordering::Equal => {
 3798                            match end.cmp(&existing_state.range.end, &map.buffer_snapshot) {
 3799                                Ordering::Less => i += 1,
 3800                                Ordering::Equal => break,
 3801                                Ordering::Greater => break,
 3802                            }
 3803                        }
 3804                    }
 3805                }
 3806                this.autoclose_regions.insert(
 3807                    i,
 3808                    AutocloseRegion {
 3809                        selection_id,
 3810                        range: start..end,
 3811                        pair,
 3812                    },
 3813                );
 3814            }
 3815
 3816            let had_active_inline_completion = this.has_active_inline_completion();
 3817            this.change_selections_inner(Some(Autoscroll::fit()), false, window, cx, |s| {
 3818                s.select(new_selections)
 3819            });
 3820
 3821            if !bracket_inserted {
 3822                if let Some(on_type_format_task) =
 3823                    this.trigger_on_type_formatting(text.to_string(), window, cx)
 3824                {
 3825                    on_type_format_task.detach_and_log_err(cx);
 3826                }
 3827            }
 3828
 3829            let editor_settings = EditorSettings::get_global(cx);
 3830            if bracket_inserted
 3831                && (editor_settings.auto_signature_help
 3832                    || editor_settings.show_signature_help_after_edits)
 3833            {
 3834                this.show_signature_help(&ShowSignatureHelp, window, cx);
 3835            }
 3836
 3837            let trigger_in_words =
 3838                this.show_edit_predictions_in_menu() || !had_active_inline_completion;
 3839            if this.hard_wrap.is_some() {
 3840                let latest: Range<Point> = this.selections.newest(cx).range();
 3841                if latest.is_empty()
 3842                    && this
 3843                        .buffer()
 3844                        .read(cx)
 3845                        .snapshot(cx)
 3846                        .line_len(MultiBufferRow(latest.start.row))
 3847                        == latest.start.column
 3848                {
 3849                    this.rewrap_impl(
 3850                        RewrapOptions {
 3851                            override_language_settings: true,
 3852                            preserve_existing_whitespace: true,
 3853                        },
 3854                        cx,
 3855                    )
 3856                }
 3857            }
 3858            this.trigger_completion_on_input(&text, trigger_in_words, window, cx);
 3859            linked_editing_ranges::refresh_linked_ranges(this, window, cx);
 3860            this.refresh_inline_completion(true, false, window, cx);
 3861            jsx_tag_auto_close::handle_from(this, initial_buffer_versions, window, cx);
 3862        });
 3863    }
 3864
 3865    fn find_possible_emoji_shortcode_at_position(
 3866        snapshot: &MultiBufferSnapshot,
 3867        position: Point,
 3868    ) -> Option<String> {
 3869        let mut chars = Vec::new();
 3870        let mut found_colon = false;
 3871        for char in snapshot.reversed_chars_at(position).take(100) {
 3872            // Found a possible emoji shortcode in the middle of the buffer
 3873            if found_colon {
 3874                if char.is_whitespace() {
 3875                    chars.reverse();
 3876                    return Some(chars.iter().collect());
 3877                }
 3878                // If the previous character is not a whitespace, we are in the middle of a word
 3879                // and we only want to complete the shortcode if the word is made up of other emojis
 3880                let mut containing_word = String::new();
 3881                for ch in snapshot
 3882                    .reversed_chars_at(position)
 3883                    .skip(chars.len() + 1)
 3884                    .take(100)
 3885                {
 3886                    if ch.is_whitespace() {
 3887                        break;
 3888                    }
 3889                    containing_word.push(ch);
 3890                }
 3891                let containing_word = containing_word.chars().rev().collect::<String>();
 3892                if util::word_consists_of_emojis(containing_word.as_str()) {
 3893                    chars.reverse();
 3894                    return Some(chars.iter().collect());
 3895                }
 3896            }
 3897
 3898            if char.is_whitespace() || !char.is_ascii() {
 3899                return None;
 3900            }
 3901            if char == ':' {
 3902                found_colon = true;
 3903            } else {
 3904                chars.push(char);
 3905            }
 3906        }
 3907        // Found a possible emoji shortcode at the beginning of the buffer
 3908        chars.reverse();
 3909        Some(chars.iter().collect())
 3910    }
 3911
 3912    pub fn newline(&mut self, _: &Newline, window: &mut Window, cx: &mut Context<Self>) {
 3913        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
 3914        self.transact(window, cx, |this, window, cx| {
 3915            let (edits, selection_fixup_info): (Vec<_>, Vec<_>) = {
 3916                let selections = this.selections.all::<usize>(cx);
 3917                let multi_buffer = this.buffer.read(cx);
 3918                let buffer = multi_buffer.snapshot(cx);
 3919                selections
 3920                    .iter()
 3921                    .map(|selection| {
 3922                        let start_point = selection.start.to_point(&buffer);
 3923                        let mut indent =
 3924                            buffer.indent_size_for_line(MultiBufferRow(start_point.row));
 3925                        indent.len = cmp::min(indent.len, start_point.column);
 3926                        let start = selection.start;
 3927                        let end = selection.end;
 3928                        let selection_is_empty = start == end;
 3929                        let language_scope = buffer.language_scope_at(start);
 3930                        let (comment_delimiter, insert_extra_newline) = if let Some(language) =
 3931                            &language_scope
 3932                        {
 3933                            let insert_extra_newline =
 3934                                insert_extra_newline_brackets(&buffer, start..end, language)
 3935                                    || insert_extra_newline_tree_sitter(&buffer, start..end);
 3936
 3937                            // Comment extension on newline is allowed only for cursor selections
 3938                            let comment_delimiter = maybe!({
 3939                                if !selection_is_empty {
 3940                                    return None;
 3941                                }
 3942
 3943                                if !multi_buffer.language_settings(cx).extend_comment_on_newline {
 3944                                    return None;
 3945                                }
 3946
 3947                                let delimiters = language.line_comment_prefixes();
 3948                                let max_len_of_delimiter =
 3949                                    delimiters.iter().map(|delimiter| delimiter.len()).max()?;
 3950                                let (snapshot, range) =
 3951                                    buffer.buffer_line_for_row(MultiBufferRow(start_point.row))?;
 3952
 3953                                let mut index_of_first_non_whitespace = 0;
 3954                                let comment_candidate = snapshot
 3955                                    .chars_for_range(range)
 3956                                    .skip_while(|c| {
 3957                                        let should_skip = c.is_whitespace();
 3958                                        if should_skip {
 3959                                            index_of_first_non_whitespace += 1;
 3960                                        }
 3961                                        should_skip
 3962                                    })
 3963                                    .take(max_len_of_delimiter)
 3964                                    .collect::<String>();
 3965                                let comment_prefix = delimiters.iter().find(|comment_prefix| {
 3966                                    comment_candidate.starts_with(comment_prefix.as_ref())
 3967                                })?;
 3968                                let cursor_is_placed_after_comment_marker =
 3969                                    index_of_first_non_whitespace + comment_prefix.len()
 3970                                        <= start_point.column as usize;
 3971                                if cursor_is_placed_after_comment_marker {
 3972                                    Some(comment_prefix.clone())
 3973                                } else {
 3974                                    None
 3975                                }
 3976                            });
 3977                            (comment_delimiter, insert_extra_newline)
 3978                        } else {
 3979                            (None, false)
 3980                        };
 3981
 3982                        let capacity_for_delimiter = comment_delimiter
 3983                            .as_deref()
 3984                            .map(str::len)
 3985                            .unwrap_or_default();
 3986                        let mut new_text =
 3987                            String::with_capacity(1 + capacity_for_delimiter + indent.len as usize);
 3988                        new_text.push('\n');
 3989                        new_text.extend(indent.chars());
 3990                        if let Some(delimiter) = &comment_delimiter {
 3991                            new_text.push_str(delimiter);
 3992                        }
 3993                        if insert_extra_newline {
 3994                            new_text = new_text.repeat(2);
 3995                        }
 3996
 3997                        let anchor = buffer.anchor_after(end);
 3998                        let new_selection = selection.map(|_| anchor);
 3999                        (
 4000                            (start..end, new_text),
 4001                            (insert_extra_newline, new_selection),
 4002                        )
 4003                    })
 4004                    .unzip()
 4005            };
 4006
 4007            this.edit_with_autoindent(edits, cx);
 4008            let buffer = this.buffer.read(cx).snapshot(cx);
 4009            let new_selections = selection_fixup_info
 4010                .into_iter()
 4011                .map(|(extra_newline_inserted, new_selection)| {
 4012                    let mut cursor = new_selection.end.to_point(&buffer);
 4013                    if extra_newline_inserted {
 4014                        cursor.row -= 1;
 4015                        cursor.column = buffer.line_len(MultiBufferRow(cursor.row));
 4016                    }
 4017                    new_selection.map(|_| cursor)
 4018                })
 4019                .collect();
 4020
 4021            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 4022                s.select(new_selections)
 4023            });
 4024            this.refresh_inline_completion(true, false, window, cx);
 4025        });
 4026    }
 4027
 4028    pub fn newline_above(&mut self, _: &NewlineAbove, window: &mut Window, cx: &mut Context<Self>) {
 4029        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
 4030
 4031        let buffer = self.buffer.read(cx);
 4032        let snapshot = buffer.snapshot(cx);
 4033
 4034        let mut edits = Vec::new();
 4035        let mut rows = Vec::new();
 4036
 4037        for (rows_inserted, selection) in self.selections.all_adjusted(cx).into_iter().enumerate() {
 4038            let cursor = selection.head();
 4039            let row = cursor.row;
 4040
 4041            let start_of_line = snapshot.clip_point(Point::new(row, 0), Bias::Left);
 4042
 4043            let newline = "\n".to_string();
 4044            edits.push((start_of_line..start_of_line, newline));
 4045
 4046            rows.push(row + rows_inserted as u32);
 4047        }
 4048
 4049        self.transact(window, cx, |editor, window, cx| {
 4050            editor.edit(edits, cx);
 4051
 4052            editor.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 4053                let mut index = 0;
 4054                s.move_cursors_with(|map, _, _| {
 4055                    let row = rows[index];
 4056                    index += 1;
 4057
 4058                    let point = Point::new(row, 0);
 4059                    let boundary = map.next_line_boundary(point).1;
 4060                    let clipped = map.clip_point(boundary, Bias::Left);
 4061
 4062                    (clipped, SelectionGoal::None)
 4063                });
 4064            });
 4065
 4066            let mut indent_edits = Vec::new();
 4067            let multibuffer_snapshot = editor.buffer.read(cx).snapshot(cx);
 4068            for row in rows {
 4069                let indents = multibuffer_snapshot.suggested_indents(row..row + 1, cx);
 4070                for (row, indent) in indents {
 4071                    if indent.len == 0 {
 4072                        continue;
 4073                    }
 4074
 4075                    let text = match indent.kind {
 4076                        IndentKind::Space => " ".repeat(indent.len as usize),
 4077                        IndentKind::Tab => "\t".repeat(indent.len as usize),
 4078                    };
 4079                    let point = Point::new(row.0, 0);
 4080                    indent_edits.push((point..point, text));
 4081                }
 4082            }
 4083            editor.edit(indent_edits, cx);
 4084        });
 4085    }
 4086
 4087    pub fn newline_below(&mut self, _: &NewlineBelow, window: &mut Window, cx: &mut Context<Self>) {
 4088        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
 4089
 4090        let buffer = self.buffer.read(cx);
 4091        let snapshot = buffer.snapshot(cx);
 4092
 4093        let mut edits = Vec::new();
 4094        let mut rows = Vec::new();
 4095        let mut rows_inserted = 0;
 4096
 4097        for selection in self.selections.all_adjusted(cx) {
 4098            let cursor = selection.head();
 4099            let row = cursor.row;
 4100
 4101            let point = Point::new(row + 1, 0);
 4102            let start_of_line = snapshot.clip_point(point, Bias::Left);
 4103
 4104            let newline = "\n".to_string();
 4105            edits.push((start_of_line..start_of_line, newline));
 4106
 4107            rows_inserted += 1;
 4108            rows.push(row + rows_inserted);
 4109        }
 4110
 4111        self.transact(window, cx, |editor, window, cx| {
 4112            editor.edit(edits, cx);
 4113
 4114            editor.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 4115                let mut index = 0;
 4116                s.move_cursors_with(|map, _, _| {
 4117                    let row = rows[index];
 4118                    index += 1;
 4119
 4120                    let point = Point::new(row, 0);
 4121                    let boundary = map.next_line_boundary(point).1;
 4122                    let clipped = map.clip_point(boundary, Bias::Left);
 4123
 4124                    (clipped, SelectionGoal::None)
 4125                });
 4126            });
 4127
 4128            let mut indent_edits = Vec::new();
 4129            let multibuffer_snapshot = editor.buffer.read(cx).snapshot(cx);
 4130            for row in rows {
 4131                let indents = multibuffer_snapshot.suggested_indents(row..row + 1, cx);
 4132                for (row, indent) in indents {
 4133                    if indent.len == 0 {
 4134                        continue;
 4135                    }
 4136
 4137                    let text = match indent.kind {
 4138                        IndentKind::Space => " ".repeat(indent.len as usize),
 4139                        IndentKind::Tab => "\t".repeat(indent.len as usize),
 4140                    };
 4141                    let point = Point::new(row.0, 0);
 4142                    indent_edits.push((point..point, text));
 4143                }
 4144            }
 4145            editor.edit(indent_edits, cx);
 4146        });
 4147    }
 4148
 4149    pub fn insert(&mut self, text: &str, window: &mut Window, cx: &mut Context<Self>) {
 4150        let autoindent = text.is_empty().not().then(|| AutoindentMode::Block {
 4151            original_indent_columns: Vec::new(),
 4152        });
 4153        self.insert_with_autoindent_mode(text, autoindent, window, cx);
 4154    }
 4155
 4156    fn insert_with_autoindent_mode(
 4157        &mut self,
 4158        text: &str,
 4159        autoindent_mode: Option<AutoindentMode>,
 4160        window: &mut Window,
 4161        cx: &mut Context<Self>,
 4162    ) {
 4163        if self.read_only(cx) {
 4164            return;
 4165        }
 4166
 4167        let text: Arc<str> = text.into();
 4168        self.transact(window, cx, |this, window, cx| {
 4169            let old_selections = this.selections.all_adjusted(cx);
 4170            let selection_anchors = this.buffer.update(cx, |buffer, cx| {
 4171                let anchors = {
 4172                    let snapshot = buffer.read(cx);
 4173                    old_selections
 4174                        .iter()
 4175                        .map(|s| {
 4176                            let anchor = snapshot.anchor_after(s.head());
 4177                            s.map(|_| anchor)
 4178                        })
 4179                        .collect::<Vec<_>>()
 4180                };
 4181                buffer.edit(
 4182                    old_selections
 4183                        .iter()
 4184                        .map(|s| (s.start..s.end, text.clone())),
 4185                    autoindent_mode,
 4186                    cx,
 4187                );
 4188                anchors
 4189            });
 4190
 4191            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 4192                s.select_anchors(selection_anchors);
 4193            });
 4194
 4195            cx.notify();
 4196        });
 4197    }
 4198
 4199    fn trigger_completion_on_input(
 4200        &mut self,
 4201        text: &str,
 4202        trigger_in_words: bool,
 4203        window: &mut Window,
 4204        cx: &mut Context<Self>,
 4205    ) {
 4206        let ignore_completion_provider = self
 4207            .context_menu
 4208            .borrow()
 4209            .as_ref()
 4210            .map(|menu| match menu {
 4211                CodeContextMenu::Completions(completions_menu) => {
 4212                    completions_menu.ignore_completion_provider
 4213                }
 4214                CodeContextMenu::CodeActions(_) => false,
 4215            })
 4216            .unwrap_or(false);
 4217
 4218        if ignore_completion_provider {
 4219            self.show_word_completions(&ShowWordCompletions, window, cx);
 4220        } else if self.is_completion_trigger(text, trigger_in_words, cx) {
 4221            self.show_completions(
 4222                &ShowCompletions {
 4223                    trigger: Some(text.to_owned()).filter(|x| !x.is_empty()),
 4224                },
 4225                window,
 4226                cx,
 4227            );
 4228        } else {
 4229            self.hide_context_menu(window, cx);
 4230        }
 4231    }
 4232
 4233    fn is_completion_trigger(
 4234        &self,
 4235        text: &str,
 4236        trigger_in_words: bool,
 4237        cx: &mut Context<Self>,
 4238    ) -> bool {
 4239        let position = self.selections.newest_anchor().head();
 4240        let multibuffer = self.buffer.read(cx);
 4241        let Some(buffer) = position
 4242            .buffer_id
 4243            .and_then(|buffer_id| multibuffer.buffer(buffer_id).clone())
 4244        else {
 4245            return false;
 4246        };
 4247
 4248        if let Some(completion_provider) = &self.completion_provider {
 4249            completion_provider.is_completion_trigger(
 4250                &buffer,
 4251                position.text_anchor,
 4252                text,
 4253                trigger_in_words,
 4254                cx,
 4255            )
 4256        } else {
 4257            false
 4258        }
 4259    }
 4260
 4261    /// If any empty selections is touching the start of its innermost containing autoclose
 4262    /// region, expand it to select the brackets.
 4263    fn select_autoclose_pair(&mut self, window: &mut Window, cx: &mut Context<Self>) {
 4264        let selections = self.selections.all::<usize>(cx);
 4265        let buffer = self.buffer.read(cx).read(cx);
 4266        let new_selections = self
 4267            .selections_with_autoclose_regions(selections, &buffer)
 4268            .map(|(mut selection, region)| {
 4269                if !selection.is_empty() {
 4270                    return selection;
 4271                }
 4272
 4273                if let Some(region) = region {
 4274                    let mut range = region.range.to_offset(&buffer);
 4275                    if selection.start == range.start && range.start >= region.pair.start.len() {
 4276                        range.start -= region.pair.start.len();
 4277                        if buffer.contains_str_at(range.start, &region.pair.start)
 4278                            && buffer.contains_str_at(range.end, &region.pair.end)
 4279                        {
 4280                            range.end += region.pair.end.len();
 4281                            selection.start = range.start;
 4282                            selection.end = range.end;
 4283
 4284                            return selection;
 4285                        }
 4286                    }
 4287                }
 4288
 4289                let always_treat_brackets_as_autoclosed = buffer
 4290                    .language_settings_at(selection.start, cx)
 4291                    .always_treat_brackets_as_autoclosed;
 4292
 4293                if !always_treat_brackets_as_autoclosed {
 4294                    return selection;
 4295                }
 4296
 4297                if let Some(scope) = buffer.language_scope_at(selection.start) {
 4298                    for (pair, enabled) in scope.brackets() {
 4299                        if !enabled || !pair.close {
 4300                            continue;
 4301                        }
 4302
 4303                        if buffer.contains_str_at(selection.start, &pair.end) {
 4304                            let pair_start_len = pair.start.len();
 4305                            if buffer.contains_str_at(
 4306                                selection.start.saturating_sub(pair_start_len),
 4307                                &pair.start,
 4308                            ) {
 4309                                selection.start -= pair_start_len;
 4310                                selection.end += pair.end.len();
 4311
 4312                                return selection;
 4313                            }
 4314                        }
 4315                    }
 4316                }
 4317
 4318                selection
 4319            })
 4320            .collect();
 4321
 4322        drop(buffer);
 4323        self.change_selections(None, window, cx, |selections| {
 4324            selections.select(new_selections)
 4325        });
 4326    }
 4327
 4328    /// Iterate the given selections, and for each one, find the smallest surrounding
 4329    /// autoclose region. This uses the ordering of the selections and the autoclose
 4330    /// regions to avoid repeated comparisons.
 4331    fn selections_with_autoclose_regions<'a, D: ToOffset + Clone>(
 4332        &'a self,
 4333        selections: impl IntoIterator<Item = Selection<D>>,
 4334        buffer: &'a MultiBufferSnapshot,
 4335    ) -> impl Iterator<Item = (Selection<D>, Option<&'a AutocloseRegion>)> {
 4336        let mut i = 0;
 4337        let mut regions = self.autoclose_regions.as_slice();
 4338        selections.into_iter().map(move |selection| {
 4339            let range = selection.start.to_offset(buffer)..selection.end.to_offset(buffer);
 4340
 4341            let mut enclosing = None;
 4342            while let Some(pair_state) = regions.get(i) {
 4343                if pair_state.range.end.to_offset(buffer) < range.start {
 4344                    regions = &regions[i + 1..];
 4345                    i = 0;
 4346                } else if pair_state.range.start.to_offset(buffer) > range.end {
 4347                    break;
 4348                } else {
 4349                    if pair_state.selection_id == selection.id {
 4350                        enclosing = Some(pair_state);
 4351                    }
 4352                    i += 1;
 4353                }
 4354            }
 4355
 4356            (selection, enclosing)
 4357        })
 4358    }
 4359
 4360    /// Remove any autoclose regions that no longer contain their selection.
 4361    fn invalidate_autoclose_regions(
 4362        &mut self,
 4363        mut selections: &[Selection<Anchor>],
 4364        buffer: &MultiBufferSnapshot,
 4365    ) {
 4366        self.autoclose_regions.retain(|state| {
 4367            let mut i = 0;
 4368            while let Some(selection) = selections.get(i) {
 4369                if selection.end.cmp(&state.range.start, buffer).is_lt() {
 4370                    selections = &selections[1..];
 4371                    continue;
 4372                }
 4373                if selection.start.cmp(&state.range.end, buffer).is_gt() {
 4374                    break;
 4375                }
 4376                if selection.id == state.selection_id {
 4377                    return true;
 4378                } else {
 4379                    i += 1;
 4380                }
 4381            }
 4382            false
 4383        });
 4384    }
 4385
 4386    fn completion_query(buffer: &MultiBufferSnapshot, position: impl ToOffset) -> Option<String> {
 4387        let offset = position.to_offset(buffer);
 4388        let (word_range, kind) = buffer.surrounding_word(offset, true);
 4389        if offset > word_range.start && kind == Some(CharKind::Word) {
 4390            Some(
 4391                buffer
 4392                    .text_for_range(word_range.start..offset)
 4393                    .collect::<String>(),
 4394            )
 4395        } else {
 4396            None
 4397        }
 4398    }
 4399
 4400    pub fn toggle_inline_values(
 4401        &mut self,
 4402        _: &ToggleInlineValues,
 4403        _: &mut Window,
 4404        cx: &mut Context<Self>,
 4405    ) {
 4406        self.inline_value_cache.enabled = !self.inline_value_cache.enabled;
 4407
 4408        self.refresh_inline_values(cx);
 4409    }
 4410
 4411    pub fn toggle_inlay_hints(
 4412        &mut self,
 4413        _: &ToggleInlayHints,
 4414        _: &mut Window,
 4415        cx: &mut Context<Self>,
 4416    ) {
 4417        self.refresh_inlay_hints(
 4418            InlayHintRefreshReason::Toggle(!self.inlay_hints_enabled()),
 4419            cx,
 4420        );
 4421    }
 4422
 4423    pub fn inlay_hints_enabled(&self) -> bool {
 4424        self.inlay_hint_cache.enabled
 4425    }
 4426
 4427    pub fn inline_values_enabled(&self) -> bool {
 4428        self.inline_value_cache.enabled
 4429    }
 4430
 4431    #[cfg(any(test, feature = "test-support"))]
 4432    pub fn inline_value_inlays(&self, cx: &App) -> Vec<Inlay> {
 4433        self.display_map
 4434            .read(cx)
 4435            .current_inlays()
 4436            .filter(|inlay| matches!(inlay.id, InlayId::DebuggerValue(_)))
 4437            .cloned()
 4438            .collect()
 4439    }
 4440
 4441    fn refresh_inlay_hints(&mut self, reason: InlayHintRefreshReason, cx: &mut Context<Self>) {
 4442        if self.semantics_provider.is_none() || !self.mode.is_full() {
 4443            return;
 4444        }
 4445
 4446        let reason_description = reason.description();
 4447        let ignore_debounce = matches!(
 4448            reason,
 4449            InlayHintRefreshReason::SettingsChange(_)
 4450                | InlayHintRefreshReason::Toggle(_)
 4451                | InlayHintRefreshReason::ExcerptsRemoved(_)
 4452                | InlayHintRefreshReason::ModifiersChanged(_)
 4453        );
 4454        let (invalidate_cache, required_languages) = match reason {
 4455            InlayHintRefreshReason::ModifiersChanged(enabled) => {
 4456                match self.inlay_hint_cache.modifiers_override(enabled) {
 4457                    Some(enabled) => {
 4458                        if enabled {
 4459                            (InvalidationStrategy::RefreshRequested, None)
 4460                        } else {
 4461                            self.splice_inlays(
 4462                                &self
 4463                                    .visible_inlay_hints(cx)
 4464                                    .iter()
 4465                                    .map(|inlay| inlay.id)
 4466                                    .collect::<Vec<InlayId>>(),
 4467                                Vec::new(),
 4468                                cx,
 4469                            );
 4470                            return;
 4471                        }
 4472                    }
 4473                    None => return,
 4474                }
 4475            }
 4476            InlayHintRefreshReason::Toggle(enabled) => {
 4477                if self.inlay_hint_cache.toggle(enabled) {
 4478                    if enabled {
 4479                        (InvalidationStrategy::RefreshRequested, None)
 4480                    } else {
 4481                        self.splice_inlays(
 4482                            &self
 4483                                .visible_inlay_hints(cx)
 4484                                .iter()
 4485                                .map(|inlay| inlay.id)
 4486                                .collect::<Vec<InlayId>>(),
 4487                            Vec::new(),
 4488                            cx,
 4489                        );
 4490                        return;
 4491                    }
 4492                } else {
 4493                    return;
 4494                }
 4495            }
 4496            InlayHintRefreshReason::SettingsChange(new_settings) => {
 4497                match self.inlay_hint_cache.update_settings(
 4498                    &self.buffer,
 4499                    new_settings,
 4500                    self.visible_inlay_hints(cx),
 4501                    cx,
 4502                ) {
 4503                    ControlFlow::Break(Some(InlaySplice {
 4504                        to_remove,
 4505                        to_insert,
 4506                    })) => {
 4507                        self.splice_inlays(&to_remove, to_insert, cx);
 4508                        return;
 4509                    }
 4510                    ControlFlow::Break(None) => return,
 4511                    ControlFlow::Continue(()) => (InvalidationStrategy::RefreshRequested, None),
 4512                }
 4513            }
 4514            InlayHintRefreshReason::ExcerptsRemoved(excerpts_removed) => {
 4515                if let Some(InlaySplice {
 4516                    to_remove,
 4517                    to_insert,
 4518                }) = self.inlay_hint_cache.remove_excerpts(&excerpts_removed)
 4519                {
 4520                    self.splice_inlays(&to_remove, to_insert, cx);
 4521                }
 4522                self.display_map.update(cx, |display_map, _| {
 4523                    display_map.remove_inlays_for_excerpts(&excerpts_removed)
 4524                });
 4525                return;
 4526            }
 4527            InlayHintRefreshReason::NewLinesShown => (InvalidationStrategy::None, None),
 4528            InlayHintRefreshReason::BufferEdited(buffer_languages) => {
 4529                (InvalidationStrategy::BufferEdited, Some(buffer_languages))
 4530            }
 4531            InlayHintRefreshReason::RefreshRequested => {
 4532                (InvalidationStrategy::RefreshRequested, None)
 4533            }
 4534        };
 4535
 4536        if let Some(InlaySplice {
 4537            to_remove,
 4538            to_insert,
 4539        }) = self.inlay_hint_cache.spawn_hint_refresh(
 4540            reason_description,
 4541            self.excerpts_for_inlay_hints_query(required_languages.as_ref(), cx),
 4542            invalidate_cache,
 4543            ignore_debounce,
 4544            cx,
 4545        ) {
 4546            self.splice_inlays(&to_remove, to_insert, cx);
 4547        }
 4548    }
 4549
 4550    fn visible_inlay_hints(&self, cx: &Context<Editor>) -> Vec<Inlay> {
 4551        self.display_map
 4552            .read(cx)
 4553            .current_inlays()
 4554            .filter(move |inlay| matches!(inlay.id, InlayId::Hint(_)))
 4555            .cloned()
 4556            .collect()
 4557    }
 4558
 4559    pub fn excerpts_for_inlay_hints_query(
 4560        &self,
 4561        restrict_to_languages: Option<&HashSet<Arc<Language>>>,
 4562        cx: &mut Context<Editor>,
 4563    ) -> HashMap<ExcerptId, (Entity<Buffer>, clock::Global, Range<usize>)> {
 4564        let Some(project) = self.project.as_ref() else {
 4565            return HashMap::default();
 4566        };
 4567        let project = project.read(cx);
 4568        let multi_buffer = self.buffer().read(cx);
 4569        let multi_buffer_snapshot = multi_buffer.snapshot(cx);
 4570        let multi_buffer_visible_start = self
 4571            .scroll_manager
 4572            .anchor()
 4573            .anchor
 4574            .to_point(&multi_buffer_snapshot);
 4575        let multi_buffer_visible_end = multi_buffer_snapshot.clip_point(
 4576            multi_buffer_visible_start
 4577                + Point::new(self.visible_line_count().unwrap_or(0.).ceil() as u32, 0),
 4578            Bias::Left,
 4579        );
 4580        let multi_buffer_visible_range = multi_buffer_visible_start..multi_buffer_visible_end;
 4581        multi_buffer_snapshot
 4582            .range_to_buffer_ranges(multi_buffer_visible_range)
 4583            .into_iter()
 4584            .filter(|(_, excerpt_visible_range, _)| !excerpt_visible_range.is_empty())
 4585            .filter_map(|(buffer, excerpt_visible_range, excerpt_id)| {
 4586                let buffer_file = project::File::from_dyn(buffer.file())?;
 4587                let buffer_worktree = project.worktree_for_id(buffer_file.worktree_id(cx), cx)?;
 4588                let worktree_entry = buffer_worktree
 4589                    .read(cx)
 4590                    .entry_for_id(buffer_file.project_entry_id(cx)?)?;
 4591                if worktree_entry.is_ignored {
 4592                    return None;
 4593                }
 4594
 4595                let language = buffer.language()?;
 4596                if let Some(restrict_to_languages) = restrict_to_languages {
 4597                    if !restrict_to_languages.contains(language) {
 4598                        return None;
 4599                    }
 4600                }
 4601                Some((
 4602                    excerpt_id,
 4603                    (
 4604                        multi_buffer.buffer(buffer.remote_id()).unwrap(),
 4605                        buffer.version().clone(),
 4606                        excerpt_visible_range,
 4607                    ),
 4608                ))
 4609            })
 4610            .collect()
 4611    }
 4612
 4613    pub fn text_layout_details(&self, window: &mut Window) -> TextLayoutDetails {
 4614        TextLayoutDetails {
 4615            text_system: window.text_system().clone(),
 4616            editor_style: self.style.clone().unwrap(),
 4617            rem_size: window.rem_size(),
 4618            scroll_anchor: self.scroll_manager.anchor(),
 4619            visible_rows: self.visible_line_count(),
 4620            vertical_scroll_margin: self.scroll_manager.vertical_scroll_margin,
 4621        }
 4622    }
 4623
 4624    pub fn splice_inlays(
 4625        &self,
 4626        to_remove: &[InlayId],
 4627        to_insert: Vec<Inlay>,
 4628        cx: &mut Context<Self>,
 4629    ) {
 4630        self.display_map.update(cx, |display_map, cx| {
 4631            display_map.splice_inlays(to_remove, to_insert, cx)
 4632        });
 4633        cx.notify();
 4634    }
 4635
 4636    fn trigger_on_type_formatting(
 4637        &self,
 4638        input: String,
 4639        window: &mut Window,
 4640        cx: &mut Context<Self>,
 4641    ) -> Option<Task<Result<()>>> {
 4642        if input.len() != 1 {
 4643            return None;
 4644        }
 4645
 4646        let project = self.project.as_ref()?;
 4647        let position = self.selections.newest_anchor().head();
 4648        let (buffer, buffer_position) = self
 4649            .buffer
 4650            .read(cx)
 4651            .text_anchor_for_position(position, cx)?;
 4652
 4653        let settings = language_settings::language_settings(
 4654            buffer
 4655                .read(cx)
 4656                .language_at(buffer_position)
 4657                .map(|l| l.name()),
 4658            buffer.read(cx).file(),
 4659            cx,
 4660        );
 4661        if !settings.use_on_type_format {
 4662            return None;
 4663        }
 4664
 4665        // OnTypeFormatting returns a list of edits, no need to pass them between Zed instances,
 4666        // hence we do LSP request & edit on host side only — add formats to host's history.
 4667        let push_to_lsp_host_history = true;
 4668        // If this is not the host, append its history with new edits.
 4669        let push_to_client_history = project.read(cx).is_via_collab();
 4670
 4671        let on_type_formatting = project.update(cx, |project, cx| {
 4672            project.on_type_format(
 4673                buffer.clone(),
 4674                buffer_position,
 4675                input,
 4676                push_to_lsp_host_history,
 4677                cx,
 4678            )
 4679        });
 4680        Some(cx.spawn_in(window, async move |editor, cx| {
 4681            if let Some(transaction) = on_type_formatting.await? {
 4682                if push_to_client_history {
 4683                    buffer
 4684                        .update(cx, |buffer, _| {
 4685                            buffer.push_transaction(transaction, Instant::now());
 4686                            buffer.finalize_last_transaction();
 4687                        })
 4688                        .ok();
 4689                }
 4690                editor.update(cx, |editor, cx| {
 4691                    editor.refresh_document_highlights(cx);
 4692                })?;
 4693            }
 4694            Ok(())
 4695        }))
 4696    }
 4697
 4698    pub fn show_word_completions(
 4699        &mut self,
 4700        _: &ShowWordCompletions,
 4701        window: &mut Window,
 4702        cx: &mut Context<Self>,
 4703    ) {
 4704        self.open_completions_menu(true, None, window, cx);
 4705    }
 4706
 4707    pub fn show_completions(
 4708        &mut self,
 4709        options: &ShowCompletions,
 4710        window: &mut Window,
 4711        cx: &mut Context<Self>,
 4712    ) {
 4713        self.open_completions_menu(false, options.trigger.as_deref(), window, cx);
 4714    }
 4715
 4716    fn open_completions_menu(
 4717        &mut self,
 4718        ignore_completion_provider: bool,
 4719        trigger: Option<&str>,
 4720        window: &mut Window,
 4721        cx: &mut Context<Self>,
 4722    ) {
 4723        if self.pending_rename.is_some() {
 4724            return;
 4725        }
 4726        if !self.snippet_stack.is_empty() && self.context_menu.borrow().as_ref().is_some() {
 4727            return;
 4728        }
 4729
 4730        let position = self.selections.newest_anchor().head();
 4731        if position.diff_base_anchor.is_some() {
 4732            return;
 4733        }
 4734        let (buffer, buffer_position) =
 4735            if let Some(output) = self.buffer.read(cx).text_anchor_for_position(position, cx) {
 4736                output
 4737            } else {
 4738                return;
 4739            };
 4740        let buffer_snapshot = buffer.read(cx).snapshot();
 4741        let show_completion_documentation = buffer_snapshot
 4742            .settings_at(buffer_position, cx)
 4743            .show_completion_documentation;
 4744
 4745        let query = Self::completion_query(&self.buffer.read(cx).read(cx), position);
 4746
 4747        let trigger_kind = match trigger {
 4748            Some(trigger) if buffer.read(cx).completion_triggers().contains(trigger) => {
 4749                CompletionTriggerKind::TRIGGER_CHARACTER
 4750            }
 4751            _ => CompletionTriggerKind::INVOKED,
 4752        };
 4753        let completion_context = CompletionContext {
 4754            trigger_character: trigger.and_then(|trigger| {
 4755                if trigger_kind == CompletionTriggerKind::TRIGGER_CHARACTER {
 4756                    Some(String::from(trigger))
 4757                } else {
 4758                    None
 4759                }
 4760            }),
 4761            trigger_kind,
 4762        };
 4763
 4764        let (old_range, word_kind) = buffer_snapshot.surrounding_word(buffer_position);
 4765        let (old_range, word_to_exclude) = if word_kind == Some(CharKind::Word) {
 4766            let word_to_exclude = buffer_snapshot
 4767                .text_for_range(old_range.clone())
 4768                .collect::<String>();
 4769            (
 4770                buffer_snapshot.anchor_before(old_range.start)
 4771                    ..buffer_snapshot.anchor_after(old_range.end),
 4772                Some(word_to_exclude),
 4773            )
 4774        } else {
 4775            (buffer_position..buffer_position, None)
 4776        };
 4777
 4778        let completion_settings = language_settings(
 4779            buffer_snapshot
 4780                .language_at(buffer_position)
 4781                .map(|language| language.name()),
 4782            buffer_snapshot.file(),
 4783            cx,
 4784        )
 4785        .completions;
 4786
 4787        // The document can be large, so stay in reasonable bounds when searching for words,
 4788        // otherwise completion pop-up might be slow to appear.
 4789        const WORD_LOOKUP_ROWS: u32 = 5_000;
 4790        let buffer_row = text::ToPoint::to_point(&buffer_position, &buffer_snapshot).row;
 4791        let min_word_search = buffer_snapshot.clip_point(
 4792            Point::new(buffer_row.saturating_sub(WORD_LOOKUP_ROWS), 0),
 4793            Bias::Left,
 4794        );
 4795        let max_word_search = buffer_snapshot.clip_point(
 4796            Point::new(buffer_row + WORD_LOOKUP_ROWS, 0).min(buffer_snapshot.max_point()),
 4797            Bias::Right,
 4798        );
 4799        let word_search_range = buffer_snapshot.point_to_offset(min_word_search)
 4800            ..buffer_snapshot.point_to_offset(max_word_search);
 4801
 4802        let provider = self
 4803            .completion_provider
 4804            .as_ref()
 4805            .filter(|_| !ignore_completion_provider);
 4806        let skip_digits = query
 4807            .as_ref()
 4808            .map_or(true, |query| !query.chars().any(|c| c.is_digit(10)));
 4809
 4810        let (mut words, provided_completions) = match provider {
 4811            Some(provider) => {
 4812                let completions = provider.completions(
 4813                    position.excerpt_id,
 4814                    &buffer,
 4815                    buffer_position,
 4816                    completion_context,
 4817                    window,
 4818                    cx,
 4819                );
 4820
 4821                let words = match completion_settings.words {
 4822                    WordsCompletionMode::Disabled => Task::ready(BTreeMap::default()),
 4823                    WordsCompletionMode::Enabled | WordsCompletionMode::Fallback => cx
 4824                        .background_spawn(async move {
 4825                            buffer_snapshot.words_in_range(WordsQuery {
 4826                                fuzzy_contents: None,
 4827                                range: word_search_range,
 4828                                skip_digits,
 4829                            })
 4830                        }),
 4831                };
 4832
 4833                (words, completions)
 4834            }
 4835            None => (
 4836                cx.background_spawn(async move {
 4837                    buffer_snapshot.words_in_range(WordsQuery {
 4838                        fuzzy_contents: None,
 4839                        range: word_search_range,
 4840                        skip_digits,
 4841                    })
 4842                }),
 4843                Task::ready(Ok(None)),
 4844            ),
 4845        };
 4846
 4847        let sort_completions = provider
 4848            .as_ref()
 4849            .map_or(false, |provider| provider.sort_completions());
 4850
 4851        let filter_completions = provider
 4852            .as_ref()
 4853            .map_or(true, |provider| provider.filter_completions());
 4854
 4855        let snippet_sort_order = EditorSettings::get_global(cx).snippet_sort_order;
 4856
 4857        let id = post_inc(&mut self.next_completion_id);
 4858        let task = cx.spawn_in(window, async move |editor, cx| {
 4859            async move {
 4860                editor.update(cx, |this, _| {
 4861                    this.completion_tasks.retain(|(task_id, _)| *task_id >= id);
 4862                })?;
 4863
 4864                let mut completions = Vec::new();
 4865                if let Some(provided_completions) = provided_completions.await.log_err().flatten() {
 4866                    completions.extend(provided_completions);
 4867                    if completion_settings.words == WordsCompletionMode::Fallback {
 4868                        words = Task::ready(BTreeMap::default());
 4869                    }
 4870                }
 4871
 4872                let mut words = words.await;
 4873                if let Some(word_to_exclude) = &word_to_exclude {
 4874                    words.remove(word_to_exclude);
 4875                }
 4876                for lsp_completion in &completions {
 4877                    words.remove(&lsp_completion.new_text);
 4878                }
 4879                completions.extend(words.into_iter().map(|(word, word_range)| Completion {
 4880                    replace_range: old_range.clone(),
 4881                    new_text: word.clone(),
 4882                    label: CodeLabel::plain(word, None),
 4883                    icon_path: None,
 4884                    documentation: None,
 4885                    source: CompletionSource::BufferWord {
 4886                        word_range,
 4887                        resolved: false,
 4888                    },
 4889                    insert_text_mode: Some(InsertTextMode::AS_IS),
 4890                    confirm: None,
 4891                }));
 4892
 4893                let menu = if completions.is_empty() {
 4894                    None
 4895                } else {
 4896                    let mut menu = CompletionsMenu::new(
 4897                        id,
 4898                        sort_completions,
 4899                        show_completion_documentation,
 4900                        ignore_completion_provider,
 4901                        position,
 4902                        buffer.clone(),
 4903                        completions.into(),
 4904                        snippet_sort_order,
 4905                    );
 4906
 4907                    menu.filter(
 4908                        if filter_completions {
 4909                            query.as_deref()
 4910                        } else {
 4911                            None
 4912                        },
 4913                        cx.background_executor().clone(),
 4914                    )
 4915                    .await;
 4916
 4917                    menu.visible().then_some(menu)
 4918                };
 4919
 4920                editor.update_in(cx, |editor, window, cx| {
 4921                    match editor.context_menu.borrow().as_ref() {
 4922                        None => {}
 4923                        Some(CodeContextMenu::Completions(prev_menu)) => {
 4924                            if prev_menu.id > id {
 4925                                return;
 4926                            }
 4927                        }
 4928                        _ => return,
 4929                    }
 4930
 4931                    if editor.focus_handle.is_focused(window) && menu.is_some() {
 4932                        let mut menu = menu.unwrap();
 4933                        menu.resolve_visible_completions(editor.completion_provider.as_deref(), cx);
 4934
 4935                        *editor.context_menu.borrow_mut() =
 4936                            Some(CodeContextMenu::Completions(menu));
 4937
 4938                        if editor.show_edit_predictions_in_menu() {
 4939                            editor.update_visible_inline_completion(window, cx);
 4940                        } else {
 4941                            editor.discard_inline_completion(false, cx);
 4942                        }
 4943
 4944                        cx.notify();
 4945                    } else if editor.completion_tasks.len() <= 1 {
 4946                        // If there are no more completion tasks and the last menu was
 4947                        // empty, we should hide it.
 4948                        let was_hidden = editor.hide_context_menu(window, cx).is_none();
 4949                        // If it was already hidden and we don't show inline
 4950                        // completions in the menu, we should also show the
 4951                        // inline-completion when available.
 4952                        if was_hidden && editor.show_edit_predictions_in_menu() {
 4953                            editor.update_visible_inline_completion(window, cx);
 4954                        }
 4955                    }
 4956                })?;
 4957
 4958                anyhow::Ok(())
 4959            }
 4960            .log_err()
 4961            .await
 4962        });
 4963
 4964        self.completion_tasks.push((id, task));
 4965    }
 4966
 4967    #[cfg(feature = "test-support")]
 4968    pub fn current_completions(&self) -> Option<Vec<project::Completion>> {
 4969        let menu = self.context_menu.borrow();
 4970        if let CodeContextMenu::Completions(menu) = menu.as_ref()? {
 4971            let completions = menu.completions.borrow();
 4972            Some(completions.to_vec())
 4973        } else {
 4974            None
 4975        }
 4976    }
 4977
 4978    pub fn confirm_completion(
 4979        &mut self,
 4980        action: &ConfirmCompletion,
 4981        window: &mut Window,
 4982        cx: &mut Context<Self>,
 4983    ) -> Option<Task<Result<()>>> {
 4984        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
 4985        self.do_completion(action.item_ix, CompletionIntent::Complete, window, cx)
 4986    }
 4987
 4988    pub fn confirm_completion_insert(
 4989        &mut self,
 4990        _: &ConfirmCompletionInsert,
 4991        window: &mut Window,
 4992        cx: &mut Context<Self>,
 4993    ) -> Option<Task<Result<()>>> {
 4994        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
 4995        self.do_completion(None, CompletionIntent::CompleteWithInsert, window, cx)
 4996    }
 4997
 4998    pub fn confirm_completion_replace(
 4999        &mut self,
 5000        _: &ConfirmCompletionReplace,
 5001        window: &mut Window,
 5002        cx: &mut Context<Self>,
 5003    ) -> Option<Task<Result<()>>> {
 5004        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
 5005        self.do_completion(None, CompletionIntent::CompleteWithReplace, window, cx)
 5006    }
 5007
 5008    pub fn compose_completion(
 5009        &mut self,
 5010        action: &ComposeCompletion,
 5011        window: &mut Window,
 5012        cx: &mut Context<Self>,
 5013    ) -> Option<Task<Result<()>>> {
 5014        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
 5015        self.do_completion(action.item_ix, CompletionIntent::Compose, window, cx)
 5016    }
 5017
 5018    fn do_completion(
 5019        &mut self,
 5020        item_ix: Option<usize>,
 5021        intent: CompletionIntent,
 5022        window: &mut Window,
 5023        cx: &mut Context<Editor>,
 5024    ) -> Option<Task<Result<()>>> {
 5025        use language::ToOffset as _;
 5026
 5027        let CodeContextMenu::Completions(completions_menu) = self.hide_context_menu(window, cx)?
 5028        else {
 5029            return None;
 5030        };
 5031
 5032        let candidate_id = {
 5033            let entries = completions_menu.entries.borrow();
 5034            let mat = entries.get(item_ix.unwrap_or(completions_menu.selected_item))?;
 5035            if self.show_edit_predictions_in_menu() {
 5036                self.discard_inline_completion(true, cx);
 5037            }
 5038            mat.candidate_id
 5039        };
 5040
 5041        let buffer_handle = completions_menu.buffer;
 5042        let completion = completions_menu
 5043            .completions
 5044            .borrow()
 5045            .get(candidate_id)?
 5046            .clone();
 5047        cx.stop_propagation();
 5048
 5049        let snapshot = self.buffer.read(cx).snapshot(cx);
 5050        let newest_anchor = self.selections.newest_anchor();
 5051
 5052        let snippet;
 5053        let new_text;
 5054        if completion.is_snippet() {
 5055            let mut snippet_source = completion.new_text.clone();
 5056            if let Some(scope) = snapshot.language_scope_at(newest_anchor.head()) {
 5057                if scope.prefers_label_for_snippet_in_completion() {
 5058                    if let Some(label) = completion.label() {
 5059                        if matches!(
 5060                            completion.kind(),
 5061                            Some(CompletionItemKind::FUNCTION) | Some(CompletionItemKind::METHOD)
 5062                        ) {
 5063                            snippet_source = label;
 5064                        }
 5065                    }
 5066                }
 5067            }
 5068            snippet = Some(Snippet::parse(&snippet_source).log_err()?);
 5069            new_text = snippet.as_ref().unwrap().text.clone();
 5070        } else {
 5071            snippet = None;
 5072            new_text = completion.new_text.clone();
 5073        };
 5074
 5075        let replace_range = choose_completion_range(&completion, intent, &buffer_handle, cx);
 5076        let buffer = buffer_handle.read(cx);
 5077        let replace_range_multibuffer = {
 5078            let excerpt = snapshot.excerpt_containing(newest_anchor.range()).unwrap();
 5079            let multibuffer_anchor = snapshot
 5080                .anchor_in_excerpt(excerpt.id(), buffer.anchor_before(replace_range.start))
 5081                .unwrap()
 5082                ..snapshot
 5083                    .anchor_in_excerpt(excerpt.id(), buffer.anchor_before(replace_range.end))
 5084                    .unwrap();
 5085            multibuffer_anchor.start.to_offset(&snapshot)
 5086                ..multibuffer_anchor.end.to_offset(&snapshot)
 5087        };
 5088        if newest_anchor.head().buffer_id != Some(buffer.remote_id()) {
 5089            return None;
 5090        }
 5091
 5092        let old_text = buffer
 5093            .text_for_range(replace_range.clone())
 5094            .collect::<String>();
 5095        let lookbehind = newest_anchor
 5096            .start
 5097            .text_anchor
 5098            .to_offset(buffer)
 5099            .saturating_sub(replace_range.start);
 5100        let lookahead = replace_range
 5101            .end
 5102            .saturating_sub(newest_anchor.end.text_anchor.to_offset(buffer));
 5103        let prefix = &old_text[..old_text.len().saturating_sub(lookahead)];
 5104        let suffix = &old_text[lookbehind.min(old_text.len())..];
 5105
 5106        let selections = self.selections.all::<usize>(cx);
 5107        let mut ranges = Vec::new();
 5108        let mut linked_edits = HashMap::<_, Vec<_>>::default();
 5109
 5110        for selection in &selections {
 5111            let range = if selection.id == newest_anchor.id {
 5112                replace_range_multibuffer.clone()
 5113            } else {
 5114                let mut range = selection.range();
 5115
 5116                // if prefix is present, don't duplicate it
 5117                if snapshot.contains_str_at(range.start.saturating_sub(lookbehind), prefix) {
 5118                    range.start = range.start.saturating_sub(lookbehind);
 5119
 5120                    // if suffix is also present, mimic the newest cursor and replace it
 5121                    if selection.id != newest_anchor.id
 5122                        && snapshot.contains_str_at(range.end, suffix)
 5123                    {
 5124                        range.end += lookahead;
 5125                    }
 5126                }
 5127                range
 5128            };
 5129
 5130            ranges.push(range.clone());
 5131
 5132            if !self.linked_edit_ranges.is_empty() {
 5133                let start_anchor = snapshot.anchor_before(range.start);
 5134                let end_anchor = snapshot.anchor_after(range.end);
 5135                if let Some(ranges) = self
 5136                    .linked_editing_ranges_for(start_anchor.text_anchor..end_anchor.text_anchor, cx)
 5137                {
 5138                    for (buffer, edits) in ranges {
 5139                        linked_edits
 5140                            .entry(buffer.clone())
 5141                            .or_default()
 5142                            .extend(edits.into_iter().map(|range| (range, new_text.to_owned())));
 5143                    }
 5144                }
 5145            }
 5146        }
 5147
 5148        cx.emit(EditorEvent::InputHandled {
 5149            utf16_range_to_replace: None,
 5150            text: new_text.clone().into(),
 5151        });
 5152
 5153        self.transact(window, cx, |this, window, cx| {
 5154            if let Some(mut snippet) = snippet {
 5155                snippet.text = new_text.to_string();
 5156                this.insert_snippet(&ranges, snippet, window, cx).log_err();
 5157            } else {
 5158                this.buffer.update(cx, |buffer, cx| {
 5159                    let auto_indent = match completion.insert_text_mode {
 5160                        Some(InsertTextMode::AS_IS) => None,
 5161                        _ => this.autoindent_mode.clone(),
 5162                    };
 5163                    let edits = ranges.into_iter().map(|range| (range, new_text.as_str()));
 5164                    buffer.edit(edits, auto_indent, cx);
 5165                });
 5166            }
 5167            for (buffer, edits) in linked_edits {
 5168                buffer.update(cx, |buffer, cx| {
 5169                    let snapshot = buffer.snapshot();
 5170                    let edits = edits
 5171                        .into_iter()
 5172                        .map(|(range, text)| {
 5173                            use text::ToPoint as TP;
 5174                            let end_point = TP::to_point(&range.end, &snapshot);
 5175                            let start_point = TP::to_point(&range.start, &snapshot);
 5176                            (start_point..end_point, text)
 5177                        })
 5178                        .sorted_by_key(|(range, _)| range.start);
 5179                    buffer.edit(edits, None, cx);
 5180                })
 5181            }
 5182
 5183            this.refresh_inline_completion(true, false, window, cx);
 5184        });
 5185
 5186        let show_new_completions_on_confirm = completion
 5187            .confirm
 5188            .as_ref()
 5189            .map_or(false, |confirm| confirm(intent, window, cx));
 5190        if show_new_completions_on_confirm {
 5191            self.show_completions(&ShowCompletions { trigger: None }, window, cx);
 5192        }
 5193
 5194        let provider = self.completion_provider.as_ref()?;
 5195        drop(completion);
 5196        let apply_edits = provider.apply_additional_edits_for_completion(
 5197            buffer_handle,
 5198            completions_menu.completions.clone(),
 5199            candidate_id,
 5200            true,
 5201            cx,
 5202        );
 5203
 5204        let editor_settings = EditorSettings::get_global(cx);
 5205        if editor_settings.show_signature_help_after_edits || editor_settings.auto_signature_help {
 5206            // After the code completion is finished, users often want to know what signatures are needed.
 5207            // so we should automatically call signature_help
 5208            self.show_signature_help(&ShowSignatureHelp, window, cx);
 5209        }
 5210
 5211        Some(cx.foreground_executor().spawn(async move {
 5212            apply_edits.await?;
 5213            Ok(())
 5214        }))
 5215    }
 5216
 5217    pub fn toggle_code_actions(
 5218        &mut self,
 5219        action: &ToggleCodeActions,
 5220        window: &mut Window,
 5221        cx: &mut Context<Self>,
 5222    ) {
 5223        let quick_launch = action.quick_launch;
 5224        let mut context_menu = self.context_menu.borrow_mut();
 5225        if let Some(CodeContextMenu::CodeActions(code_actions)) = context_menu.as_ref() {
 5226            if code_actions.deployed_from_indicator == action.deployed_from_indicator {
 5227                // Toggle if we're selecting the same one
 5228                *context_menu = None;
 5229                cx.notify();
 5230                return;
 5231            } else {
 5232                // Otherwise, clear it and start a new one
 5233                *context_menu = None;
 5234                cx.notify();
 5235            }
 5236        }
 5237        drop(context_menu);
 5238        let snapshot = self.snapshot(window, cx);
 5239        let deployed_from_indicator = action.deployed_from_indicator;
 5240        let mut task = self.code_actions_task.take();
 5241        let action = action.clone();
 5242        cx.spawn_in(window, async move |editor, cx| {
 5243            while let Some(prev_task) = task {
 5244                prev_task.await.log_err();
 5245                task = editor.update(cx, |this, _| this.code_actions_task.take())?;
 5246            }
 5247
 5248            let spawned_test_task = editor.update_in(cx, |editor, window, cx| {
 5249                if editor.focus_handle.is_focused(window) {
 5250                    let multibuffer_point = action
 5251                        .deployed_from_indicator
 5252                        .map(|row| DisplayPoint::new(row, 0).to_point(&snapshot))
 5253                        .unwrap_or_else(|| editor.selections.newest::<Point>(cx).head());
 5254                    let (buffer, buffer_row) = snapshot
 5255                        .buffer_snapshot
 5256                        .buffer_line_for_row(MultiBufferRow(multibuffer_point.row))
 5257                        .and_then(|(buffer_snapshot, range)| {
 5258                            editor
 5259                                .buffer
 5260                                .read(cx)
 5261                                .buffer(buffer_snapshot.remote_id())
 5262                                .map(|buffer| (buffer, range.start.row))
 5263                        })?;
 5264                    let (_, code_actions) = editor
 5265                        .available_code_actions
 5266                        .clone()
 5267                        .and_then(|(location, code_actions)| {
 5268                            let snapshot = location.buffer.read(cx).snapshot();
 5269                            let point_range = location.range.to_point(&snapshot);
 5270                            let point_range = point_range.start.row..=point_range.end.row;
 5271                            if point_range.contains(&buffer_row) {
 5272                                Some((location, code_actions))
 5273                            } else {
 5274                                None
 5275                            }
 5276                        })
 5277                        .unzip();
 5278                    let buffer_id = buffer.read(cx).remote_id();
 5279                    let tasks = editor
 5280                        .tasks
 5281                        .get(&(buffer_id, buffer_row))
 5282                        .map(|t| Arc::new(t.to_owned()));
 5283                    if tasks.is_none() && code_actions.is_none() {
 5284                        return None;
 5285                    }
 5286
 5287                    editor.completion_tasks.clear();
 5288                    editor.discard_inline_completion(false, cx);
 5289                    let task_context =
 5290                        tasks
 5291                            .as_ref()
 5292                            .zip(editor.project.clone())
 5293                            .map(|(tasks, project)| {
 5294                                Self::build_tasks_context(&project, &buffer, buffer_row, tasks, cx)
 5295                            });
 5296
 5297                    Some(cx.spawn_in(window, async move |editor, cx| {
 5298                        let task_context = match task_context {
 5299                            Some(task_context) => task_context.await,
 5300                            None => None,
 5301                        };
 5302                        let resolved_tasks =
 5303                            tasks
 5304                                .zip(task_context.clone())
 5305                                .map(|(tasks, task_context)| ResolvedTasks {
 5306                                    templates: tasks.resolve(&task_context).collect(),
 5307                                    position: snapshot.buffer_snapshot.anchor_before(Point::new(
 5308                                        multibuffer_point.row,
 5309                                        tasks.column,
 5310                                    )),
 5311                                });
 5312                        let debug_scenarios = editor.update(cx, |editor, cx| {
 5313                            if cx.has_flag::<DebuggerFeatureFlag>() {
 5314                                maybe!({
 5315                                    let project = editor.project.as_ref()?;
 5316                                    let dap_store = project.read(cx).dap_store();
 5317                                    let mut scenarios = vec![];
 5318                                    let resolved_tasks = resolved_tasks.as_ref()?;
 5319                                    let buffer = buffer.read(cx);
 5320                                    let language = buffer.language()?;
 5321                                    let file = buffer.file();
 5322                                    let debug_adapter =
 5323                                        language_settings(language.name().into(), file, cx)
 5324                                            .debuggers
 5325                                            .first()
 5326                                            .map(SharedString::from)
 5327                                            .or_else(|| {
 5328                                                language
 5329                                                    .config()
 5330                                                    .debuggers
 5331                                                    .first()
 5332                                                    .map(SharedString::from)
 5333                                            })?;
 5334
 5335                                    dap_store.update(cx, |dap_store, cx| {
 5336                                        for (_, task) in &resolved_tasks.templates {
 5337                                            if let Some(scenario) = dap_store
 5338                                                .debug_scenario_for_build_task(
 5339                                                    task.original_task().clone(),
 5340                                                    debug_adapter.clone().into(),
 5341                                                    task.display_label().to_owned().into(),
 5342                                                    cx,
 5343                                                )
 5344                                            {
 5345                                                scenarios.push(scenario);
 5346                                            }
 5347                                        }
 5348                                    });
 5349                                    Some(scenarios)
 5350                                })
 5351                                .unwrap_or_default()
 5352                            } else {
 5353                                vec![]
 5354                            }
 5355                        })?;
 5356                        let spawn_straight_away = quick_launch
 5357                            && resolved_tasks
 5358                                .as_ref()
 5359                                .map_or(false, |tasks| tasks.templates.len() == 1)
 5360                            && code_actions
 5361                                .as_ref()
 5362                                .map_or(true, |actions| actions.is_empty())
 5363                            && debug_scenarios.is_empty();
 5364                        if let Ok(task) = editor.update_in(cx, |editor, window, cx| {
 5365                            *editor.context_menu.borrow_mut() =
 5366                                Some(CodeContextMenu::CodeActions(CodeActionsMenu {
 5367                                    buffer,
 5368                                    actions: CodeActionContents::new(
 5369                                        resolved_tasks,
 5370                                        code_actions,
 5371                                        debug_scenarios,
 5372                                        task_context.unwrap_or_default(),
 5373                                    ),
 5374                                    selected_item: Default::default(),
 5375                                    scroll_handle: UniformListScrollHandle::default(),
 5376                                    deployed_from_indicator,
 5377                                }));
 5378                            if spawn_straight_away {
 5379                                if let Some(task) = editor.confirm_code_action(
 5380                                    &ConfirmCodeAction { item_ix: Some(0) },
 5381                                    window,
 5382                                    cx,
 5383                                ) {
 5384                                    cx.notify();
 5385                                    return task;
 5386                                }
 5387                            }
 5388                            cx.notify();
 5389                            Task::ready(Ok(()))
 5390                        }) {
 5391                            task.await
 5392                        } else {
 5393                            Ok(())
 5394                        }
 5395                    }))
 5396                } else {
 5397                    Some(Task::ready(Ok(())))
 5398                }
 5399            })?;
 5400            if let Some(task) = spawned_test_task {
 5401                task.await?;
 5402            }
 5403
 5404            Ok::<_, anyhow::Error>(())
 5405        })
 5406        .detach_and_log_err(cx);
 5407    }
 5408
 5409    pub fn confirm_code_action(
 5410        &mut self,
 5411        action: &ConfirmCodeAction,
 5412        window: &mut Window,
 5413        cx: &mut Context<Self>,
 5414    ) -> Option<Task<Result<()>>> {
 5415        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
 5416
 5417        let actions_menu =
 5418            if let CodeContextMenu::CodeActions(menu) = self.hide_context_menu(window, cx)? {
 5419                menu
 5420            } else {
 5421                return None;
 5422            };
 5423
 5424        let action_ix = action.item_ix.unwrap_or(actions_menu.selected_item);
 5425        let action = actions_menu.actions.get(action_ix)?;
 5426        let title = action.label();
 5427        let buffer = actions_menu.buffer;
 5428        let workspace = self.workspace()?;
 5429
 5430        match action {
 5431            CodeActionsItem::Task(task_source_kind, resolved_task) => {
 5432                workspace.update(cx, |workspace, cx| {
 5433                    workspace.schedule_resolved_task(
 5434                        task_source_kind,
 5435                        resolved_task,
 5436                        false,
 5437                        window,
 5438                        cx,
 5439                    );
 5440
 5441                    Some(Task::ready(Ok(())))
 5442                })
 5443            }
 5444            CodeActionsItem::CodeAction {
 5445                excerpt_id,
 5446                action,
 5447                provider,
 5448            } => {
 5449                let apply_code_action =
 5450                    provider.apply_code_action(buffer, action, excerpt_id, true, window, cx);
 5451                let workspace = workspace.downgrade();
 5452                Some(cx.spawn_in(window, async move |editor, cx| {
 5453                    let project_transaction = apply_code_action.await?;
 5454                    Self::open_project_transaction(
 5455                        &editor,
 5456                        workspace,
 5457                        project_transaction,
 5458                        title,
 5459                        cx,
 5460                    )
 5461                    .await
 5462                }))
 5463            }
 5464            CodeActionsItem::DebugScenario(scenario) => {
 5465                let context = actions_menu.actions.context.clone();
 5466
 5467                workspace.update(cx, |workspace, cx| {
 5468                    workspace.start_debug_session(scenario, context, Some(buffer), window, cx);
 5469                });
 5470                Some(Task::ready(Ok(())))
 5471            }
 5472        }
 5473    }
 5474
 5475    pub async fn open_project_transaction(
 5476        this: &WeakEntity<Editor>,
 5477        workspace: WeakEntity<Workspace>,
 5478        transaction: ProjectTransaction,
 5479        title: String,
 5480        cx: &mut AsyncWindowContext,
 5481    ) -> Result<()> {
 5482        let mut entries = transaction.0.into_iter().collect::<Vec<_>>();
 5483        cx.update(|_, cx| {
 5484            entries.sort_unstable_by_key(|(buffer, _)| {
 5485                buffer.read(cx).file().map(|f| f.path().clone())
 5486            });
 5487        })?;
 5488
 5489        // If the project transaction's edits are all contained within this editor, then
 5490        // avoid opening a new editor to display them.
 5491
 5492        if let Some((buffer, transaction)) = entries.first() {
 5493            if entries.len() == 1 {
 5494                let excerpt = this.update(cx, |editor, cx| {
 5495                    editor
 5496                        .buffer()
 5497                        .read(cx)
 5498                        .excerpt_containing(editor.selections.newest_anchor().head(), cx)
 5499                })?;
 5500                if let Some((_, excerpted_buffer, excerpt_range)) = excerpt {
 5501                    if excerpted_buffer == *buffer {
 5502                        let all_edits_within_excerpt = buffer.read_with(cx, |buffer, _| {
 5503                            let excerpt_range = excerpt_range.to_offset(buffer);
 5504                            buffer
 5505                                .edited_ranges_for_transaction::<usize>(transaction)
 5506                                .all(|range| {
 5507                                    excerpt_range.start <= range.start
 5508                                        && excerpt_range.end >= range.end
 5509                                })
 5510                        })?;
 5511
 5512                        if all_edits_within_excerpt {
 5513                            return Ok(());
 5514                        }
 5515                    }
 5516                }
 5517            }
 5518        } else {
 5519            return Ok(());
 5520        }
 5521
 5522        let mut ranges_to_highlight = Vec::new();
 5523        let excerpt_buffer = cx.new(|cx| {
 5524            let mut multibuffer = MultiBuffer::new(Capability::ReadWrite).with_title(title);
 5525            for (buffer_handle, transaction) in &entries {
 5526                let edited_ranges = buffer_handle
 5527                    .read(cx)
 5528                    .edited_ranges_for_transaction::<Point>(transaction)
 5529                    .collect::<Vec<_>>();
 5530                let (ranges, _) = multibuffer.set_excerpts_for_path(
 5531                    PathKey::for_buffer(buffer_handle, cx),
 5532                    buffer_handle.clone(),
 5533                    edited_ranges,
 5534                    DEFAULT_MULTIBUFFER_CONTEXT,
 5535                    cx,
 5536                );
 5537
 5538                ranges_to_highlight.extend(ranges);
 5539            }
 5540            multibuffer.push_transaction(entries.iter().map(|(b, t)| (b, t)), cx);
 5541            multibuffer
 5542        })?;
 5543
 5544        workspace.update_in(cx, |workspace, window, cx| {
 5545            let project = workspace.project().clone();
 5546            let editor =
 5547                cx.new(|cx| Editor::for_multibuffer(excerpt_buffer, Some(project), window, cx));
 5548            workspace.add_item_to_active_pane(Box::new(editor.clone()), None, true, window, cx);
 5549            editor.update(cx, |editor, cx| {
 5550                editor.highlight_background::<Self>(
 5551                    &ranges_to_highlight,
 5552                    |theme| theme.editor_highlighted_line_background,
 5553                    cx,
 5554                );
 5555            });
 5556        })?;
 5557
 5558        Ok(())
 5559    }
 5560
 5561    pub fn clear_code_action_providers(&mut self) {
 5562        self.code_action_providers.clear();
 5563        self.available_code_actions.take();
 5564    }
 5565
 5566    pub fn add_code_action_provider(
 5567        &mut self,
 5568        provider: Rc<dyn CodeActionProvider>,
 5569        window: &mut Window,
 5570        cx: &mut Context<Self>,
 5571    ) {
 5572        if self
 5573            .code_action_providers
 5574            .iter()
 5575            .any(|existing_provider| existing_provider.id() == provider.id())
 5576        {
 5577            return;
 5578        }
 5579
 5580        self.code_action_providers.push(provider);
 5581        self.refresh_code_actions(window, cx);
 5582    }
 5583
 5584    pub fn remove_code_action_provider(
 5585        &mut self,
 5586        id: Arc<str>,
 5587        window: &mut Window,
 5588        cx: &mut Context<Self>,
 5589    ) {
 5590        self.code_action_providers
 5591            .retain(|provider| provider.id() != id);
 5592        self.refresh_code_actions(window, cx);
 5593    }
 5594
 5595    fn refresh_code_actions(&mut self, window: &mut Window, cx: &mut Context<Self>) -> Option<()> {
 5596        let newest_selection = self.selections.newest_anchor().clone();
 5597        let newest_selection_adjusted = self.selections.newest_adjusted(cx).clone();
 5598        let buffer = self.buffer.read(cx);
 5599        if newest_selection.head().diff_base_anchor.is_some() {
 5600            return None;
 5601        }
 5602        let (start_buffer, start) =
 5603            buffer.text_anchor_for_position(newest_selection_adjusted.start, cx)?;
 5604        let (end_buffer, end) =
 5605            buffer.text_anchor_for_position(newest_selection_adjusted.end, cx)?;
 5606        if start_buffer != end_buffer {
 5607            return None;
 5608        }
 5609
 5610        self.code_actions_task = Some(cx.spawn_in(window, async move |this, cx| {
 5611            cx.background_executor()
 5612                .timer(CODE_ACTIONS_DEBOUNCE_TIMEOUT)
 5613                .await;
 5614
 5615            let (providers, tasks) = this.update_in(cx, |this, window, cx| {
 5616                let providers = this.code_action_providers.clone();
 5617                let tasks = this
 5618                    .code_action_providers
 5619                    .iter()
 5620                    .map(|provider| provider.code_actions(&start_buffer, start..end, window, cx))
 5621                    .collect::<Vec<_>>();
 5622                (providers, tasks)
 5623            })?;
 5624
 5625            let mut actions = Vec::new();
 5626            for (provider, provider_actions) in
 5627                providers.into_iter().zip(future::join_all(tasks).await)
 5628            {
 5629                if let Some(provider_actions) = provider_actions.log_err() {
 5630                    actions.extend(provider_actions.into_iter().map(|action| {
 5631                        AvailableCodeAction {
 5632                            excerpt_id: newest_selection.start.excerpt_id,
 5633                            action,
 5634                            provider: provider.clone(),
 5635                        }
 5636                    }));
 5637                }
 5638            }
 5639
 5640            this.update(cx, |this, cx| {
 5641                this.available_code_actions = if actions.is_empty() {
 5642                    None
 5643                } else {
 5644                    Some((
 5645                        Location {
 5646                            buffer: start_buffer,
 5647                            range: start..end,
 5648                        },
 5649                        actions.into(),
 5650                    ))
 5651                };
 5652                cx.notify();
 5653            })
 5654        }));
 5655        None
 5656    }
 5657
 5658    fn start_inline_blame_timer(&mut self, window: &mut Window, cx: &mut Context<Self>) {
 5659        if let Some(delay) = ProjectSettings::get_global(cx).git.inline_blame_delay() {
 5660            self.show_git_blame_inline = false;
 5661
 5662            self.show_git_blame_inline_delay_task =
 5663                Some(cx.spawn_in(window, async move |this, cx| {
 5664                    cx.background_executor().timer(delay).await;
 5665
 5666                    this.update(cx, |this, cx| {
 5667                        this.show_git_blame_inline = true;
 5668                        cx.notify();
 5669                    })
 5670                    .log_err();
 5671                }));
 5672        }
 5673    }
 5674
 5675    fn show_blame_popover(
 5676        &mut self,
 5677        blame_entry: &BlameEntry,
 5678        position: gpui::Point<Pixels>,
 5679        cx: &mut Context<Self>,
 5680    ) {
 5681        if let Some(state) = &mut self.inline_blame_popover {
 5682            state.hide_task.take();
 5683            cx.notify();
 5684        } else {
 5685            let delay = EditorSettings::get_global(cx).hover_popover_delay;
 5686            let show_task = cx.spawn(async move |editor, cx| {
 5687                cx.background_executor()
 5688                    .timer(std::time::Duration::from_millis(delay))
 5689                    .await;
 5690                editor
 5691                    .update(cx, |editor, cx| {
 5692                        if let Some(state) = &mut editor.inline_blame_popover {
 5693                            state.show_task = None;
 5694                            cx.notify();
 5695                        }
 5696                    })
 5697                    .ok();
 5698            });
 5699            let Some(blame) = self.blame.as_ref() else {
 5700                return;
 5701            };
 5702            let blame = blame.read(cx);
 5703            let details = blame.details_for_entry(&blame_entry);
 5704            let markdown = cx.new(|cx| {
 5705                Markdown::new(
 5706                    details
 5707                        .as_ref()
 5708                        .map(|message| message.message.clone())
 5709                        .unwrap_or_default(),
 5710                    None,
 5711                    None,
 5712                    cx,
 5713                )
 5714            });
 5715            self.inline_blame_popover = Some(InlineBlamePopover {
 5716                position,
 5717                show_task: Some(show_task),
 5718                hide_task: None,
 5719                popover_bounds: None,
 5720                popover_state: InlineBlamePopoverState {
 5721                    scroll_handle: ScrollHandle::new(),
 5722                    commit_message: details,
 5723                    markdown,
 5724                },
 5725            });
 5726        }
 5727    }
 5728
 5729    fn hide_blame_popover(&mut self, cx: &mut Context<Self>) {
 5730        if let Some(state) = &mut self.inline_blame_popover {
 5731            if state.show_task.is_some() {
 5732                self.inline_blame_popover.take();
 5733                cx.notify();
 5734            } else {
 5735                let hide_task = cx.spawn(async move |editor, cx| {
 5736                    cx.background_executor()
 5737                        .timer(std::time::Duration::from_millis(100))
 5738                        .await;
 5739                    editor
 5740                        .update(cx, |editor, cx| {
 5741                            editor.inline_blame_popover.take();
 5742                            cx.notify();
 5743                        })
 5744                        .ok();
 5745                });
 5746                state.hide_task = Some(hide_task);
 5747            }
 5748        }
 5749    }
 5750
 5751    fn refresh_document_highlights(&mut self, cx: &mut Context<Self>) -> Option<()> {
 5752        if self.pending_rename.is_some() {
 5753            return None;
 5754        }
 5755
 5756        let provider = self.semantics_provider.clone()?;
 5757        let buffer = self.buffer.read(cx);
 5758        let newest_selection = self.selections.newest_anchor().clone();
 5759        let cursor_position = newest_selection.head();
 5760        let (cursor_buffer, cursor_buffer_position) =
 5761            buffer.text_anchor_for_position(cursor_position, cx)?;
 5762        let (tail_buffer, tail_buffer_position) =
 5763            buffer.text_anchor_for_position(newest_selection.tail(), cx)?;
 5764        if cursor_buffer != tail_buffer {
 5765            return None;
 5766        }
 5767
 5768        let snapshot = cursor_buffer.read(cx).snapshot();
 5769        let (start_word_range, _) = snapshot.surrounding_word(cursor_buffer_position);
 5770        let (end_word_range, _) = snapshot.surrounding_word(tail_buffer_position);
 5771        if start_word_range != end_word_range {
 5772            self.document_highlights_task.take();
 5773            self.clear_background_highlights::<DocumentHighlightRead>(cx);
 5774            self.clear_background_highlights::<DocumentHighlightWrite>(cx);
 5775            return None;
 5776        }
 5777
 5778        let debounce = EditorSettings::get_global(cx).lsp_highlight_debounce;
 5779        self.document_highlights_task = Some(cx.spawn(async move |this, cx| {
 5780            cx.background_executor()
 5781                .timer(Duration::from_millis(debounce))
 5782                .await;
 5783
 5784            let highlights = if let Some(highlights) = cx
 5785                .update(|cx| {
 5786                    provider.document_highlights(&cursor_buffer, cursor_buffer_position, cx)
 5787                })
 5788                .ok()
 5789                .flatten()
 5790            {
 5791                highlights.await.log_err()
 5792            } else {
 5793                None
 5794            };
 5795
 5796            if let Some(highlights) = highlights {
 5797                this.update(cx, |this, cx| {
 5798                    if this.pending_rename.is_some() {
 5799                        return;
 5800                    }
 5801
 5802                    let buffer_id = cursor_position.buffer_id;
 5803                    let buffer = this.buffer.read(cx);
 5804                    if !buffer
 5805                        .text_anchor_for_position(cursor_position, cx)
 5806                        .map_or(false, |(buffer, _)| buffer == cursor_buffer)
 5807                    {
 5808                        return;
 5809                    }
 5810
 5811                    let cursor_buffer_snapshot = cursor_buffer.read(cx);
 5812                    let mut write_ranges = Vec::new();
 5813                    let mut read_ranges = Vec::new();
 5814                    for highlight in highlights {
 5815                        for (excerpt_id, excerpt_range) in
 5816                            buffer.excerpts_for_buffer(cursor_buffer.read(cx).remote_id(), cx)
 5817                        {
 5818                            let start = highlight
 5819                                .range
 5820                                .start
 5821                                .max(&excerpt_range.context.start, cursor_buffer_snapshot);
 5822                            let end = highlight
 5823                                .range
 5824                                .end
 5825                                .min(&excerpt_range.context.end, cursor_buffer_snapshot);
 5826                            if start.cmp(&end, cursor_buffer_snapshot).is_ge() {
 5827                                continue;
 5828                            }
 5829
 5830                            let range = Anchor {
 5831                                buffer_id,
 5832                                excerpt_id,
 5833                                text_anchor: start,
 5834                                diff_base_anchor: None,
 5835                            }..Anchor {
 5836                                buffer_id,
 5837                                excerpt_id,
 5838                                text_anchor: end,
 5839                                diff_base_anchor: None,
 5840                            };
 5841                            if highlight.kind == lsp::DocumentHighlightKind::WRITE {
 5842                                write_ranges.push(range);
 5843                            } else {
 5844                                read_ranges.push(range);
 5845                            }
 5846                        }
 5847                    }
 5848
 5849                    this.highlight_background::<DocumentHighlightRead>(
 5850                        &read_ranges,
 5851                        |theme| theme.editor_document_highlight_read_background,
 5852                        cx,
 5853                    );
 5854                    this.highlight_background::<DocumentHighlightWrite>(
 5855                        &write_ranges,
 5856                        |theme| theme.editor_document_highlight_write_background,
 5857                        cx,
 5858                    );
 5859                    cx.notify();
 5860                })
 5861                .log_err();
 5862            }
 5863        }));
 5864        None
 5865    }
 5866
 5867    fn prepare_highlight_query_from_selection(
 5868        &mut self,
 5869        cx: &mut Context<Editor>,
 5870    ) -> Option<(String, Range<Anchor>)> {
 5871        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 5872            return None;
 5873        }
 5874        if !EditorSettings::get_global(cx).selection_highlight {
 5875            return None;
 5876        }
 5877        if self.selections.count() != 1 || self.selections.line_mode {
 5878            return None;
 5879        }
 5880        let selection = self.selections.newest::<Point>(cx);
 5881        if selection.is_empty() || selection.start.row != selection.end.row {
 5882            return None;
 5883        }
 5884        let multi_buffer_snapshot = self.buffer().read(cx).snapshot(cx);
 5885        let selection_anchor_range = selection.range().to_anchors(&multi_buffer_snapshot);
 5886        let query = multi_buffer_snapshot
 5887            .text_for_range(selection_anchor_range.clone())
 5888            .collect::<String>();
 5889        if query.trim().is_empty() {
 5890            return None;
 5891        }
 5892        Some((query, selection_anchor_range))
 5893    }
 5894
 5895    fn update_selection_occurrence_highlights(
 5896        &mut self,
 5897        query_text: String,
 5898        query_range: Range<Anchor>,
 5899        multi_buffer_range_to_query: Range<Point>,
 5900        use_debounce: bool,
 5901        window: &mut Window,
 5902        cx: &mut Context<Editor>,
 5903    ) -> Task<()> {
 5904        let multi_buffer_snapshot = self.buffer().read(cx).snapshot(cx);
 5905        cx.spawn_in(window, async move |editor, cx| {
 5906            if use_debounce {
 5907                cx.background_executor()
 5908                    .timer(SELECTION_HIGHLIGHT_DEBOUNCE_TIMEOUT)
 5909                    .await;
 5910            }
 5911            let match_task = cx.background_spawn(async move {
 5912                let buffer_ranges = multi_buffer_snapshot
 5913                    .range_to_buffer_ranges(multi_buffer_range_to_query)
 5914                    .into_iter()
 5915                    .filter(|(_, excerpt_visible_range, _)| !excerpt_visible_range.is_empty());
 5916                let mut match_ranges = Vec::new();
 5917                let Ok(regex) = project::search::SearchQuery::text(
 5918                    query_text.clone(),
 5919                    false,
 5920                    false,
 5921                    false,
 5922                    Default::default(),
 5923                    Default::default(),
 5924                    false,
 5925                    None,
 5926                ) else {
 5927                    return Vec::default();
 5928                };
 5929                for (buffer_snapshot, search_range, excerpt_id) in buffer_ranges {
 5930                    match_ranges.extend(
 5931                        regex
 5932                            .search(&buffer_snapshot, Some(search_range.clone()))
 5933                            .await
 5934                            .into_iter()
 5935                            .filter_map(|match_range| {
 5936                                let match_start = buffer_snapshot
 5937                                    .anchor_after(search_range.start + match_range.start);
 5938                                let match_end = buffer_snapshot
 5939                                    .anchor_before(search_range.start + match_range.end);
 5940                                let match_anchor_range = Anchor::range_in_buffer(
 5941                                    excerpt_id,
 5942                                    buffer_snapshot.remote_id(),
 5943                                    match_start..match_end,
 5944                                );
 5945                                (match_anchor_range != query_range).then_some(match_anchor_range)
 5946                            }),
 5947                    );
 5948                }
 5949                match_ranges
 5950            });
 5951            let match_ranges = match_task.await;
 5952            editor
 5953                .update_in(cx, |editor, _, cx| {
 5954                    editor.clear_background_highlights::<SelectedTextHighlight>(cx);
 5955                    if !match_ranges.is_empty() {
 5956                        editor.highlight_background::<SelectedTextHighlight>(
 5957                            &match_ranges,
 5958                            |theme| theme.editor_document_highlight_bracket_background,
 5959                            cx,
 5960                        )
 5961                    }
 5962                })
 5963                .log_err();
 5964        })
 5965    }
 5966
 5967    fn refresh_selected_text_highlights(
 5968        &mut self,
 5969        on_buffer_edit: bool,
 5970        window: &mut Window,
 5971        cx: &mut Context<Editor>,
 5972    ) {
 5973        let Some((query_text, query_range)) = self.prepare_highlight_query_from_selection(cx)
 5974        else {
 5975            self.clear_background_highlights::<SelectedTextHighlight>(cx);
 5976            self.quick_selection_highlight_task.take();
 5977            self.debounced_selection_highlight_task.take();
 5978            return;
 5979        };
 5980        let multi_buffer_snapshot = self.buffer().read(cx).snapshot(cx);
 5981        if on_buffer_edit
 5982            || self
 5983                .quick_selection_highlight_task
 5984                .as_ref()
 5985                .map_or(true, |(prev_anchor_range, _)| {
 5986                    prev_anchor_range != &query_range
 5987                })
 5988        {
 5989            let multi_buffer_visible_start = self
 5990                .scroll_manager
 5991                .anchor()
 5992                .anchor
 5993                .to_point(&multi_buffer_snapshot);
 5994            let multi_buffer_visible_end = multi_buffer_snapshot.clip_point(
 5995                multi_buffer_visible_start
 5996                    + Point::new(self.visible_line_count().unwrap_or(0.).ceil() as u32, 0),
 5997                Bias::Left,
 5998            );
 5999            let multi_buffer_visible_range = multi_buffer_visible_start..multi_buffer_visible_end;
 6000            self.quick_selection_highlight_task = Some((
 6001                query_range.clone(),
 6002                self.update_selection_occurrence_highlights(
 6003                    query_text.clone(),
 6004                    query_range.clone(),
 6005                    multi_buffer_visible_range,
 6006                    false,
 6007                    window,
 6008                    cx,
 6009                ),
 6010            ));
 6011        }
 6012        if on_buffer_edit
 6013            || self
 6014                .debounced_selection_highlight_task
 6015                .as_ref()
 6016                .map_or(true, |(prev_anchor_range, _)| {
 6017                    prev_anchor_range != &query_range
 6018                })
 6019        {
 6020            let multi_buffer_start = multi_buffer_snapshot
 6021                .anchor_before(0)
 6022                .to_point(&multi_buffer_snapshot);
 6023            let multi_buffer_end = multi_buffer_snapshot
 6024                .anchor_after(multi_buffer_snapshot.len())
 6025                .to_point(&multi_buffer_snapshot);
 6026            let multi_buffer_full_range = multi_buffer_start..multi_buffer_end;
 6027            self.debounced_selection_highlight_task = Some((
 6028                query_range.clone(),
 6029                self.update_selection_occurrence_highlights(
 6030                    query_text,
 6031                    query_range,
 6032                    multi_buffer_full_range,
 6033                    true,
 6034                    window,
 6035                    cx,
 6036                ),
 6037            ));
 6038        }
 6039    }
 6040
 6041    pub fn refresh_inline_completion(
 6042        &mut self,
 6043        debounce: bool,
 6044        user_requested: bool,
 6045        window: &mut Window,
 6046        cx: &mut Context<Self>,
 6047    ) -> Option<()> {
 6048        let provider = self.edit_prediction_provider()?;
 6049        let cursor = self.selections.newest_anchor().head();
 6050        let (buffer, cursor_buffer_position) =
 6051            self.buffer.read(cx).text_anchor_for_position(cursor, cx)?;
 6052
 6053        if !self.edit_predictions_enabled_in_buffer(&buffer, cursor_buffer_position, cx) {
 6054            self.discard_inline_completion(false, cx);
 6055            return None;
 6056        }
 6057
 6058        if !user_requested
 6059            && (!self.should_show_edit_predictions()
 6060                || !self.is_focused(window)
 6061                || buffer.read(cx).is_empty())
 6062        {
 6063            self.discard_inline_completion(false, cx);
 6064            return None;
 6065        }
 6066
 6067        self.update_visible_inline_completion(window, cx);
 6068        provider.refresh(
 6069            self.project.clone(),
 6070            buffer,
 6071            cursor_buffer_position,
 6072            debounce,
 6073            cx,
 6074        );
 6075        Some(())
 6076    }
 6077
 6078    fn show_edit_predictions_in_menu(&self) -> bool {
 6079        match self.edit_prediction_settings {
 6080            EditPredictionSettings::Disabled => false,
 6081            EditPredictionSettings::Enabled { show_in_menu, .. } => show_in_menu,
 6082        }
 6083    }
 6084
 6085    pub fn edit_predictions_enabled(&self) -> bool {
 6086        match self.edit_prediction_settings {
 6087            EditPredictionSettings::Disabled => false,
 6088            EditPredictionSettings::Enabled { .. } => true,
 6089        }
 6090    }
 6091
 6092    fn edit_prediction_requires_modifier(&self) -> bool {
 6093        match self.edit_prediction_settings {
 6094            EditPredictionSettings::Disabled => false,
 6095            EditPredictionSettings::Enabled {
 6096                preview_requires_modifier,
 6097                ..
 6098            } => preview_requires_modifier,
 6099        }
 6100    }
 6101
 6102    pub fn update_edit_prediction_settings(&mut self, cx: &mut Context<Self>) {
 6103        if self.edit_prediction_provider.is_none() {
 6104            self.edit_prediction_settings = EditPredictionSettings::Disabled;
 6105        } else {
 6106            let selection = self.selections.newest_anchor();
 6107            let cursor = selection.head();
 6108
 6109            if let Some((buffer, cursor_buffer_position)) =
 6110                self.buffer.read(cx).text_anchor_for_position(cursor, cx)
 6111            {
 6112                self.edit_prediction_settings =
 6113                    self.edit_prediction_settings_at_position(&buffer, cursor_buffer_position, cx);
 6114            }
 6115        }
 6116    }
 6117
 6118    fn edit_prediction_settings_at_position(
 6119        &self,
 6120        buffer: &Entity<Buffer>,
 6121        buffer_position: language::Anchor,
 6122        cx: &App,
 6123    ) -> EditPredictionSettings {
 6124        if !self.mode.is_full()
 6125            || !self.show_inline_completions_override.unwrap_or(true)
 6126            || self.inline_completions_disabled_in_scope(buffer, buffer_position, cx)
 6127        {
 6128            return EditPredictionSettings::Disabled;
 6129        }
 6130
 6131        let buffer = buffer.read(cx);
 6132
 6133        let file = buffer.file();
 6134
 6135        if !language_settings(buffer.language().map(|l| l.name()), file, cx).show_edit_predictions {
 6136            return EditPredictionSettings::Disabled;
 6137        };
 6138
 6139        let by_provider = matches!(
 6140            self.menu_inline_completions_policy,
 6141            MenuInlineCompletionsPolicy::ByProvider
 6142        );
 6143
 6144        let show_in_menu = by_provider
 6145            && self
 6146                .edit_prediction_provider
 6147                .as_ref()
 6148                .map_or(false, |provider| {
 6149                    provider.provider.show_completions_in_menu()
 6150                });
 6151
 6152        let preview_requires_modifier =
 6153            all_language_settings(file, cx).edit_predictions_mode() == EditPredictionsMode::Subtle;
 6154
 6155        EditPredictionSettings::Enabled {
 6156            show_in_menu,
 6157            preview_requires_modifier,
 6158        }
 6159    }
 6160
 6161    fn should_show_edit_predictions(&self) -> bool {
 6162        self.snippet_stack.is_empty() && self.edit_predictions_enabled()
 6163    }
 6164
 6165    pub fn edit_prediction_preview_is_active(&self) -> bool {
 6166        matches!(
 6167            self.edit_prediction_preview,
 6168            EditPredictionPreview::Active { .. }
 6169        )
 6170    }
 6171
 6172    pub fn edit_predictions_enabled_at_cursor(&self, cx: &App) -> bool {
 6173        let cursor = self.selections.newest_anchor().head();
 6174        if let Some((buffer, cursor_position)) =
 6175            self.buffer.read(cx).text_anchor_for_position(cursor, cx)
 6176        {
 6177            self.edit_predictions_enabled_in_buffer(&buffer, cursor_position, cx)
 6178        } else {
 6179            false
 6180        }
 6181    }
 6182
 6183    pub fn supports_minimap(&self, cx: &App) -> bool {
 6184        !self.minimap_visibility.disabled() && self.is_singleton(cx)
 6185    }
 6186
 6187    fn edit_predictions_enabled_in_buffer(
 6188        &self,
 6189        buffer: &Entity<Buffer>,
 6190        buffer_position: language::Anchor,
 6191        cx: &App,
 6192    ) -> bool {
 6193        maybe!({
 6194            if self.read_only(cx) {
 6195                return Some(false);
 6196            }
 6197            let provider = self.edit_prediction_provider()?;
 6198            if !provider.is_enabled(&buffer, buffer_position, cx) {
 6199                return Some(false);
 6200            }
 6201            let buffer = buffer.read(cx);
 6202            let Some(file) = buffer.file() else {
 6203                return Some(true);
 6204            };
 6205            let settings = all_language_settings(Some(file), cx);
 6206            Some(settings.edit_predictions_enabled_for_file(file, cx))
 6207        })
 6208        .unwrap_or(false)
 6209    }
 6210
 6211    fn cycle_inline_completion(
 6212        &mut self,
 6213        direction: Direction,
 6214        window: &mut Window,
 6215        cx: &mut Context<Self>,
 6216    ) -> Option<()> {
 6217        let provider = self.edit_prediction_provider()?;
 6218        let cursor = self.selections.newest_anchor().head();
 6219        let (buffer, cursor_buffer_position) =
 6220            self.buffer.read(cx).text_anchor_for_position(cursor, cx)?;
 6221        if self.inline_completions_hidden_for_vim_mode || !self.should_show_edit_predictions() {
 6222            return None;
 6223        }
 6224
 6225        provider.cycle(buffer, cursor_buffer_position, direction, cx);
 6226        self.update_visible_inline_completion(window, cx);
 6227
 6228        Some(())
 6229    }
 6230
 6231    pub fn show_inline_completion(
 6232        &mut self,
 6233        _: &ShowEditPrediction,
 6234        window: &mut Window,
 6235        cx: &mut Context<Self>,
 6236    ) {
 6237        if !self.has_active_inline_completion() {
 6238            self.refresh_inline_completion(false, true, window, cx);
 6239            return;
 6240        }
 6241
 6242        self.update_visible_inline_completion(window, cx);
 6243    }
 6244
 6245    pub fn display_cursor_names(
 6246        &mut self,
 6247        _: &DisplayCursorNames,
 6248        window: &mut Window,
 6249        cx: &mut Context<Self>,
 6250    ) {
 6251        self.show_cursor_names(window, cx);
 6252    }
 6253
 6254    fn show_cursor_names(&mut self, window: &mut Window, cx: &mut Context<Self>) {
 6255        self.show_cursor_names = true;
 6256        cx.notify();
 6257        cx.spawn_in(window, async move |this, cx| {
 6258            cx.background_executor().timer(CURSORS_VISIBLE_FOR).await;
 6259            this.update(cx, |this, cx| {
 6260                this.show_cursor_names = false;
 6261                cx.notify()
 6262            })
 6263            .ok()
 6264        })
 6265        .detach();
 6266    }
 6267
 6268    pub fn next_edit_prediction(
 6269        &mut self,
 6270        _: &NextEditPrediction,
 6271        window: &mut Window,
 6272        cx: &mut Context<Self>,
 6273    ) {
 6274        if self.has_active_inline_completion() {
 6275            self.cycle_inline_completion(Direction::Next, window, cx);
 6276        } else {
 6277            let is_copilot_disabled = self
 6278                .refresh_inline_completion(false, true, window, cx)
 6279                .is_none();
 6280            if is_copilot_disabled {
 6281                cx.propagate();
 6282            }
 6283        }
 6284    }
 6285
 6286    pub fn previous_edit_prediction(
 6287        &mut self,
 6288        _: &PreviousEditPrediction,
 6289        window: &mut Window,
 6290        cx: &mut Context<Self>,
 6291    ) {
 6292        if self.has_active_inline_completion() {
 6293            self.cycle_inline_completion(Direction::Prev, window, cx);
 6294        } else {
 6295            let is_copilot_disabled = self
 6296                .refresh_inline_completion(false, true, window, cx)
 6297                .is_none();
 6298            if is_copilot_disabled {
 6299                cx.propagate();
 6300            }
 6301        }
 6302    }
 6303
 6304    pub fn accept_edit_prediction(
 6305        &mut self,
 6306        _: &AcceptEditPrediction,
 6307        window: &mut Window,
 6308        cx: &mut Context<Self>,
 6309    ) {
 6310        if self.show_edit_predictions_in_menu() {
 6311            self.hide_context_menu(window, cx);
 6312        }
 6313
 6314        let Some(active_inline_completion) = self.active_inline_completion.as_ref() else {
 6315            return;
 6316        };
 6317
 6318        self.report_inline_completion_event(
 6319            active_inline_completion.completion_id.clone(),
 6320            true,
 6321            cx,
 6322        );
 6323
 6324        match &active_inline_completion.completion {
 6325            InlineCompletion::Move { target, .. } => {
 6326                let target = *target;
 6327
 6328                if let Some(position_map) = &self.last_position_map {
 6329                    if position_map
 6330                        .visible_row_range
 6331                        .contains(&target.to_display_point(&position_map.snapshot).row())
 6332                        || !self.edit_prediction_requires_modifier()
 6333                    {
 6334                        self.unfold_ranges(&[target..target], true, false, cx);
 6335                        // Note that this is also done in vim's handler of the Tab action.
 6336                        self.change_selections(
 6337                            Some(Autoscroll::newest()),
 6338                            window,
 6339                            cx,
 6340                            |selections| {
 6341                                selections.select_anchor_ranges([target..target]);
 6342                            },
 6343                        );
 6344                        self.clear_row_highlights::<EditPredictionPreview>();
 6345
 6346                        self.edit_prediction_preview
 6347                            .set_previous_scroll_position(None);
 6348                    } else {
 6349                        self.edit_prediction_preview
 6350                            .set_previous_scroll_position(Some(
 6351                                position_map.snapshot.scroll_anchor,
 6352                            ));
 6353
 6354                        self.highlight_rows::<EditPredictionPreview>(
 6355                            target..target,
 6356                            cx.theme().colors().editor_highlighted_line_background,
 6357                            RowHighlightOptions {
 6358                                autoscroll: true,
 6359                                ..Default::default()
 6360                            },
 6361                            cx,
 6362                        );
 6363                        self.request_autoscroll(Autoscroll::fit(), cx);
 6364                    }
 6365                }
 6366            }
 6367            InlineCompletion::Edit { edits, .. } => {
 6368                if let Some(provider) = self.edit_prediction_provider() {
 6369                    provider.accept(cx);
 6370                }
 6371
 6372                let snapshot = self.buffer.read(cx).snapshot(cx);
 6373                let last_edit_end = edits.last().unwrap().0.end.bias_right(&snapshot);
 6374
 6375                self.buffer.update(cx, |buffer, cx| {
 6376                    buffer.edit(edits.iter().cloned(), None, cx)
 6377                });
 6378
 6379                self.change_selections(None, window, cx, |s| {
 6380                    s.select_anchor_ranges([last_edit_end..last_edit_end])
 6381                });
 6382
 6383                self.update_visible_inline_completion(window, cx);
 6384                if self.active_inline_completion.is_none() {
 6385                    self.refresh_inline_completion(true, true, window, cx);
 6386                }
 6387
 6388                cx.notify();
 6389            }
 6390        }
 6391
 6392        self.edit_prediction_requires_modifier_in_indent_conflict = false;
 6393    }
 6394
 6395    pub fn accept_partial_inline_completion(
 6396        &mut self,
 6397        _: &AcceptPartialEditPrediction,
 6398        window: &mut Window,
 6399        cx: &mut Context<Self>,
 6400    ) {
 6401        let Some(active_inline_completion) = self.active_inline_completion.as_ref() else {
 6402            return;
 6403        };
 6404        if self.selections.count() != 1 {
 6405            return;
 6406        }
 6407
 6408        self.report_inline_completion_event(
 6409            active_inline_completion.completion_id.clone(),
 6410            true,
 6411            cx,
 6412        );
 6413
 6414        match &active_inline_completion.completion {
 6415            InlineCompletion::Move { target, .. } => {
 6416                let target = *target;
 6417                self.change_selections(Some(Autoscroll::newest()), window, cx, |selections| {
 6418                    selections.select_anchor_ranges([target..target]);
 6419                });
 6420            }
 6421            InlineCompletion::Edit { edits, .. } => {
 6422                // Find an insertion that starts at the cursor position.
 6423                let snapshot = self.buffer.read(cx).snapshot(cx);
 6424                let cursor_offset = self.selections.newest::<usize>(cx).head();
 6425                let insertion = edits.iter().find_map(|(range, text)| {
 6426                    let range = range.to_offset(&snapshot);
 6427                    if range.is_empty() && range.start == cursor_offset {
 6428                        Some(text)
 6429                    } else {
 6430                        None
 6431                    }
 6432                });
 6433
 6434                if let Some(text) = insertion {
 6435                    let mut partial_completion = text
 6436                        .chars()
 6437                        .by_ref()
 6438                        .take_while(|c| c.is_alphabetic())
 6439                        .collect::<String>();
 6440                    if partial_completion.is_empty() {
 6441                        partial_completion = text
 6442                            .chars()
 6443                            .by_ref()
 6444                            .take_while(|c| c.is_whitespace() || !c.is_alphabetic())
 6445                            .collect::<String>();
 6446                    }
 6447
 6448                    cx.emit(EditorEvent::InputHandled {
 6449                        utf16_range_to_replace: None,
 6450                        text: partial_completion.clone().into(),
 6451                    });
 6452
 6453                    self.insert_with_autoindent_mode(&partial_completion, None, window, cx);
 6454
 6455                    self.refresh_inline_completion(true, true, window, cx);
 6456                    cx.notify();
 6457                } else {
 6458                    self.accept_edit_prediction(&Default::default(), window, cx);
 6459                }
 6460            }
 6461        }
 6462    }
 6463
 6464    fn discard_inline_completion(
 6465        &mut self,
 6466        should_report_inline_completion_event: bool,
 6467        cx: &mut Context<Self>,
 6468    ) -> bool {
 6469        if should_report_inline_completion_event {
 6470            let completion_id = self
 6471                .active_inline_completion
 6472                .as_ref()
 6473                .and_then(|active_completion| active_completion.completion_id.clone());
 6474
 6475            self.report_inline_completion_event(completion_id, false, cx);
 6476        }
 6477
 6478        if let Some(provider) = self.edit_prediction_provider() {
 6479            provider.discard(cx);
 6480        }
 6481
 6482        self.take_active_inline_completion(cx)
 6483    }
 6484
 6485    fn report_inline_completion_event(&self, id: Option<SharedString>, accepted: bool, cx: &App) {
 6486        let Some(provider) = self.edit_prediction_provider() else {
 6487            return;
 6488        };
 6489
 6490        let Some((_, buffer, _)) = self
 6491            .buffer
 6492            .read(cx)
 6493            .excerpt_containing(self.selections.newest_anchor().head(), cx)
 6494        else {
 6495            return;
 6496        };
 6497
 6498        let extension = buffer
 6499            .read(cx)
 6500            .file()
 6501            .and_then(|file| Some(file.path().extension()?.to_string_lossy().to_string()));
 6502
 6503        let event_type = match accepted {
 6504            true => "Edit Prediction Accepted",
 6505            false => "Edit Prediction Discarded",
 6506        };
 6507        telemetry::event!(
 6508            event_type,
 6509            provider = provider.name(),
 6510            prediction_id = id,
 6511            suggestion_accepted = accepted,
 6512            file_extension = extension,
 6513        );
 6514    }
 6515
 6516    pub fn has_active_inline_completion(&self) -> bool {
 6517        self.active_inline_completion.is_some()
 6518    }
 6519
 6520    fn take_active_inline_completion(&mut self, cx: &mut Context<Self>) -> bool {
 6521        let Some(active_inline_completion) = self.active_inline_completion.take() else {
 6522            return false;
 6523        };
 6524
 6525        self.splice_inlays(&active_inline_completion.inlay_ids, Default::default(), cx);
 6526        self.clear_highlights::<InlineCompletionHighlight>(cx);
 6527        self.stale_inline_completion_in_menu = Some(active_inline_completion);
 6528        true
 6529    }
 6530
 6531    /// Returns true when we're displaying the edit prediction popover below the cursor
 6532    /// like we are not previewing and the LSP autocomplete menu is visible
 6533    /// or we are in `when_holding_modifier` mode.
 6534    pub fn edit_prediction_visible_in_cursor_popover(&self, has_completion: bool) -> bool {
 6535        if self.edit_prediction_preview_is_active()
 6536            || !self.show_edit_predictions_in_menu()
 6537            || !self.edit_predictions_enabled()
 6538        {
 6539            return false;
 6540        }
 6541
 6542        if self.has_visible_completions_menu() {
 6543            return true;
 6544        }
 6545
 6546        has_completion && self.edit_prediction_requires_modifier()
 6547    }
 6548
 6549    fn handle_modifiers_changed(
 6550        &mut self,
 6551        modifiers: Modifiers,
 6552        position_map: &PositionMap,
 6553        window: &mut Window,
 6554        cx: &mut Context<Self>,
 6555    ) {
 6556        if self.show_edit_predictions_in_menu() {
 6557            self.update_edit_prediction_preview(&modifiers, window, cx);
 6558        }
 6559
 6560        self.update_selection_mode(&modifiers, position_map, window, cx);
 6561
 6562        let mouse_position = window.mouse_position();
 6563        if !position_map.text_hitbox.is_hovered(window) {
 6564            return;
 6565        }
 6566
 6567        self.update_hovered_link(
 6568            position_map.point_for_position(mouse_position),
 6569            &position_map.snapshot,
 6570            modifiers,
 6571            window,
 6572            cx,
 6573        )
 6574    }
 6575
 6576    fn update_selection_mode(
 6577        &mut self,
 6578        modifiers: &Modifiers,
 6579        position_map: &PositionMap,
 6580        window: &mut Window,
 6581        cx: &mut Context<Self>,
 6582    ) {
 6583        if modifiers != &COLUMNAR_SELECTION_MODIFIERS || self.selections.pending.is_none() {
 6584            return;
 6585        }
 6586
 6587        let mouse_position = window.mouse_position();
 6588        let point_for_position = position_map.point_for_position(mouse_position);
 6589        let position = point_for_position.previous_valid;
 6590
 6591        self.select(
 6592            SelectPhase::BeginColumnar {
 6593                position,
 6594                reset: false,
 6595                goal_column: point_for_position.exact_unclipped.column(),
 6596            },
 6597            window,
 6598            cx,
 6599        );
 6600    }
 6601
 6602    fn update_edit_prediction_preview(
 6603        &mut self,
 6604        modifiers: &Modifiers,
 6605        window: &mut Window,
 6606        cx: &mut Context<Self>,
 6607    ) {
 6608        let accept_keybind = self.accept_edit_prediction_keybind(window, cx);
 6609        let Some(accept_keystroke) = accept_keybind.keystroke() else {
 6610            return;
 6611        };
 6612
 6613        if &accept_keystroke.modifiers == modifiers && accept_keystroke.modifiers.modified() {
 6614            if matches!(
 6615                self.edit_prediction_preview,
 6616                EditPredictionPreview::Inactive { .. }
 6617            ) {
 6618                self.edit_prediction_preview = EditPredictionPreview::Active {
 6619                    previous_scroll_position: None,
 6620                    since: Instant::now(),
 6621                };
 6622
 6623                self.update_visible_inline_completion(window, cx);
 6624                cx.notify();
 6625            }
 6626        } else if let EditPredictionPreview::Active {
 6627            previous_scroll_position,
 6628            since,
 6629        } = self.edit_prediction_preview
 6630        {
 6631            if let (Some(previous_scroll_position), Some(position_map)) =
 6632                (previous_scroll_position, self.last_position_map.as_ref())
 6633            {
 6634                self.set_scroll_position(
 6635                    previous_scroll_position
 6636                        .scroll_position(&position_map.snapshot.display_snapshot),
 6637                    window,
 6638                    cx,
 6639                );
 6640            }
 6641
 6642            self.edit_prediction_preview = EditPredictionPreview::Inactive {
 6643                released_too_fast: since.elapsed() < Duration::from_millis(200),
 6644            };
 6645            self.clear_row_highlights::<EditPredictionPreview>();
 6646            self.update_visible_inline_completion(window, cx);
 6647            cx.notify();
 6648        }
 6649    }
 6650
 6651    fn update_visible_inline_completion(
 6652        &mut self,
 6653        _window: &mut Window,
 6654        cx: &mut Context<Self>,
 6655    ) -> Option<()> {
 6656        let selection = self.selections.newest_anchor();
 6657        let cursor = selection.head();
 6658        let multibuffer = self.buffer.read(cx).snapshot(cx);
 6659        let offset_selection = selection.map(|endpoint| endpoint.to_offset(&multibuffer));
 6660        let excerpt_id = cursor.excerpt_id;
 6661
 6662        let show_in_menu = self.show_edit_predictions_in_menu();
 6663        let completions_menu_has_precedence = !show_in_menu
 6664            && (self.context_menu.borrow().is_some()
 6665                || (!self.completion_tasks.is_empty() && !self.has_active_inline_completion()));
 6666
 6667        if completions_menu_has_precedence
 6668            || !offset_selection.is_empty()
 6669            || self
 6670                .active_inline_completion
 6671                .as_ref()
 6672                .map_or(false, |completion| {
 6673                    let invalidation_range = completion.invalidation_range.to_offset(&multibuffer);
 6674                    let invalidation_range = invalidation_range.start..=invalidation_range.end;
 6675                    !invalidation_range.contains(&offset_selection.head())
 6676                })
 6677        {
 6678            self.discard_inline_completion(false, cx);
 6679            return None;
 6680        }
 6681
 6682        self.take_active_inline_completion(cx);
 6683        let Some(provider) = self.edit_prediction_provider() else {
 6684            self.edit_prediction_settings = EditPredictionSettings::Disabled;
 6685            return None;
 6686        };
 6687
 6688        let (buffer, cursor_buffer_position) =
 6689            self.buffer.read(cx).text_anchor_for_position(cursor, cx)?;
 6690
 6691        self.edit_prediction_settings =
 6692            self.edit_prediction_settings_at_position(&buffer, cursor_buffer_position, cx);
 6693
 6694        self.edit_prediction_indent_conflict = multibuffer.is_line_whitespace_upto(cursor);
 6695
 6696        if self.edit_prediction_indent_conflict {
 6697            let cursor_point = cursor.to_point(&multibuffer);
 6698
 6699            let indents = multibuffer.suggested_indents(cursor_point.row..cursor_point.row + 1, cx);
 6700
 6701            if let Some((_, indent)) = indents.iter().next() {
 6702                if indent.len == cursor_point.column {
 6703                    self.edit_prediction_indent_conflict = false;
 6704                }
 6705            }
 6706        }
 6707
 6708        let inline_completion = provider.suggest(&buffer, cursor_buffer_position, cx)?;
 6709        let edits = inline_completion
 6710            .edits
 6711            .into_iter()
 6712            .flat_map(|(range, new_text)| {
 6713                let start = multibuffer.anchor_in_excerpt(excerpt_id, range.start)?;
 6714                let end = multibuffer.anchor_in_excerpt(excerpt_id, range.end)?;
 6715                Some((start..end, new_text))
 6716            })
 6717            .collect::<Vec<_>>();
 6718        if edits.is_empty() {
 6719            return None;
 6720        }
 6721
 6722        let first_edit_start = edits.first().unwrap().0.start;
 6723        let first_edit_start_point = first_edit_start.to_point(&multibuffer);
 6724        let edit_start_row = first_edit_start_point.row.saturating_sub(2);
 6725
 6726        let last_edit_end = edits.last().unwrap().0.end;
 6727        let last_edit_end_point = last_edit_end.to_point(&multibuffer);
 6728        let edit_end_row = cmp::min(multibuffer.max_point().row, last_edit_end_point.row + 2);
 6729
 6730        let cursor_row = cursor.to_point(&multibuffer).row;
 6731
 6732        let snapshot = multibuffer.buffer_for_excerpt(excerpt_id).cloned()?;
 6733
 6734        let mut inlay_ids = Vec::new();
 6735        let invalidation_row_range;
 6736        let move_invalidation_row_range = if cursor_row < edit_start_row {
 6737            Some(cursor_row..edit_end_row)
 6738        } else if cursor_row > edit_end_row {
 6739            Some(edit_start_row..cursor_row)
 6740        } else {
 6741            None
 6742        };
 6743        let is_move =
 6744            move_invalidation_row_range.is_some() || self.inline_completions_hidden_for_vim_mode;
 6745        let completion = if is_move {
 6746            invalidation_row_range =
 6747                move_invalidation_row_range.unwrap_or(edit_start_row..edit_end_row);
 6748            let target = first_edit_start;
 6749            InlineCompletion::Move { target, snapshot }
 6750        } else {
 6751            let show_completions_in_buffer = !self.edit_prediction_visible_in_cursor_popover(true)
 6752                && !self.inline_completions_hidden_for_vim_mode;
 6753
 6754            if show_completions_in_buffer {
 6755                if edits
 6756                    .iter()
 6757                    .all(|(range, _)| range.to_offset(&multibuffer).is_empty())
 6758                {
 6759                    let mut inlays = Vec::new();
 6760                    for (range, new_text) in &edits {
 6761                        let inlay = Inlay::inline_completion(
 6762                            post_inc(&mut self.next_inlay_id),
 6763                            range.start,
 6764                            new_text.as_str(),
 6765                        );
 6766                        inlay_ids.push(inlay.id);
 6767                        inlays.push(inlay);
 6768                    }
 6769
 6770                    self.splice_inlays(&[], inlays, cx);
 6771                } else {
 6772                    let background_color = cx.theme().status().deleted_background;
 6773                    self.highlight_text::<InlineCompletionHighlight>(
 6774                        edits.iter().map(|(range, _)| range.clone()).collect(),
 6775                        HighlightStyle {
 6776                            background_color: Some(background_color),
 6777                            ..Default::default()
 6778                        },
 6779                        cx,
 6780                    );
 6781                }
 6782            }
 6783
 6784            invalidation_row_range = edit_start_row..edit_end_row;
 6785
 6786            let display_mode = if all_edits_insertions_or_deletions(&edits, &multibuffer) {
 6787                if provider.show_tab_accept_marker() {
 6788                    EditDisplayMode::TabAccept
 6789                } else {
 6790                    EditDisplayMode::Inline
 6791                }
 6792            } else {
 6793                EditDisplayMode::DiffPopover
 6794            };
 6795
 6796            InlineCompletion::Edit {
 6797                edits,
 6798                edit_preview: inline_completion.edit_preview,
 6799                display_mode,
 6800                snapshot,
 6801            }
 6802        };
 6803
 6804        let invalidation_range = multibuffer
 6805            .anchor_before(Point::new(invalidation_row_range.start, 0))
 6806            ..multibuffer.anchor_after(Point::new(
 6807                invalidation_row_range.end,
 6808                multibuffer.line_len(MultiBufferRow(invalidation_row_range.end)),
 6809            ));
 6810
 6811        self.stale_inline_completion_in_menu = None;
 6812        self.active_inline_completion = Some(InlineCompletionState {
 6813            inlay_ids,
 6814            completion,
 6815            completion_id: inline_completion.id,
 6816            invalidation_range,
 6817        });
 6818
 6819        cx.notify();
 6820
 6821        Some(())
 6822    }
 6823
 6824    pub fn edit_prediction_provider(&self) -> Option<Arc<dyn InlineCompletionProviderHandle>> {
 6825        Some(self.edit_prediction_provider.as_ref()?.provider.clone())
 6826    }
 6827
 6828    fn clear_tasks(&mut self) {
 6829        self.tasks.clear()
 6830    }
 6831
 6832    fn insert_tasks(&mut self, key: (BufferId, BufferRow), value: RunnableTasks) {
 6833        if self.tasks.insert(key, value).is_some() {
 6834            // This case should hopefully be rare, but just in case...
 6835            log::error!(
 6836                "multiple different run targets found on a single line, only the last target will be rendered"
 6837            )
 6838        }
 6839    }
 6840
 6841    /// Get all display points of breakpoints that will be rendered within editor
 6842    ///
 6843    /// This function is used to handle overlaps between breakpoints and Code action/runner symbol.
 6844    /// It's also used to set the color of line numbers with breakpoints to the breakpoint color.
 6845    /// TODO debugger: Use this function to color toggle symbols that house nested breakpoints
 6846    fn active_breakpoints(
 6847        &self,
 6848        range: Range<DisplayRow>,
 6849        window: &mut Window,
 6850        cx: &mut Context<Self>,
 6851    ) -> HashMap<DisplayRow, (Anchor, Breakpoint)> {
 6852        let mut breakpoint_display_points = HashMap::default();
 6853
 6854        let Some(breakpoint_store) = self.breakpoint_store.clone() else {
 6855            return breakpoint_display_points;
 6856        };
 6857
 6858        let snapshot = self.snapshot(window, cx);
 6859
 6860        let multi_buffer_snapshot = &snapshot.display_snapshot.buffer_snapshot;
 6861        let Some(project) = self.project.as_ref() else {
 6862            return breakpoint_display_points;
 6863        };
 6864
 6865        let range = snapshot.display_point_to_point(DisplayPoint::new(range.start, 0), Bias::Left)
 6866            ..snapshot.display_point_to_point(DisplayPoint::new(range.end, 0), Bias::Right);
 6867
 6868        for (buffer_snapshot, range, excerpt_id) in
 6869            multi_buffer_snapshot.range_to_buffer_ranges(range)
 6870        {
 6871            let Some(buffer) = project.read_with(cx, |this, cx| {
 6872                this.buffer_for_id(buffer_snapshot.remote_id(), cx)
 6873            }) else {
 6874                continue;
 6875            };
 6876            let breakpoints = breakpoint_store.read(cx).breakpoints(
 6877                &buffer,
 6878                Some(
 6879                    buffer_snapshot.anchor_before(range.start)
 6880                        ..buffer_snapshot.anchor_after(range.end),
 6881                ),
 6882                buffer_snapshot,
 6883                cx,
 6884            );
 6885            for (anchor, breakpoint) in breakpoints {
 6886                let multi_buffer_anchor =
 6887                    Anchor::in_buffer(excerpt_id, buffer_snapshot.remote_id(), *anchor);
 6888                let position = multi_buffer_anchor
 6889                    .to_point(&multi_buffer_snapshot)
 6890                    .to_display_point(&snapshot);
 6891
 6892                breakpoint_display_points
 6893                    .insert(position.row(), (multi_buffer_anchor, breakpoint.clone()));
 6894            }
 6895        }
 6896
 6897        breakpoint_display_points
 6898    }
 6899
 6900    fn breakpoint_context_menu(
 6901        &self,
 6902        anchor: Anchor,
 6903        window: &mut Window,
 6904        cx: &mut Context<Self>,
 6905    ) -> Entity<ui::ContextMenu> {
 6906        let weak_editor = cx.weak_entity();
 6907        let focus_handle = self.focus_handle(cx);
 6908
 6909        let row = self
 6910            .buffer
 6911            .read(cx)
 6912            .snapshot(cx)
 6913            .summary_for_anchor::<Point>(&anchor)
 6914            .row;
 6915
 6916        let breakpoint = self
 6917            .breakpoint_at_row(row, window, cx)
 6918            .map(|(anchor, bp)| (anchor, Arc::from(bp)));
 6919
 6920        let log_breakpoint_msg = if breakpoint.as_ref().is_some_and(|bp| bp.1.message.is_some()) {
 6921            "Edit Log Breakpoint"
 6922        } else {
 6923            "Set Log Breakpoint"
 6924        };
 6925
 6926        let condition_breakpoint_msg = if breakpoint
 6927            .as_ref()
 6928            .is_some_and(|bp| bp.1.condition.is_some())
 6929        {
 6930            "Edit Condition Breakpoint"
 6931        } else {
 6932            "Set Condition Breakpoint"
 6933        };
 6934
 6935        let hit_condition_breakpoint_msg = if breakpoint
 6936            .as_ref()
 6937            .is_some_and(|bp| bp.1.hit_condition.is_some())
 6938        {
 6939            "Edit Hit Condition Breakpoint"
 6940        } else {
 6941            "Set Hit Condition Breakpoint"
 6942        };
 6943
 6944        let set_breakpoint_msg = if breakpoint.as_ref().is_some() {
 6945            "Unset Breakpoint"
 6946        } else {
 6947            "Set Breakpoint"
 6948        };
 6949
 6950        let run_to_cursor = command_palette_hooks::CommandPaletteFilter::try_global(cx)
 6951            .map_or(false, |filter| !filter.is_hidden(&DebuggerRunToCursor));
 6952
 6953        let toggle_state_msg = breakpoint.as_ref().map_or(None, |bp| match bp.1.state {
 6954            BreakpointState::Enabled => Some("Disable"),
 6955            BreakpointState::Disabled => Some("Enable"),
 6956        });
 6957
 6958        let (anchor, breakpoint) =
 6959            breakpoint.unwrap_or_else(|| (anchor, Arc::new(Breakpoint::new_standard())));
 6960
 6961        ui::ContextMenu::build(window, cx, |menu, _, _cx| {
 6962            menu.on_blur_subscription(Subscription::new(|| {}))
 6963                .context(focus_handle)
 6964                .when(run_to_cursor, |this| {
 6965                    let weak_editor = weak_editor.clone();
 6966                    this.entry("Run to cursor", None, move |window, cx| {
 6967                        weak_editor
 6968                            .update(cx, |editor, cx| {
 6969                                editor.change_selections(None, window, cx, |s| {
 6970                                    s.select_ranges([Point::new(row, 0)..Point::new(row, 0)])
 6971                                });
 6972                            })
 6973                            .ok();
 6974
 6975                        window.dispatch_action(Box::new(DebuggerRunToCursor), cx);
 6976                    })
 6977                    .separator()
 6978                })
 6979                .when_some(toggle_state_msg, |this, msg| {
 6980                    this.entry(msg, None, {
 6981                        let weak_editor = weak_editor.clone();
 6982                        let breakpoint = breakpoint.clone();
 6983                        move |_window, cx| {
 6984                            weak_editor
 6985                                .update(cx, |this, cx| {
 6986                                    this.edit_breakpoint_at_anchor(
 6987                                        anchor,
 6988                                        breakpoint.as_ref().clone(),
 6989                                        BreakpointEditAction::InvertState,
 6990                                        cx,
 6991                                    );
 6992                                })
 6993                                .log_err();
 6994                        }
 6995                    })
 6996                })
 6997                .entry(set_breakpoint_msg, None, {
 6998                    let weak_editor = weak_editor.clone();
 6999                    let breakpoint = breakpoint.clone();
 7000                    move |_window, cx| {
 7001                        weak_editor
 7002                            .update(cx, |this, cx| {
 7003                                this.edit_breakpoint_at_anchor(
 7004                                    anchor,
 7005                                    breakpoint.as_ref().clone(),
 7006                                    BreakpointEditAction::Toggle,
 7007                                    cx,
 7008                                );
 7009                            })
 7010                            .log_err();
 7011                    }
 7012                })
 7013                .entry(log_breakpoint_msg, None, {
 7014                    let breakpoint = breakpoint.clone();
 7015                    let weak_editor = weak_editor.clone();
 7016                    move |window, cx| {
 7017                        weak_editor
 7018                            .update(cx, |this, cx| {
 7019                                this.add_edit_breakpoint_block(
 7020                                    anchor,
 7021                                    breakpoint.as_ref(),
 7022                                    BreakpointPromptEditAction::Log,
 7023                                    window,
 7024                                    cx,
 7025                                );
 7026                            })
 7027                            .log_err();
 7028                    }
 7029                })
 7030                .entry(condition_breakpoint_msg, None, {
 7031                    let breakpoint = breakpoint.clone();
 7032                    let weak_editor = weak_editor.clone();
 7033                    move |window, cx| {
 7034                        weak_editor
 7035                            .update(cx, |this, cx| {
 7036                                this.add_edit_breakpoint_block(
 7037                                    anchor,
 7038                                    breakpoint.as_ref(),
 7039                                    BreakpointPromptEditAction::Condition,
 7040                                    window,
 7041                                    cx,
 7042                                );
 7043                            })
 7044                            .log_err();
 7045                    }
 7046                })
 7047                .entry(hit_condition_breakpoint_msg, None, move |window, cx| {
 7048                    weak_editor
 7049                        .update(cx, |this, cx| {
 7050                            this.add_edit_breakpoint_block(
 7051                                anchor,
 7052                                breakpoint.as_ref(),
 7053                                BreakpointPromptEditAction::HitCondition,
 7054                                window,
 7055                                cx,
 7056                            );
 7057                        })
 7058                        .log_err();
 7059                })
 7060        })
 7061    }
 7062
 7063    fn render_breakpoint(
 7064        &self,
 7065        position: Anchor,
 7066        row: DisplayRow,
 7067        breakpoint: &Breakpoint,
 7068        cx: &mut Context<Self>,
 7069    ) -> IconButton {
 7070        // Is it a breakpoint that shows up when hovering over gutter?
 7071        let (is_phantom, collides_with_existing) = self.gutter_breakpoint_indicator.0.map_or(
 7072            (false, false),
 7073            |PhantomBreakpointIndicator {
 7074                 is_active,
 7075                 display_row,
 7076                 collides_with_existing_breakpoint,
 7077             }| {
 7078                (
 7079                    is_active && display_row == row,
 7080                    collides_with_existing_breakpoint,
 7081                )
 7082            },
 7083        );
 7084
 7085        let (color, icon) = {
 7086            let icon = match (&breakpoint.message.is_some(), breakpoint.is_disabled()) {
 7087                (false, false) => ui::IconName::DebugBreakpoint,
 7088                (true, false) => ui::IconName::DebugLogBreakpoint,
 7089                (false, true) => ui::IconName::DebugDisabledBreakpoint,
 7090                (true, true) => ui::IconName::DebugDisabledLogBreakpoint,
 7091            };
 7092
 7093            let color = if is_phantom {
 7094                Color::Hint
 7095            } else {
 7096                Color::Debugger
 7097            };
 7098
 7099            (color, icon)
 7100        };
 7101
 7102        let breakpoint = Arc::from(breakpoint.clone());
 7103
 7104        let alt_as_text = gpui::Keystroke {
 7105            modifiers: Modifiers::secondary_key(),
 7106            ..Default::default()
 7107        };
 7108        let primary_action_text = if breakpoint.is_disabled() {
 7109            "enable"
 7110        } else if is_phantom && !collides_with_existing {
 7111            "set"
 7112        } else {
 7113            "unset"
 7114        };
 7115        let mut primary_text = format!("Click to {primary_action_text}");
 7116        if collides_with_existing && !breakpoint.is_disabled() {
 7117            use std::fmt::Write;
 7118            write!(primary_text, ", {alt_as_text}-click to disable").ok();
 7119        }
 7120        let primary_text = SharedString::from(primary_text);
 7121        let focus_handle = self.focus_handle.clone();
 7122        IconButton::new(("breakpoint_indicator", row.0 as usize), icon)
 7123            .icon_size(IconSize::XSmall)
 7124            .size(ui::ButtonSize::None)
 7125            .icon_color(color)
 7126            .style(ButtonStyle::Transparent)
 7127            .on_click(cx.listener({
 7128                let breakpoint = breakpoint.clone();
 7129
 7130                move |editor, event: &ClickEvent, window, cx| {
 7131                    let edit_action = if event.modifiers().platform || breakpoint.is_disabled() {
 7132                        BreakpointEditAction::InvertState
 7133                    } else {
 7134                        BreakpointEditAction::Toggle
 7135                    };
 7136
 7137                    window.focus(&editor.focus_handle(cx));
 7138                    editor.edit_breakpoint_at_anchor(
 7139                        position,
 7140                        breakpoint.as_ref().clone(),
 7141                        edit_action,
 7142                        cx,
 7143                    );
 7144                }
 7145            }))
 7146            .on_right_click(cx.listener(move |editor, event: &ClickEvent, window, cx| {
 7147                editor.set_breakpoint_context_menu(
 7148                    row,
 7149                    Some(position),
 7150                    event.down.position,
 7151                    window,
 7152                    cx,
 7153                );
 7154            }))
 7155            .tooltip(move |window, cx| {
 7156                Tooltip::with_meta_in(
 7157                    primary_text.clone(),
 7158                    None,
 7159                    "Right-click for more options",
 7160                    &focus_handle,
 7161                    window,
 7162                    cx,
 7163                )
 7164            })
 7165    }
 7166
 7167    fn build_tasks_context(
 7168        project: &Entity<Project>,
 7169        buffer: &Entity<Buffer>,
 7170        buffer_row: u32,
 7171        tasks: &Arc<RunnableTasks>,
 7172        cx: &mut Context<Self>,
 7173    ) -> Task<Option<task::TaskContext>> {
 7174        let position = Point::new(buffer_row, tasks.column);
 7175        let range_start = buffer.read(cx).anchor_at(position, Bias::Right);
 7176        let location = Location {
 7177            buffer: buffer.clone(),
 7178            range: range_start..range_start,
 7179        };
 7180        // Fill in the environmental variables from the tree-sitter captures
 7181        let mut captured_task_variables = TaskVariables::default();
 7182        for (capture_name, value) in tasks.extra_variables.clone() {
 7183            captured_task_variables.insert(
 7184                task::VariableName::Custom(capture_name.into()),
 7185                value.clone(),
 7186            );
 7187        }
 7188        project.update(cx, |project, cx| {
 7189            project.task_store().update(cx, |task_store, cx| {
 7190                task_store.task_context_for_location(captured_task_variables, location, cx)
 7191            })
 7192        })
 7193    }
 7194
 7195    pub fn spawn_nearest_task(
 7196        &mut self,
 7197        action: &SpawnNearestTask,
 7198        window: &mut Window,
 7199        cx: &mut Context<Self>,
 7200    ) {
 7201        let Some((workspace, _)) = self.workspace.clone() else {
 7202            return;
 7203        };
 7204        let Some(project) = self.project.clone() else {
 7205            return;
 7206        };
 7207
 7208        // Try to find a closest, enclosing node using tree-sitter that has a
 7209        // task
 7210        let Some((buffer, buffer_row, tasks)) = self
 7211            .find_enclosing_node_task(cx)
 7212            // Or find the task that's closest in row-distance.
 7213            .or_else(|| self.find_closest_task(cx))
 7214        else {
 7215            return;
 7216        };
 7217
 7218        let reveal_strategy = action.reveal;
 7219        let task_context = Self::build_tasks_context(&project, &buffer, buffer_row, &tasks, cx);
 7220        cx.spawn_in(window, async move |_, cx| {
 7221            let context = task_context.await?;
 7222            let (task_source_kind, mut resolved_task) = tasks.resolve(&context).next()?;
 7223
 7224            let resolved = &mut resolved_task.resolved;
 7225            resolved.reveal = reveal_strategy;
 7226
 7227            workspace
 7228                .update_in(cx, |workspace, window, cx| {
 7229                    workspace.schedule_resolved_task(
 7230                        task_source_kind,
 7231                        resolved_task,
 7232                        false,
 7233                        window,
 7234                        cx,
 7235                    );
 7236                })
 7237                .ok()
 7238        })
 7239        .detach();
 7240    }
 7241
 7242    fn find_closest_task(
 7243        &mut self,
 7244        cx: &mut Context<Self>,
 7245    ) -> Option<(Entity<Buffer>, u32, Arc<RunnableTasks>)> {
 7246        let cursor_row = self.selections.newest_adjusted(cx).head().row;
 7247
 7248        let ((buffer_id, row), tasks) = self
 7249            .tasks
 7250            .iter()
 7251            .min_by_key(|((_, row), _)| cursor_row.abs_diff(*row))?;
 7252
 7253        let buffer = self.buffer.read(cx).buffer(*buffer_id)?;
 7254        let tasks = Arc::new(tasks.to_owned());
 7255        Some((buffer, *row, tasks))
 7256    }
 7257
 7258    fn find_enclosing_node_task(
 7259        &mut self,
 7260        cx: &mut Context<Self>,
 7261    ) -> Option<(Entity<Buffer>, u32, Arc<RunnableTasks>)> {
 7262        let snapshot = self.buffer.read(cx).snapshot(cx);
 7263        let offset = self.selections.newest::<usize>(cx).head();
 7264        let excerpt = snapshot.excerpt_containing(offset..offset)?;
 7265        let buffer_id = excerpt.buffer().remote_id();
 7266
 7267        let layer = excerpt.buffer().syntax_layer_at(offset)?;
 7268        let mut cursor = layer.node().walk();
 7269
 7270        while cursor.goto_first_child_for_byte(offset).is_some() {
 7271            if cursor.node().end_byte() == offset {
 7272                cursor.goto_next_sibling();
 7273            }
 7274        }
 7275
 7276        // Ascend to the smallest ancestor that contains the range and has a task.
 7277        loop {
 7278            let node = cursor.node();
 7279            let node_range = node.byte_range();
 7280            let symbol_start_row = excerpt.buffer().offset_to_point(node.start_byte()).row;
 7281
 7282            // Check if this node contains our offset
 7283            if node_range.start <= offset && node_range.end >= offset {
 7284                // If it contains offset, check for task
 7285                if let Some(tasks) = self.tasks.get(&(buffer_id, symbol_start_row)) {
 7286                    let buffer = self.buffer.read(cx).buffer(buffer_id)?;
 7287                    return Some((buffer, symbol_start_row, Arc::new(tasks.to_owned())));
 7288                }
 7289            }
 7290
 7291            if !cursor.goto_parent() {
 7292                break;
 7293            }
 7294        }
 7295        None
 7296    }
 7297
 7298    fn render_run_indicator(
 7299        &self,
 7300        _style: &EditorStyle,
 7301        is_active: bool,
 7302        row: DisplayRow,
 7303        breakpoint: Option<(Anchor, Breakpoint)>,
 7304        cx: &mut Context<Self>,
 7305    ) -> IconButton {
 7306        let color = Color::Muted;
 7307        let position = breakpoint.as_ref().map(|(anchor, _)| *anchor);
 7308
 7309        IconButton::new(("run_indicator", row.0 as usize), ui::IconName::Play)
 7310            .shape(ui::IconButtonShape::Square)
 7311            .icon_size(IconSize::XSmall)
 7312            .icon_color(color)
 7313            .toggle_state(is_active)
 7314            .on_click(cx.listener(move |editor, e: &ClickEvent, window, cx| {
 7315                let quick_launch = e.down.button == MouseButton::Left;
 7316                window.focus(&editor.focus_handle(cx));
 7317                editor.toggle_code_actions(
 7318                    &ToggleCodeActions {
 7319                        deployed_from_indicator: Some(row),
 7320                        quick_launch,
 7321                    },
 7322                    window,
 7323                    cx,
 7324                );
 7325            }))
 7326            .on_right_click(cx.listener(move |editor, event: &ClickEvent, window, cx| {
 7327                editor.set_breakpoint_context_menu(row, position, event.down.position, window, cx);
 7328            }))
 7329    }
 7330
 7331    pub fn context_menu_visible(&self) -> bool {
 7332        !self.edit_prediction_preview_is_active()
 7333            && self
 7334                .context_menu
 7335                .borrow()
 7336                .as_ref()
 7337                .map_or(false, |menu| menu.visible())
 7338    }
 7339
 7340    fn context_menu_origin(&self) -> Option<ContextMenuOrigin> {
 7341        self.context_menu
 7342            .borrow()
 7343            .as_ref()
 7344            .map(|menu| menu.origin())
 7345    }
 7346
 7347    pub fn set_context_menu_options(&mut self, options: ContextMenuOptions) {
 7348        self.context_menu_options = Some(options);
 7349    }
 7350
 7351    const EDIT_PREDICTION_POPOVER_PADDING_X: Pixels = Pixels(24.);
 7352    const EDIT_PREDICTION_POPOVER_PADDING_Y: Pixels = Pixels(2.);
 7353
 7354    fn render_edit_prediction_popover(
 7355        &mut self,
 7356        text_bounds: &Bounds<Pixels>,
 7357        content_origin: gpui::Point<Pixels>,
 7358        right_margin: Pixels,
 7359        editor_snapshot: &EditorSnapshot,
 7360        visible_row_range: Range<DisplayRow>,
 7361        scroll_top: f32,
 7362        scroll_bottom: f32,
 7363        line_layouts: &[LineWithInvisibles],
 7364        line_height: Pixels,
 7365        scroll_pixel_position: gpui::Point<Pixels>,
 7366        newest_selection_head: Option<DisplayPoint>,
 7367        editor_width: Pixels,
 7368        style: &EditorStyle,
 7369        window: &mut Window,
 7370        cx: &mut App,
 7371    ) -> Option<(AnyElement, gpui::Point<Pixels>)> {
 7372        if self.mode().is_minimap() {
 7373            return None;
 7374        }
 7375        let active_inline_completion = self.active_inline_completion.as_ref()?;
 7376
 7377        if self.edit_prediction_visible_in_cursor_popover(true) {
 7378            return None;
 7379        }
 7380
 7381        match &active_inline_completion.completion {
 7382            InlineCompletion::Move { target, .. } => {
 7383                let target_display_point = target.to_display_point(editor_snapshot);
 7384
 7385                if self.edit_prediction_requires_modifier() {
 7386                    if !self.edit_prediction_preview_is_active() {
 7387                        return None;
 7388                    }
 7389
 7390                    self.render_edit_prediction_modifier_jump_popover(
 7391                        text_bounds,
 7392                        content_origin,
 7393                        visible_row_range,
 7394                        line_layouts,
 7395                        line_height,
 7396                        scroll_pixel_position,
 7397                        newest_selection_head,
 7398                        target_display_point,
 7399                        window,
 7400                        cx,
 7401                    )
 7402                } else {
 7403                    self.render_edit_prediction_eager_jump_popover(
 7404                        text_bounds,
 7405                        content_origin,
 7406                        editor_snapshot,
 7407                        visible_row_range,
 7408                        scroll_top,
 7409                        scroll_bottom,
 7410                        line_height,
 7411                        scroll_pixel_position,
 7412                        target_display_point,
 7413                        editor_width,
 7414                        window,
 7415                        cx,
 7416                    )
 7417                }
 7418            }
 7419            InlineCompletion::Edit {
 7420                display_mode: EditDisplayMode::Inline,
 7421                ..
 7422            } => None,
 7423            InlineCompletion::Edit {
 7424                display_mode: EditDisplayMode::TabAccept,
 7425                edits,
 7426                ..
 7427            } => {
 7428                let range = &edits.first()?.0;
 7429                let target_display_point = range.end.to_display_point(editor_snapshot);
 7430
 7431                self.render_edit_prediction_end_of_line_popover(
 7432                    "Accept",
 7433                    editor_snapshot,
 7434                    visible_row_range,
 7435                    target_display_point,
 7436                    line_height,
 7437                    scroll_pixel_position,
 7438                    content_origin,
 7439                    editor_width,
 7440                    window,
 7441                    cx,
 7442                )
 7443            }
 7444            InlineCompletion::Edit {
 7445                edits,
 7446                edit_preview,
 7447                display_mode: EditDisplayMode::DiffPopover,
 7448                snapshot,
 7449            } => self.render_edit_prediction_diff_popover(
 7450                text_bounds,
 7451                content_origin,
 7452                right_margin,
 7453                editor_snapshot,
 7454                visible_row_range,
 7455                line_layouts,
 7456                line_height,
 7457                scroll_pixel_position,
 7458                newest_selection_head,
 7459                editor_width,
 7460                style,
 7461                edits,
 7462                edit_preview,
 7463                snapshot,
 7464                window,
 7465                cx,
 7466            ),
 7467        }
 7468    }
 7469
 7470    fn render_edit_prediction_modifier_jump_popover(
 7471        &mut self,
 7472        text_bounds: &Bounds<Pixels>,
 7473        content_origin: gpui::Point<Pixels>,
 7474        visible_row_range: Range<DisplayRow>,
 7475        line_layouts: &[LineWithInvisibles],
 7476        line_height: Pixels,
 7477        scroll_pixel_position: gpui::Point<Pixels>,
 7478        newest_selection_head: Option<DisplayPoint>,
 7479        target_display_point: DisplayPoint,
 7480        window: &mut Window,
 7481        cx: &mut App,
 7482    ) -> Option<(AnyElement, gpui::Point<Pixels>)> {
 7483        let scrolled_content_origin =
 7484            content_origin - gpui::Point::new(scroll_pixel_position.x, Pixels(0.0));
 7485
 7486        const SCROLL_PADDING_Y: Pixels = px(12.);
 7487
 7488        if target_display_point.row() < visible_row_range.start {
 7489            return self.render_edit_prediction_scroll_popover(
 7490                |_| SCROLL_PADDING_Y,
 7491                IconName::ArrowUp,
 7492                visible_row_range,
 7493                line_layouts,
 7494                newest_selection_head,
 7495                scrolled_content_origin,
 7496                window,
 7497                cx,
 7498            );
 7499        } else if target_display_point.row() >= visible_row_range.end {
 7500            return self.render_edit_prediction_scroll_popover(
 7501                |size| text_bounds.size.height - size.height - SCROLL_PADDING_Y,
 7502                IconName::ArrowDown,
 7503                visible_row_range,
 7504                line_layouts,
 7505                newest_selection_head,
 7506                scrolled_content_origin,
 7507                window,
 7508                cx,
 7509            );
 7510        }
 7511
 7512        const POLE_WIDTH: Pixels = px(2.);
 7513
 7514        let line_layout =
 7515            line_layouts.get(target_display_point.row().minus(visible_row_range.start) as usize)?;
 7516        let target_column = target_display_point.column() as usize;
 7517
 7518        let target_x = line_layout.x_for_index(target_column);
 7519        let target_y =
 7520            (target_display_point.row().as_f32() * line_height) - scroll_pixel_position.y;
 7521
 7522        let flag_on_right = target_x < text_bounds.size.width / 2.;
 7523
 7524        let mut border_color = Self::edit_prediction_callout_popover_border_color(cx);
 7525        border_color.l += 0.001;
 7526
 7527        let mut element = v_flex()
 7528            .items_end()
 7529            .when(flag_on_right, |el| el.items_start())
 7530            .child(if flag_on_right {
 7531                self.render_edit_prediction_line_popover("Jump", None, window, cx)?
 7532                    .rounded_bl(px(0.))
 7533                    .rounded_tl(px(0.))
 7534                    .border_l_2()
 7535                    .border_color(border_color)
 7536            } else {
 7537                self.render_edit_prediction_line_popover("Jump", None, window, cx)?
 7538                    .rounded_br(px(0.))
 7539                    .rounded_tr(px(0.))
 7540                    .border_r_2()
 7541                    .border_color(border_color)
 7542            })
 7543            .child(div().w(POLE_WIDTH).bg(border_color).h(line_height))
 7544            .into_any();
 7545
 7546        let size = element.layout_as_root(AvailableSpace::min_size(), window, cx);
 7547
 7548        let mut origin = scrolled_content_origin + point(target_x, target_y)
 7549            - point(
 7550                if flag_on_right {
 7551                    POLE_WIDTH
 7552                } else {
 7553                    size.width - POLE_WIDTH
 7554                },
 7555                size.height - line_height,
 7556            );
 7557
 7558        origin.x = origin.x.max(content_origin.x);
 7559
 7560        element.prepaint_at(origin, window, cx);
 7561
 7562        Some((element, origin))
 7563    }
 7564
 7565    fn render_edit_prediction_scroll_popover(
 7566        &mut self,
 7567        to_y: impl Fn(Size<Pixels>) -> Pixels,
 7568        scroll_icon: IconName,
 7569        visible_row_range: Range<DisplayRow>,
 7570        line_layouts: &[LineWithInvisibles],
 7571        newest_selection_head: Option<DisplayPoint>,
 7572        scrolled_content_origin: gpui::Point<Pixels>,
 7573        window: &mut Window,
 7574        cx: &mut App,
 7575    ) -> Option<(AnyElement, gpui::Point<Pixels>)> {
 7576        let mut element = self
 7577            .render_edit_prediction_line_popover("Scroll", Some(scroll_icon), window, cx)?
 7578            .into_any();
 7579
 7580        let size = element.layout_as_root(AvailableSpace::min_size(), window, cx);
 7581
 7582        let cursor = newest_selection_head?;
 7583        let cursor_row_layout =
 7584            line_layouts.get(cursor.row().minus(visible_row_range.start) as usize)?;
 7585        let cursor_column = cursor.column() as usize;
 7586
 7587        let cursor_character_x = cursor_row_layout.x_for_index(cursor_column);
 7588
 7589        let origin = scrolled_content_origin + point(cursor_character_x, to_y(size));
 7590
 7591        element.prepaint_at(origin, window, cx);
 7592        Some((element, origin))
 7593    }
 7594
 7595    fn render_edit_prediction_eager_jump_popover(
 7596        &mut self,
 7597        text_bounds: &Bounds<Pixels>,
 7598        content_origin: gpui::Point<Pixels>,
 7599        editor_snapshot: &EditorSnapshot,
 7600        visible_row_range: Range<DisplayRow>,
 7601        scroll_top: f32,
 7602        scroll_bottom: f32,
 7603        line_height: Pixels,
 7604        scroll_pixel_position: gpui::Point<Pixels>,
 7605        target_display_point: DisplayPoint,
 7606        editor_width: Pixels,
 7607        window: &mut Window,
 7608        cx: &mut App,
 7609    ) -> Option<(AnyElement, gpui::Point<Pixels>)> {
 7610        if target_display_point.row().as_f32() < scroll_top {
 7611            let mut element = self
 7612                .render_edit_prediction_line_popover(
 7613                    "Jump to Edit",
 7614                    Some(IconName::ArrowUp),
 7615                    window,
 7616                    cx,
 7617                )?
 7618                .into_any();
 7619
 7620            let size = element.layout_as_root(AvailableSpace::min_size(), window, cx);
 7621            let offset = point(
 7622                (text_bounds.size.width - size.width) / 2.,
 7623                Self::EDIT_PREDICTION_POPOVER_PADDING_Y,
 7624            );
 7625
 7626            let origin = text_bounds.origin + offset;
 7627            element.prepaint_at(origin, window, cx);
 7628            Some((element, origin))
 7629        } else if (target_display_point.row().as_f32() + 1.) > scroll_bottom {
 7630            let mut element = self
 7631                .render_edit_prediction_line_popover(
 7632                    "Jump to Edit",
 7633                    Some(IconName::ArrowDown),
 7634                    window,
 7635                    cx,
 7636                )?
 7637                .into_any();
 7638
 7639            let size = element.layout_as_root(AvailableSpace::min_size(), window, cx);
 7640            let offset = point(
 7641                (text_bounds.size.width - size.width) / 2.,
 7642                text_bounds.size.height - size.height - Self::EDIT_PREDICTION_POPOVER_PADDING_Y,
 7643            );
 7644
 7645            let origin = text_bounds.origin + offset;
 7646            element.prepaint_at(origin, window, cx);
 7647            Some((element, origin))
 7648        } else {
 7649            self.render_edit_prediction_end_of_line_popover(
 7650                "Jump to Edit",
 7651                editor_snapshot,
 7652                visible_row_range,
 7653                target_display_point,
 7654                line_height,
 7655                scroll_pixel_position,
 7656                content_origin,
 7657                editor_width,
 7658                window,
 7659                cx,
 7660            )
 7661        }
 7662    }
 7663
 7664    fn render_edit_prediction_end_of_line_popover(
 7665        self: &mut Editor,
 7666        label: &'static str,
 7667        editor_snapshot: &EditorSnapshot,
 7668        visible_row_range: Range<DisplayRow>,
 7669        target_display_point: DisplayPoint,
 7670        line_height: Pixels,
 7671        scroll_pixel_position: gpui::Point<Pixels>,
 7672        content_origin: gpui::Point<Pixels>,
 7673        editor_width: Pixels,
 7674        window: &mut Window,
 7675        cx: &mut App,
 7676    ) -> Option<(AnyElement, gpui::Point<Pixels>)> {
 7677        let target_line_end = DisplayPoint::new(
 7678            target_display_point.row(),
 7679            editor_snapshot.line_len(target_display_point.row()),
 7680        );
 7681
 7682        let mut element = self
 7683            .render_edit_prediction_line_popover(label, None, window, cx)?
 7684            .into_any();
 7685
 7686        let size = element.layout_as_root(AvailableSpace::min_size(), window, cx);
 7687
 7688        let line_origin = self.display_to_pixel_point(target_line_end, editor_snapshot, window)?;
 7689
 7690        let start_point = content_origin - point(scroll_pixel_position.x, Pixels::ZERO);
 7691        let mut origin = start_point
 7692            + line_origin
 7693            + point(Self::EDIT_PREDICTION_POPOVER_PADDING_X, Pixels::ZERO);
 7694        origin.x = origin.x.max(content_origin.x);
 7695
 7696        let max_x = content_origin.x + editor_width - size.width;
 7697
 7698        if origin.x > max_x {
 7699            let offset = line_height + Self::EDIT_PREDICTION_POPOVER_PADDING_Y;
 7700
 7701            let icon = if visible_row_range.contains(&(target_display_point.row() + 2)) {
 7702                origin.y += offset;
 7703                IconName::ArrowUp
 7704            } else {
 7705                origin.y -= offset;
 7706                IconName::ArrowDown
 7707            };
 7708
 7709            element = self
 7710                .render_edit_prediction_line_popover(label, Some(icon), window, cx)?
 7711                .into_any();
 7712
 7713            let size = element.layout_as_root(AvailableSpace::min_size(), window, cx);
 7714
 7715            origin.x = content_origin.x + editor_width - size.width - px(2.);
 7716        }
 7717
 7718        element.prepaint_at(origin, window, cx);
 7719        Some((element, origin))
 7720    }
 7721
 7722    fn render_edit_prediction_diff_popover(
 7723        self: &Editor,
 7724        text_bounds: &Bounds<Pixels>,
 7725        content_origin: gpui::Point<Pixels>,
 7726        right_margin: Pixels,
 7727        editor_snapshot: &EditorSnapshot,
 7728        visible_row_range: Range<DisplayRow>,
 7729        line_layouts: &[LineWithInvisibles],
 7730        line_height: Pixels,
 7731        scroll_pixel_position: gpui::Point<Pixels>,
 7732        newest_selection_head: Option<DisplayPoint>,
 7733        editor_width: Pixels,
 7734        style: &EditorStyle,
 7735        edits: &Vec<(Range<Anchor>, String)>,
 7736        edit_preview: &Option<language::EditPreview>,
 7737        snapshot: &language::BufferSnapshot,
 7738        window: &mut Window,
 7739        cx: &mut App,
 7740    ) -> Option<(AnyElement, gpui::Point<Pixels>)> {
 7741        let edit_start = edits
 7742            .first()
 7743            .unwrap()
 7744            .0
 7745            .start
 7746            .to_display_point(editor_snapshot);
 7747        let edit_end = edits
 7748            .last()
 7749            .unwrap()
 7750            .0
 7751            .end
 7752            .to_display_point(editor_snapshot);
 7753
 7754        let is_visible = visible_row_range.contains(&edit_start.row())
 7755            || visible_row_range.contains(&edit_end.row());
 7756        if !is_visible {
 7757            return None;
 7758        }
 7759
 7760        let highlighted_edits =
 7761            crate::inline_completion_edit_text(&snapshot, edits, edit_preview.as_ref()?, false, cx);
 7762
 7763        let styled_text = highlighted_edits.to_styled_text(&style.text);
 7764        let line_count = highlighted_edits.text.lines().count();
 7765
 7766        const BORDER_WIDTH: Pixels = px(1.);
 7767
 7768        let keybind = self.render_edit_prediction_accept_keybind(window, cx);
 7769        let has_keybind = keybind.is_some();
 7770
 7771        let mut element = h_flex()
 7772            .items_start()
 7773            .child(
 7774                h_flex()
 7775                    .bg(cx.theme().colors().editor_background)
 7776                    .border(BORDER_WIDTH)
 7777                    .shadow_sm()
 7778                    .border_color(cx.theme().colors().border)
 7779                    .rounded_l_lg()
 7780                    .when(line_count > 1, |el| el.rounded_br_lg())
 7781                    .pr_1()
 7782                    .child(styled_text),
 7783            )
 7784            .child(
 7785                h_flex()
 7786                    .h(line_height + BORDER_WIDTH * 2.)
 7787                    .px_1p5()
 7788                    .gap_1()
 7789                    // Workaround: For some reason, there's a gap if we don't do this
 7790                    .ml(-BORDER_WIDTH)
 7791                    .shadow(smallvec![gpui::BoxShadow {
 7792                        color: gpui::black().opacity(0.05),
 7793                        offset: point(px(1.), px(1.)),
 7794                        blur_radius: px(2.),
 7795                        spread_radius: px(0.),
 7796                    }])
 7797                    .bg(Editor::edit_prediction_line_popover_bg_color(cx))
 7798                    .border(BORDER_WIDTH)
 7799                    .border_color(cx.theme().colors().border)
 7800                    .rounded_r_lg()
 7801                    .id("edit_prediction_diff_popover_keybind")
 7802                    .when(!has_keybind, |el| {
 7803                        let status_colors = cx.theme().status();
 7804
 7805                        el.bg(status_colors.error_background)
 7806                            .border_color(status_colors.error.opacity(0.6))
 7807                            .child(Icon::new(IconName::Info).color(Color::Error))
 7808                            .cursor_default()
 7809                            .hoverable_tooltip(move |_window, cx| {
 7810                                cx.new(|_| MissingEditPredictionKeybindingTooltip).into()
 7811                            })
 7812                    })
 7813                    .children(keybind),
 7814            )
 7815            .into_any();
 7816
 7817        let longest_row =
 7818            editor_snapshot.longest_row_in_range(edit_start.row()..edit_end.row() + 1);
 7819        let longest_line_width = if visible_row_range.contains(&longest_row) {
 7820            line_layouts[(longest_row.0 - visible_row_range.start.0) as usize].width
 7821        } else {
 7822            layout_line(
 7823                longest_row,
 7824                editor_snapshot,
 7825                style,
 7826                editor_width,
 7827                |_| false,
 7828                window,
 7829                cx,
 7830            )
 7831            .width
 7832        };
 7833
 7834        let viewport_bounds =
 7835            Bounds::new(Default::default(), window.viewport_size()).extend(Edges {
 7836                right: -right_margin,
 7837                ..Default::default()
 7838            });
 7839
 7840        let x_after_longest =
 7841            text_bounds.origin.x + longest_line_width + Self::EDIT_PREDICTION_POPOVER_PADDING_X
 7842                - scroll_pixel_position.x;
 7843
 7844        let element_bounds = element.layout_as_root(AvailableSpace::min_size(), window, cx);
 7845
 7846        // Fully visible if it can be displayed within the window (allow overlapping other
 7847        // panes). However, this is only allowed if the popover starts within text_bounds.
 7848        let can_position_to_the_right = x_after_longest < text_bounds.right()
 7849            && x_after_longest + element_bounds.width < viewport_bounds.right();
 7850
 7851        let mut origin = if can_position_to_the_right {
 7852            point(
 7853                x_after_longest,
 7854                text_bounds.origin.y + edit_start.row().as_f32() * line_height
 7855                    - scroll_pixel_position.y,
 7856            )
 7857        } else {
 7858            let cursor_row = newest_selection_head.map(|head| head.row());
 7859            let above_edit = edit_start
 7860                .row()
 7861                .0
 7862                .checked_sub(line_count as u32)
 7863                .map(DisplayRow);
 7864            let below_edit = Some(edit_end.row() + 1);
 7865            let above_cursor =
 7866                cursor_row.and_then(|row| row.0.checked_sub(line_count as u32).map(DisplayRow));
 7867            let below_cursor = cursor_row.map(|cursor_row| cursor_row + 1);
 7868
 7869            // Place the edit popover adjacent to the edit if there is a location
 7870            // available that is onscreen and does not obscure the cursor. Otherwise,
 7871            // place it adjacent to the cursor.
 7872            let row_target = [above_edit, below_edit, above_cursor, below_cursor]
 7873                .into_iter()
 7874                .flatten()
 7875                .find(|&start_row| {
 7876                    let end_row = start_row + line_count as u32;
 7877                    visible_row_range.contains(&start_row)
 7878                        && visible_row_range.contains(&end_row)
 7879                        && cursor_row.map_or(true, |cursor_row| {
 7880                            !((start_row..end_row).contains(&cursor_row))
 7881                        })
 7882                })?;
 7883
 7884            content_origin
 7885                + point(
 7886                    -scroll_pixel_position.x,
 7887                    row_target.as_f32() * line_height - scroll_pixel_position.y,
 7888                )
 7889        };
 7890
 7891        origin.x -= BORDER_WIDTH;
 7892
 7893        window.defer_draw(element, origin, 1);
 7894
 7895        // Do not return an element, since it will already be drawn due to defer_draw.
 7896        None
 7897    }
 7898
 7899    fn edit_prediction_cursor_popover_height(&self) -> Pixels {
 7900        px(30.)
 7901    }
 7902
 7903    fn current_user_player_color(&self, cx: &mut App) -> PlayerColor {
 7904        if self.read_only(cx) {
 7905            cx.theme().players().read_only()
 7906        } else {
 7907            self.style.as_ref().unwrap().local_player
 7908        }
 7909    }
 7910
 7911    fn render_edit_prediction_accept_keybind(
 7912        &self,
 7913        window: &mut Window,
 7914        cx: &App,
 7915    ) -> Option<AnyElement> {
 7916        let accept_binding = self.accept_edit_prediction_keybind(window, cx);
 7917        let accept_keystroke = accept_binding.keystroke()?;
 7918
 7919        let is_platform_style_mac = PlatformStyle::platform() == PlatformStyle::Mac;
 7920
 7921        let modifiers_color = if accept_keystroke.modifiers == window.modifiers() {
 7922            Color::Accent
 7923        } else {
 7924            Color::Muted
 7925        };
 7926
 7927        h_flex()
 7928            .px_0p5()
 7929            .when(is_platform_style_mac, |parent| parent.gap_0p5())
 7930            .font(theme::ThemeSettings::get_global(cx).buffer_font.clone())
 7931            .text_size(TextSize::XSmall.rems(cx))
 7932            .child(h_flex().children(ui::render_modifiers(
 7933                &accept_keystroke.modifiers,
 7934                PlatformStyle::platform(),
 7935                Some(modifiers_color),
 7936                Some(IconSize::XSmall.rems().into()),
 7937                true,
 7938            )))
 7939            .when(is_platform_style_mac, |parent| {
 7940                parent.child(accept_keystroke.key.clone())
 7941            })
 7942            .when(!is_platform_style_mac, |parent| {
 7943                parent.child(
 7944                    Key::new(
 7945                        util::capitalize(&accept_keystroke.key),
 7946                        Some(Color::Default),
 7947                    )
 7948                    .size(Some(IconSize::XSmall.rems().into())),
 7949                )
 7950            })
 7951            .into_any()
 7952            .into()
 7953    }
 7954
 7955    fn render_edit_prediction_line_popover(
 7956        &self,
 7957        label: impl Into<SharedString>,
 7958        icon: Option<IconName>,
 7959        window: &mut Window,
 7960        cx: &App,
 7961    ) -> Option<Stateful<Div>> {
 7962        let padding_right = if icon.is_some() { px(4.) } else { px(8.) };
 7963
 7964        let keybind = self.render_edit_prediction_accept_keybind(window, cx);
 7965        let has_keybind = keybind.is_some();
 7966
 7967        let result = h_flex()
 7968            .id("ep-line-popover")
 7969            .py_0p5()
 7970            .pl_1()
 7971            .pr(padding_right)
 7972            .gap_1()
 7973            .rounded_md()
 7974            .border_1()
 7975            .bg(Self::edit_prediction_line_popover_bg_color(cx))
 7976            .border_color(Self::edit_prediction_callout_popover_border_color(cx))
 7977            .shadow_sm()
 7978            .when(!has_keybind, |el| {
 7979                let status_colors = cx.theme().status();
 7980
 7981                el.bg(status_colors.error_background)
 7982                    .border_color(status_colors.error.opacity(0.6))
 7983                    .pl_2()
 7984                    .child(Icon::new(IconName::ZedPredictError).color(Color::Error))
 7985                    .cursor_default()
 7986                    .hoverable_tooltip(move |_window, cx| {
 7987                        cx.new(|_| MissingEditPredictionKeybindingTooltip).into()
 7988                    })
 7989            })
 7990            .children(keybind)
 7991            .child(
 7992                Label::new(label)
 7993                    .size(LabelSize::Small)
 7994                    .when(!has_keybind, |el| {
 7995                        el.color(cx.theme().status().error.into()).strikethrough()
 7996                    }),
 7997            )
 7998            .when(!has_keybind, |el| {
 7999                el.child(
 8000                    h_flex().ml_1().child(
 8001                        Icon::new(IconName::Info)
 8002                            .size(IconSize::Small)
 8003                            .color(cx.theme().status().error.into()),
 8004                    ),
 8005                )
 8006            })
 8007            .when_some(icon, |element, icon| {
 8008                element.child(
 8009                    div()
 8010                        .mt(px(1.5))
 8011                        .child(Icon::new(icon).size(IconSize::Small)),
 8012                )
 8013            });
 8014
 8015        Some(result)
 8016    }
 8017
 8018    fn edit_prediction_line_popover_bg_color(cx: &App) -> Hsla {
 8019        let accent_color = cx.theme().colors().text_accent;
 8020        let editor_bg_color = cx.theme().colors().editor_background;
 8021        editor_bg_color.blend(accent_color.opacity(0.1))
 8022    }
 8023
 8024    fn edit_prediction_callout_popover_border_color(cx: &App) -> Hsla {
 8025        let accent_color = cx.theme().colors().text_accent;
 8026        let editor_bg_color = cx.theme().colors().editor_background;
 8027        editor_bg_color.blend(accent_color.opacity(0.6))
 8028    }
 8029
 8030    fn render_edit_prediction_cursor_popover(
 8031        &self,
 8032        min_width: Pixels,
 8033        max_width: Pixels,
 8034        cursor_point: Point,
 8035        style: &EditorStyle,
 8036        accept_keystroke: Option<&gpui::Keystroke>,
 8037        _window: &Window,
 8038        cx: &mut Context<Editor>,
 8039    ) -> Option<AnyElement> {
 8040        let provider = self.edit_prediction_provider.as_ref()?;
 8041
 8042        if provider.provider.needs_terms_acceptance(cx) {
 8043            return Some(
 8044                h_flex()
 8045                    .min_w(min_width)
 8046                    .flex_1()
 8047                    .px_2()
 8048                    .py_1()
 8049                    .gap_3()
 8050                    .elevation_2(cx)
 8051                    .hover(|style| style.bg(cx.theme().colors().element_hover))
 8052                    .id("accept-terms")
 8053                    .cursor_pointer()
 8054                    .on_mouse_down(MouseButton::Left, |_, window, _| window.prevent_default())
 8055                    .on_click(cx.listener(|this, _event, window, cx| {
 8056                        cx.stop_propagation();
 8057                        this.report_editor_event("Edit Prediction Provider ToS Clicked", None, cx);
 8058                        window.dispatch_action(
 8059                            zed_actions::OpenZedPredictOnboarding.boxed_clone(),
 8060                            cx,
 8061                        );
 8062                    }))
 8063                    .child(
 8064                        h_flex()
 8065                            .flex_1()
 8066                            .gap_2()
 8067                            .child(Icon::new(IconName::ZedPredict))
 8068                            .child(Label::new("Accept Terms of Service"))
 8069                            .child(div().w_full())
 8070                            .child(
 8071                                Icon::new(IconName::ArrowUpRight)
 8072                                    .color(Color::Muted)
 8073                                    .size(IconSize::Small),
 8074                            )
 8075                            .into_any_element(),
 8076                    )
 8077                    .into_any(),
 8078            );
 8079        }
 8080
 8081        let is_refreshing = provider.provider.is_refreshing(cx);
 8082
 8083        fn pending_completion_container() -> Div {
 8084            h_flex()
 8085                .h_full()
 8086                .flex_1()
 8087                .gap_2()
 8088                .child(Icon::new(IconName::ZedPredict))
 8089        }
 8090
 8091        let completion = match &self.active_inline_completion {
 8092            Some(prediction) => {
 8093                if !self.has_visible_completions_menu() {
 8094                    const RADIUS: Pixels = px(6.);
 8095                    const BORDER_WIDTH: Pixels = px(1.);
 8096
 8097                    return Some(
 8098                        h_flex()
 8099                            .elevation_2(cx)
 8100                            .border(BORDER_WIDTH)
 8101                            .border_color(cx.theme().colors().border)
 8102                            .when(accept_keystroke.is_none(), |el| {
 8103                                el.border_color(cx.theme().status().error)
 8104                            })
 8105                            .rounded(RADIUS)
 8106                            .rounded_tl(px(0.))
 8107                            .overflow_hidden()
 8108                            .child(div().px_1p5().child(match &prediction.completion {
 8109                                InlineCompletion::Move { target, snapshot } => {
 8110                                    use text::ToPoint as _;
 8111                                    if target.text_anchor.to_point(&snapshot).row > cursor_point.row
 8112                                    {
 8113                                        Icon::new(IconName::ZedPredictDown)
 8114                                    } else {
 8115                                        Icon::new(IconName::ZedPredictUp)
 8116                                    }
 8117                                }
 8118                                InlineCompletion::Edit { .. } => Icon::new(IconName::ZedPredict),
 8119                            }))
 8120                            .child(
 8121                                h_flex()
 8122                                    .gap_1()
 8123                                    .py_1()
 8124                                    .px_2()
 8125                                    .rounded_r(RADIUS - BORDER_WIDTH)
 8126                                    .border_l_1()
 8127                                    .border_color(cx.theme().colors().border)
 8128                                    .bg(Self::edit_prediction_line_popover_bg_color(cx))
 8129                                    .when(self.edit_prediction_preview.released_too_fast(), |el| {
 8130                                        el.child(
 8131                                            Label::new("Hold")
 8132                                                .size(LabelSize::Small)
 8133                                                .when(accept_keystroke.is_none(), |el| {
 8134                                                    el.strikethrough()
 8135                                                })
 8136                                                .line_height_style(LineHeightStyle::UiLabel),
 8137                                        )
 8138                                    })
 8139                                    .id("edit_prediction_cursor_popover_keybind")
 8140                                    .when(accept_keystroke.is_none(), |el| {
 8141                                        let status_colors = cx.theme().status();
 8142
 8143                                        el.bg(status_colors.error_background)
 8144                                            .border_color(status_colors.error.opacity(0.6))
 8145                                            .child(Icon::new(IconName::Info).color(Color::Error))
 8146                                            .cursor_default()
 8147                                            .hoverable_tooltip(move |_window, cx| {
 8148                                                cx.new(|_| MissingEditPredictionKeybindingTooltip)
 8149                                                    .into()
 8150                                            })
 8151                                    })
 8152                                    .when_some(
 8153                                        accept_keystroke.as_ref(),
 8154                                        |el, accept_keystroke| {
 8155                                            el.child(h_flex().children(ui::render_modifiers(
 8156                                                &accept_keystroke.modifiers,
 8157                                                PlatformStyle::platform(),
 8158                                                Some(Color::Default),
 8159                                                Some(IconSize::XSmall.rems().into()),
 8160                                                false,
 8161                                            )))
 8162                                        },
 8163                                    ),
 8164                            )
 8165                            .into_any(),
 8166                    );
 8167                }
 8168
 8169                self.render_edit_prediction_cursor_popover_preview(
 8170                    prediction,
 8171                    cursor_point,
 8172                    style,
 8173                    cx,
 8174                )?
 8175            }
 8176
 8177            None if is_refreshing => match &self.stale_inline_completion_in_menu {
 8178                Some(stale_completion) => self.render_edit_prediction_cursor_popover_preview(
 8179                    stale_completion,
 8180                    cursor_point,
 8181                    style,
 8182                    cx,
 8183                )?,
 8184
 8185                None => {
 8186                    pending_completion_container().child(Label::new("...").size(LabelSize::Small))
 8187                }
 8188            },
 8189
 8190            None => pending_completion_container().child(Label::new("No Prediction")),
 8191        };
 8192
 8193        let completion = if is_refreshing {
 8194            completion
 8195                .with_animation(
 8196                    "loading-completion",
 8197                    Animation::new(Duration::from_secs(2))
 8198                        .repeat()
 8199                        .with_easing(pulsating_between(0.4, 0.8)),
 8200                    |label, delta| label.opacity(delta),
 8201                )
 8202                .into_any_element()
 8203        } else {
 8204            completion.into_any_element()
 8205        };
 8206
 8207        let has_completion = self.active_inline_completion.is_some();
 8208
 8209        let is_platform_style_mac = PlatformStyle::platform() == PlatformStyle::Mac;
 8210        Some(
 8211            h_flex()
 8212                .min_w(min_width)
 8213                .max_w(max_width)
 8214                .flex_1()
 8215                .elevation_2(cx)
 8216                .border_color(cx.theme().colors().border)
 8217                .child(
 8218                    div()
 8219                        .flex_1()
 8220                        .py_1()
 8221                        .px_2()
 8222                        .overflow_hidden()
 8223                        .child(completion),
 8224                )
 8225                .when_some(accept_keystroke, |el, accept_keystroke| {
 8226                    if !accept_keystroke.modifiers.modified() {
 8227                        return el;
 8228                    }
 8229
 8230                    el.child(
 8231                        h_flex()
 8232                            .h_full()
 8233                            .border_l_1()
 8234                            .rounded_r_lg()
 8235                            .border_color(cx.theme().colors().border)
 8236                            .bg(Self::edit_prediction_line_popover_bg_color(cx))
 8237                            .gap_1()
 8238                            .py_1()
 8239                            .px_2()
 8240                            .child(
 8241                                h_flex()
 8242                                    .font(theme::ThemeSettings::get_global(cx).buffer_font.clone())
 8243                                    .when(is_platform_style_mac, |parent| parent.gap_1())
 8244                                    .child(h_flex().children(ui::render_modifiers(
 8245                                        &accept_keystroke.modifiers,
 8246                                        PlatformStyle::platform(),
 8247                                        Some(if !has_completion {
 8248                                            Color::Muted
 8249                                        } else {
 8250                                            Color::Default
 8251                                        }),
 8252                                        None,
 8253                                        false,
 8254                                    ))),
 8255                            )
 8256                            .child(Label::new("Preview").into_any_element())
 8257                            .opacity(if has_completion { 1.0 } else { 0.4 }),
 8258                    )
 8259                })
 8260                .into_any(),
 8261        )
 8262    }
 8263
 8264    fn render_edit_prediction_cursor_popover_preview(
 8265        &self,
 8266        completion: &InlineCompletionState,
 8267        cursor_point: Point,
 8268        style: &EditorStyle,
 8269        cx: &mut Context<Editor>,
 8270    ) -> Option<Div> {
 8271        use text::ToPoint as _;
 8272
 8273        fn render_relative_row_jump(
 8274            prefix: impl Into<String>,
 8275            current_row: u32,
 8276            target_row: u32,
 8277        ) -> Div {
 8278            let (row_diff, arrow) = if target_row < current_row {
 8279                (current_row - target_row, IconName::ArrowUp)
 8280            } else {
 8281                (target_row - current_row, IconName::ArrowDown)
 8282            };
 8283
 8284            h_flex()
 8285                .child(
 8286                    Label::new(format!("{}{}", prefix.into(), row_diff))
 8287                        .color(Color::Muted)
 8288                        .size(LabelSize::Small),
 8289                )
 8290                .child(Icon::new(arrow).color(Color::Muted).size(IconSize::Small))
 8291        }
 8292
 8293        match &completion.completion {
 8294            InlineCompletion::Move {
 8295                target, snapshot, ..
 8296            } => Some(
 8297                h_flex()
 8298                    .px_2()
 8299                    .gap_2()
 8300                    .flex_1()
 8301                    .child(
 8302                        if target.text_anchor.to_point(&snapshot).row > cursor_point.row {
 8303                            Icon::new(IconName::ZedPredictDown)
 8304                        } else {
 8305                            Icon::new(IconName::ZedPredictUp)
 8306                        },
 8307                    )
 8308                    .child(Label::new("Jump to Edit")),
 8309            ),
 8310
 8311            InlineCompletion::Edit {
 8312                edits,
 8313                edit_preview,
 8314                snapshot,
 8315                display_mode: _,
 8316            } => {
 8317                let first_edit_row = edits.first()?.0.start.text_anchor.to_point(&snapshot).row;
 8318
 8319                let (highlighted_edits, has_more_lines) = crate::inline_completion_edit_text(
 8320                    &snapshot,
 8321                    &edits,
 8322                    edit_preview.as_ref()?,
 8323                    true,
 8324                    cx,
 8325                )
 8326                .first_line_preview();
 8327
 8328                let styled_text = gpui::StyledText::new(highlighted_edits.text)
 8329                    .with_default_highlights(&style.text, highlighted_edits.highlights);
 8330
 8331                let preview = h_flex()
 8332                    .gap_1()
 8333                    .min_w_16()
 8334                    .child(styled_text)
 8335                    .when(has_more_lines, |parent| parent.child(""));
 8336
 8337                let left = if first_edit_row != cursor_point.row {
 8338                    render_relative_row_jump("", cursor_point.row, first_edit_row)
 8339                        .into_any_element()
 8340                } else {
 8341                    Icon::new(IconName::ZedPredict).into_any_element()
 8342                };
 8343
 8344                Some(
 8345                    h_flex()
 8346                        .h_full()
 8347                        .flex_1()
 8348                        .gap_2()
 8349                        .pr_1()
 8350                        .overflow_x_hidden()
 8351                        .font(theme::ThemeSettings::get_global(cx).buffer_font.clone())
 8352                        .child(left)
 8353                        .child(preview),
 8354                )
 8355            }
 8356        }
 8357    }
 8358
 8359    fn render_context_menu(
 8360        &self,
 8361        style: &EditorStyle,
 8362        max_height_in_lines: u32,
 8363        window: &mut Window,
 8364        cx: &mut Context<Editor>,
 8365    ) -> Option<AnyElement> {
 8366        let menu = self.context_menu.borrow();
 8367        let menu = menu.as_ref()?;
 8368        if !menu.visible() {
 8369            return None;
 8370        };
 8371        Some(menu.render(style, max_height_in_lines, window, cx))
 8372    }
 8373
 8374    fn render_context_menu_aside(
 8375        &mut self,
 8376        max_size: Size<Pixels>,
 8377        window: &mut Window,
 8378        cx: &mut Context<Editor>,
 8379    ) -> Option<AnyElement> {
 8380        self.context_menu.borrow_mut().as_mut().and_then(|menu| {
 8381            if menu.visible() {
 8382                menu.render_aside(self, max_size, window, cx)
 8383            } else {
 8384                None
 8385            }
 8386        })
 8387    }
 8388
 8389    fn hide_context_menu(
 8390        &mut self,
 8391        window: &mut Window,
 8392        cx: &mut Context<Self>,
 8393    ) -> Option<CodeContextMenu> {
 8394        cx.notify();
 8395        self.completion_tasks.clear();
 8396        let context_menu = self.context_menu.borrow_mut().take();
 8397        self.stale_inline_completion_in_menu.take();
 8398        self.update_visible_inline_completion(window, cx);
 8399        context_menu
 8400    }
 8401
 8402    fn show_snippet_choices(
 8403        &mut self,
 8404        choices: &Vec<String>,
 8405        selection: Range<Anchor>,
 8406        cx: &mut Context<Self>,
 8407    ) {
 8408        if selection.start.buffer_id.is_none() {
 8409            return;
 8410        }
 8411        let buffer_id = selection.start.buffer_id.unwrap();
 8412        let buffer = self.buffer().read(cx).buffer(buffer_id);
 8413        let id = post_inc(&mut self.next_completion_id);
 8414        let snippet_sort_order = EditorSettings::get_global(cx).snippet_sort_order;
 8415
 8416        if let Some(buffer) = buffer {
 8417            *self.context_menu.borrow_mut() = Some(CodeContextMenu::Completions(
 8418                CompletionsMenu::new_snippet_choices(
 8419                    id,
 8420                    true,
 8421                    choices,
 8422                    selection,
 8423                    buffer,
 8424                    snippet_sort_order,
 8425                ),
 8426            ));
 8427        }
 8428    }
 8429
 8430    pub fn insert_snippet(
 8431        &mut self,
 8432        insertion_ranges: &[Range<usize>],
 8433        snippet: Snippet,
 8434        window: &mut Window,
 8435        cx: &mut Context<Self>,
 8436    ) -> Result<()> {
 8437        struct Tabstop<T> {
 8438            is_end_tabstop: bool,
 8439            ranges: Vec<Range<T>>,
 8440            choices: Option<Vec<String>>,
 8441        }
 8442
 8443        let tabstops = self.buffer.update(cx, |buffer, cx| {
 8444            let snippet_text: Arc<str> = snippet.text.clone().into();
 8445            let edits = insertion_ranges
 8446                .iter()
 8447                .cloned()
 8448                .map(|range| (range, snippet_text.clone()));
 8449            buffer.edit(edits, Some(AutoindentMode::EachLine), cx);
 8450
 8451            let snapshot = &*buffer.read(cx);
 8452            let snippet = &snippet;
 8453            snippet
 8454                .tabstops
 8455                .iter()
 8456                .map(|tabstop| {
 8457                    let is_end_tabstop = tabstop.ranges.first().map_or(false, |tabstop| {
 8458                        tabstop.is_empty() && tabstop.start == snippet.text.len() as isize
 8459                    });
 8460                    let mut tabstop_ranges = tabstop
 8461                        .ranges
 8462                        .iter()
 8463                        .flat_map(|tabstop_range| {
 8464                            let mut delta = 0_isize;
 8465                            insertion_ranges.iter().map(move |insertion_range| {
 8466                                let insertion_start = insertion_range.start as isize + delta;
 8467                                delta +=
 8468                                    snippet.text.len() as isize - insertion_range.len() as isize;
 8469
 8470                                let start = ((insertion_start + tabstop_range.start) as usize)
 8471                                    .min(snapshot.len());
 8472                                let end = ((insertion_start + tabstop_range.end) as usize)
 8473                                    .min(snapshot.len());
 8474                                snapshot.anchor_before(start)..snapshot.anchor_after(end)
 8475                            })
 8476                        })
 8477                        .collect::<Vec<_>>();
 8478                    tabstop_ranges.sort_unstable_by(|a, b| a.start.cmp(&b.start, snapshot));
 8479
 8480                    Tabstop {
 8481                        is_end_tabstop,
 8482                        ranges: tabstop_ranges,
 8483                        choices: tabstop.choices.clone(),
 8484                    }
 8485                })
 8486                .collect::<Vec<_>>()
 8487        });
 8488        if let Some(tabstop) = tabstops.first() {
 8489            self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8490                s.select_ranges(tabstop.ranges.iter().cloned());
 8491            });
 8492
 8493            if let Some(choices) = &tabstop.choices {
 8494                if let Some(selection) = tabstop.ranges.first() {
 8495                    self.show_snippet_choices(choices, selection.clone(), cx)
 8496                }
 8497            }
 8498
 8499            // If we're already at the last tabstop and it's at the end of the snippet,
 8500            // we're done, we don't need to keep the state around.
 8501            if !tabstop.is_end_tabstop {
 8502                let choices = tabstops
 8503                    .iter()
 8504                    .map(|tabstop| tabstop.choices.clone())
 8505                    .collect();
 8506
 8507                let ranges = tabstops
 8508                    .into_iter()
 8509                    .map(|tabstop| tabstop.ranges)
 8510                    .collect::<Vec<_>>();
 8511
 8512                self.snippet_stack.push(SnippetState {
 8513                    active_index: 0,
 8514                    ranges,
 8515                    choices,
 8516                });
 8517            }
 8518
 8519            // Check whether the just-entered snippet ends with an auto-closable bracket.
 8520            if self.autoclose_regions.is_empty() {
 8521                let snapshot = self.buffer.read(cx).snapshot(cx);
 8522                for selection in &mut self.selections.all::<Point>(cx) {
 8523                    let selection_head = selection.head();
 8524                    let Some(scope) = snapshot.language_scope_at(selection_head) else {
 8525                        continue;
 8526                    };
 8527
 8528                    let mut bracket_pair = None;
 8529                    let next_chars = snapshot.chars_at(selection_head).collect::<String>();
 8530                    let prev_chars = snapshot
 8531                        .reversed_chars_at(selection_head)
 8532                        .collect::<String>();
 8533                    for (pair, enabled) in scope.brackets() {
 8534                        if enabled
 8535                            && pair.close
 8536                            && prev_chars.starts_with(pair.start.as_str())
 8537                            && next_chars.starts_with(pair.end.as_str())
 8538                        {
 8539                            bracket_pair = Some(pair.clone());
 8540                            break;
 8541                        }
 8542                    }
 8543                    if let Some(pair) = bracket_pair {
 8544                        let snapshot_settings = snapshot.language_settings_at(selection_head, cx);
 8545                        let autoclose_enabled =
 8546                            self.use_autoclose && snapshot_settings.use_autoclose;
 8547                        if autoclose_enabled {
 8548                            let start = snapshot.anchor_after(selection_head);
 8549                            let end = snapshot.anchor_after(selection_head);
 8550                            self.autoclose_regions.push(AutocloseRegion {
 8551                                selection_id: selection.id,
 8552                                range: start..end,
 8553                                pair,
 8554                            });
 8555                        }
 8556                    }
 8557                }
 8558            }
 8559        }
 8560        Ok(())
 8561    }
 8562
 8563    pub fn move_to_next_snippet_tabstop(
 8564        &mut self,
 8565        window: &mut Window,
 8566        cx: &mut Context<Self>,
 8567    ) -> bool {
 8568        self.move_to_snippet_tabstop(Bias::Right, window, cx)
 8569    }
 8570
 8571    pub fn move_to_prev_snippet_tabstop(
 8572        &mut self,
 8573        window: &mut Window,
 8574        cx: &mut Context<Self>,
 8575    ) -> bool {
 8576        self.move_to_snippet_tabstop(Bias::Left, window, cx)
 8577    }
 8578
 8579    pub fn move_to_snippet_tabstop(
 8580        &mut self,
 8581        bias: Bias,
 8582        window: &mut Window,
 8583        cx: &mut Context<Self>,
 8584    ) -> bool {
 8585        if let Some(mut snippet) = self.snippet_stack.pop() {
 8586            match bias {
 8587                Bias::Left => {
 8588                    if snippet.active_index > 0 {
 8589                        snippet.active_index -= 1;
 8590                    } else {
 8591                        self.snippet_stack.push(snippet);
 8592                        return false;
 8593                    }
 8594                }
 8595                Bias::Right => {
 8596                    if snippet.active_index + 1 < snippet.ranges.len() {
 8597                        snippet.active_index += 1;
 8598                    } else {
 8599                        self.snippet_stack.push(snippet);
 8600                        return false;
 8601                    }
 8602                }
 8603            }
 8604            if let Some(current_ranges) = snippet.ranges.get(snippet.active_index) {
 8605                self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8606                    s.select_anchor_ranges(current_ranges.iter().cloned())
 8607                });
 8608
 8609                if let Some(choices) = &snippet.choices[snippet.active_index] {
 8610                    if let Some(selection) = current_ranges.first() {
 8611                        self.show_snippet_choices(&choices, selection.clone(), cx);
 8612                    }
 8613                }
 8614
 8615                // If snippet state is not at the last tabstop, push it back on the stack
 8616                if snippet.active_index + 1 < snippet.ranges.len() {
 8617                    self.snippet_stack.push(snippet);
 8618                }
 8619                return true;
 8620            }
 8621        }
 8622
 8623        false
 8624    }
 8625
 8626    pub fn clear(&mut self, window: &mut Window, cx: &mut Context<Self>) {
 8627        self.transact(window, cx, |this, window, cx| {
 8628            this.select_all(&SelectAll, window, cx);
 8629            this.insert("", window, cx);
 8630        });
 8631    }
 8632
 8633    pub fn backspace(&mut self, _: &Backspace, window: &mut Window, cx: &mut Context<Self>) {
 8634        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
 8635        self.transact(window, cx, |this, window, cx| {
 8636            this.select_autoclose_pair(window, cx);
 8637            let mut linked_ranges = HashMap::<_, Vec<_>>::default();
 8638            if !this.linked_edit_ranges.is_empty() {
 8639                let selections = this.selections.all::<MultiBufferPoint>(cx);
 8640                let snapshot = this.buffer.read(cx).snapshot(cx);
 8641
 8642                for selection in selections.iter() {
 8643                    let selection_start = snapshot.anchor_before(selection.start).text_anchor;
 8644                    let selection_end = snapshot.anchor_after(selection.end).text_anchor;
 8645                    if selection_start.buffer_id != selection_end.buffer_id {
 8646                        continue;
 8647                    }
 8648                    if let Some(ranges) =
 8649                        this.linked_editing_ranges_for(selection_start..selection_end, cx)
 8650                    {
 8651                        for (buffer, entries) in ranges {
 8652                            linked_ranges.entry(buffer).or_default().extend(entries);
 8653                        }
 8654                    }
 8655                }
 8656            }
 8657
 8658            let mut selections = this.selections.all::<MultiBufferPoint>(cx);
 8659            let display_map = this.display_map.update(cx, |map, cx| map.snapshot(cx));
 8660            for selection in &mut selections {
 8661                if selection.is_empty() {
 8662                    let old_head = selection.head();
 8663                    let mut new_head =
 8664                        movement::left(&display_map, old_head.to_display_point(&display_map))
 8665                            .to_point(&display_map);
 8666                    if let Some((buffer, line_buffer_range)) = display_map
 8667                        .buffer_snapshot
 8668                        .buffer_line_for_row(MultiBufferRow(old_head.row))
 8669                    {
 8670                        let indent_size = buffer.indent_size_for_line(line_buffer_range.start.row);
 8671                        let indent_len = match indent_size.kind {
 8672                            IndentKind::Space => {
 8673                                buffer.settings_at(line_buffer_range.start, cx).tab_size
 8674                            }
 8675                            IndentKind::Tab => NonZeroU32::new(1).unwrap(),
 8676                        };
 8677                        if old_head.column <= indent_size.len && old_head.column > 0 {
 8678                            let indent_len = indent_len.get();
 8679                            new_head = cmp::min(
 8680                                new_head,
 8681                                MultiBufferPoint::new(
 8682                                    old_head.row,
 8683                                    ((old_head.column - 1) / indent_len) * indent_len,
 8684                                ),
 8685                            );
 8686                        }
 8687                    }
 8688
 8689                    selection.set_head(new_head, SelectionGoal::None);
 8690                }
 8691            }
 8692
 8693            this.signature_help_state.set_backspace_pressed(true);
 8694            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8695                s.select(selections)
 8696            });
 8697            this.insert("", window, cx);
 8698            let empty_str: Arc<str> = Arc::from("");
 8699            for (buffer, edits) in linked_ranges {
 8700                let snapshot = buffer.read(cx).snapshot();
 8701                use text::ToPoint as TP;
 8702
 8703                let edits = edits
 8704                    .into_iter()
 8705                    .map(|range| {
 8706                        let end_point = TP::to_point(&range.end, &snapshot);
 8707                        let mut start_point = TP::to_point(&range.start, &snapshot);
 8708
 8709                        if end_point == start_point {
 8710                            let offset = text::ToOffset::to_offset(&range.start, &snapshot)
 8711                                .saturating_sub(1);
 8712                            start_point =
 8713                                snapshot.clip_point(TP::to_point(&offset, &snapshot), Bias::Left);
 8714                        };
 8715
 8716                        (start_point..end_point, empty_str.clone())
 8717                    })
 8718                    .sorted_by_key(|(range, _)| range.start)
 8719                    .collect::<Vec<_>>();
 8720                buffer.update(cx, |this, cx| {
 8721                    this.edit(edits, None, cx);
 8722                })
 8723            }
 8724            this.refresh_inline_completion(true, false, window, cx);
 8725            linked_editing_ranges::refresh_linked_ranges(this, window, cx);
 8726        });
 8727    }
 8728
 8729    pub fn delete(&mut self, _: &Delete, window: &mut Window, cx: &mut Context<Self>) {
 8730        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
 8731        self.transact(window, cx, |this, window, cx| {
 8732            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8733                s.move_with(|map, selection| {
 8734                    if selection.is_empty() {
 8735                        let cursor = movement::right(map, selection.head());
 8736                        selection.end = cursor;
 8737                        selection.reversed = true;
 8738                        selection.goal = SelectionGoal::None;
 8739                    }
 8740                })
 8741            });
 8742            this.insert("", window, cx);
 8743            this.refresh_inline_completion(true, false, window, cx);
 8744        });
 8745    }
 8746
 8747    pub fn backtab(&mut self, _: &Backtab, window: &mut Window, cx: &mut Context<Self>) {
 8748        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
 8749        if self.move_to_prev_snippet_tabstop(window, cx) {
 8750            return;
 8751        }
 8752        self.outdent(&Outdent, window, cx);
 8753    }
 8754
 8755    pub fn tab(&mut self, _: &Tab, window: &mut Window, cx: &mut Context<Self>) {
 8756        if self.move_to_next_snippet_tabstop(window, cx) {
 8757            self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
 8758            return;
 8759        }
 8760        if self.read_only(cx) {
 8761            return;
 8762        }
 8763        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
 8764        let mut selections = self.selections.all_adjusted(cx);
 8765        let buffer = self.buffer.read(cx);
 8766        let snapshot = buffer.snapshot(cx);
 8767        let rows_iter = selections.iter().map(|s| s.head().row);
 8768        let suggested_indents = snapshot.suggested_indents(rows_iter, cx);
 8769
 8770        let has_some_cursor_in_whitespace = selections
 8771            .iter()
 8772            .filter(|selection| selection.is_empty())
 8773            .any(|selection| {
 8774                let cursor = selection.head();
 8775                let current_indent = snapshot.indent_size_for_line(MultiBufferRow(cursor.row));
 8776                cursor.column < current_indent.len
 8777            });
 8778
 8779        let mut edits = Vec::new();
 8780        let mut prev_edited_row = 0;
 8781        let mut row_delta = 0;
 8782        for selection in &mut selections {
 8783            if selection.start.row != prev_edited_row {
 8784                row_delta = 0;
 8785            }
 8786            prev_edited_row = selection.end.row;
 8787
 8788            // If the selection is non-empty, then increase the indentation of the selected lines.
 8789            if !selection.is_empty() {
 8790                row_delta =
 8791                    Self::indent_selection(buffer, &snapshot, selection, &mut edits, row_delta, cx);
 8792                continue;
 8793            }
 8794
 8795            let cursor = selection.head();
 8796            let current_indent = snapshot.indent_size_for_line(MultiBufferRow(cursor.row));
 8797            if let Some(suggested_indent) =
 8798                suggested_indents.get(&MultiBufferRow(cursor.row)).copied()
 8799            {
 8800                // Don't do anything if already at suggested indent
 8801                // and there is any other cursor which is not
 8802                if has_some_cursor_in_whitespace
 8803                    && cursor.column == current_indent.len
 8804                    && current_indent.len == suggested_indent.len
 8805                {
 8806                    continue;
 8807                }
 8808
 8809                // Adjust line and move cursor to suggested indent
 8810                // if cursor is not at suggested indent
 8811                if cursor.column < suggested_indent.len
 8812                    && cursor.column <= current_indent.len
 8813                    && current_indent.len <= suggested_indent.len
 8814                {
 8815                    selection.start = Point::new(cursor.row, suggested_indent.len);
 8816                    selection.end = selection.start;
 8817                    if row_delta == 0 {
 8818                        edits.extend(Buffer::edit_for_indent_size_adjustment(
 8819                            cursor.row,
 8820                            current_indent,
 8821                            suggested_indent,
 8822                        ));
 8823                        row_delta = suggested_indent.len - current_indent.len;
 8824                    }
 8825                    continue;
 8826                }
 8827
 8828                // If current indent is more than suggested indent
 8829                // only move cursor to current indent and skip indent
 8830                if cursor.column < current_indent.len && current_indent.len > suggested_indent.len {
 8831                    selection.start = Point::new(cursor.row, current_indent.len);
 8832                    selection.end = selection.start;
 8833                    continue;
 8834                }
 8835            }
 8836
 8837            // Otherwise, insert a hard or soft tab.
 8838            let settings = buffer.language_settings_at(cursor, cx);
 8839            let tab_size = if settings.hard_tabs {
 8840                IndentSize::tab()
 8841            } else {
 8842                let tab_size = settings.tab_size.get();
 8843                let indent_remainder = snapshot
 8844                    .text_for_range(Point::new(cursor.row, 0)..cursor)
 8845                    .flat_map(str::chars)
 8846                    .fold(row_delta % tab_size, |counter: u32, c| {
 8847                        if c == '\t' {
 8848                            0
 8849                        } else {
 8850                            (counter + 1) % tab_size
 8851                        }
 8852                    });
 8853
 8854                let chars_to_next_tab_stop = tab_size - indent_remainder;
 8855                IndentSize::spaces(chars_to_next_tab_stop)
 8856            };
 8857            selection.start = Point::new(cursor.row, cursor.column + row_delta + tab_size.len);
 8858            selection.end = selection.start;
 8859            edits.push((cursor..cursor, tab_size.chars().collect::<String>()));
 8860            row_delta += tab_size.len;
 8861        }
 8862
 8863        self.transact(window, cx, |this, window, cx| {
 8864            this.buffer.update(cx, |b, cx| b.edit(edits, None, cx));
 8865            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8866                s.select(selections)
 8867            });
 8868            this.refresh_inline_completion(true, false, window, cx);
 8869        });
 8870    }
 8871
 8872    pub fn indent(&mut self, _: &Indent, window: &mut Window, cx: &mut Context<Self>) {
 8873        if self.read_only(cx) {
 8874            return;
 8875        }
 8876        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
 8877        let mut selections = self.selections.all::<Point>(cx);
 8878        let mut prev_edited_row = 0;
 8879        let mut row_delta = 0;
 8880        let mut edits = Vec::new();
 8881        let buffer = self.buffer.read(cx);
 8882        let snapshot = buffer.snapshot(cx);
 8883        for selection in &mut selections {
 8884            if selection.start.row != prev_edited_row {
 8885                row_delta = 0;
 8886            }
 8887            prev_edited_row = selection.end.row;
 8888
 8889            row_delta =
 8890                Self::indent_selection(buffer, &snapshot, selection, &mut edits, row_delta, cx);
 8891        }
 8892
 8893        self.transact(window, cx, |this, window, cx| {
 8894            this.buffer.update(cx, |b, cx| b.edit(edits, None, cx));
 8895            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8896                s.select(selections)
 8897            });
 8898        });
 8899    }
 8900
 8901    fn indent_selection(
 8902        buffer: &MultiBuffer,
 8903        snapshot: &MultiBufferSnapshot,
 8904        selection: &mut Selection<Point>,
 8905        edits: &mut Vec<(Range<Point>, String)>,
 8906        delta_for_start_row: u32,
 8907        cx: &App,
 8908    ) -> u32 {
 8909        let settings = buffer.language_settings_at(selection.start, cx);
 8910        let tab_size = settings.tab_size.get();
 8911        let indent_kind = if settings.hard_tabs {
 8912            IndentKind::Tab
 8913        } else {
 8914            IndentKind::Space
 8915        };
 8916        let mut start_row = selection.start.row;
 8917        let mut end_row = selection.end.row + 1;
 8918
 8919        // If a selection ends at the beginning of a line, don't indent
 8920        // that last line.
 8921        if selection.end.column == 0 && selection.end.row > selection.start.row {
 8922            end_row -= 1;
 8923        }
 8924
 8925        // Avoid re-indenting a row that has already been indented by a
 8926        // previous selection, but still update this selection's column
 8927        // to reflect that indentation.
 8928        if delta_for_start_row > 0 {
 8929            start_row += 1;
 8930            selection.start.column += delta_for_start_row;
 8931            if selection.end.row == selection.start.row {
 8932                selection.end.column += delta_for_start_row;
 8933            }
 8934        }
 8935
 8936        let mut delta_for_end_row = 0;
 8937        let has_multiple_rows = start_row + 1 != end_row;
 8938        for row in start_row..end_row {
 8939            let current_indent = snapshot.indent_size_for_line(MultiBufferRow(row));
 8940            let indent_delta = match (current_indent.kind, indent_kind) {
 8941                (IndentKind::Space, IndentKind::Space) => {
 8942                    let columns_to_next_tab_stop = tab_size - (current_indent.len % tab_size);
 8943                    IndentSize::spaces(columns_to_next_tab_stop)
 8944                }
 8945                (IndentKind::Tab, IndentKind::Space) => IndentSize::spaces(tab_size),
 8946                (_, IndentKind::Tab) => IndentSize::tab(),
 8947            };
 8948
 8949            let start = if has_multiple_rows || current_indent.len < selection.start.column {
 8950                0
 8951            } else {
 8952                selection.start.column
 8953            };
 8954            let row_start = Point::new(row, start);
 8955            edits.push((
 8956                row_start..row_start,
 8957                indent_delta.chars().collect::<String>(),
 8958            ));
 8959
 8960            // Update this selection's endpoints to reflect the indentation.
 8961            if row == selection.start.row {
 8962                selection.start.column += indent_delta.len;
 8963            }
 8964            if row == selection.end.row {
 8965                selection.end.column += indent_delta.len;
 8966                delta_for_end_row = indent_delta.len;
 8967            }
 8968        }
 8969
 8970        if selection.start.row == selection.end.row {
 8971            delta_for_start_row + delta_for_end_row
 8972        } else {
 8973            delta_for_end_row
 8974        }
 8975    }
 8976
 8977    pub fn outdent(&mut self, _: &Outdent, window: &mut Window, cx: &mut Context<Self>) {
 8978        if self.read_only(cx) {
 8979            return;
 8980        }
 8981        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
 8982        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 8983        let selections = self.selections.all::<Point>(cx);
 8984        let mut deletion_ranges = Vec::new();
 8985        let mut last_outdent = None;
 8986        {
 8987            let buffer = self.buffer.read(cx);
 8988            let snapshot = buffer.snapshot(cx);
 8989            for selection in &selections {
 8990                let settings = buffer.language_settings_at(selection.start, cx);
 8991                let tab_size = settings.tab_size.get();
 8992                let mut rows = selection.spanned_rows(false, &display_map);
 8993
 8994                // Avoid re-outdenting a row that has already been outdented by a
 8995                // previous selection.
 8996                if let Some(last_row) = last_outdent {
 8997                    if last_row == rows.start {
 8998                        rows.start = rows.start.next_row();
 8999                    }
 9000                }
 9001                let has_multiple_rows = rows.len() > 1;
 9002                for row in rows.iter_rows() {
 9003                    let indent_size = snapshot.indent_size_for_line(row);
 9004                    if indent_size.len > 0 {
 9005                        let deletion_len = match indent_size.kind {
 9006                            IndentKind::Space => {
 9007                                let columns_to_prev_tab_stop = indent_size.len % tab_size;
 9008                                if columns_to_prev_tab_stop == 0 {
 9009                                    tab_size
 9010                                } else {
 9011                                    columns_to_prev_tab_stop
 9012                                }
 9013                            }
 9014                            IndentKind::Tab => 1,
 9015                        };
 9016                        let start = if has_multiple_rows
 9017                            || deletion_len > selection.start.column
 9018                            || indent_size.len < selection.start.column
 9019                        {
 9020                            0
 9021                        } else {
 9022                            selection.start.column - deletion_len
 9023                        };
 9024                        deletion_ranges.push(
 9025                            Point::new(row.0, start)..Point::new(row.0, start + deletion_len),
 9026                        );
 9027                        last_outdent = Some(row);
 9028                    }
 9029                }
 9030            }
 9031        }
 9032
 9033        self.transact(window, cx, |this, window, cx| {
 9034            this.buffer.update(cx, |buffer, cx| {
 9035                let empty_str: Arc<str> = Arc::default();
 9036                buffer.edit(
 9037                    deletion_ranges
 9038                        .into_iter()
 9039                        .map(|range| (range, empty_str.clone())),
 9040                    None,
 9041                    cx,
 9042                );
 9043            });
 9044            let selections = this.selections.all::<usize>(cx);
 9045            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9046                s.select(selections)
 9047            });
 9048        });
 9049    }
 9050
 9051    pub fn autoindent(&mut self, _: &AutoIndent, window: &mut Window, cx: &mut Context<Self>) {
 9052        if self.read_only(cx) {
 9053            return;
 9054        }
 9055        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
 9056        let selections = self
 9057            .selections
 9058            .all::<usize>(cx)
 9059            .into_iter()
 9060            .map(|s| s.range());
 9061
 9062        self.transact(window, cx, |this, window, cx| {
 9063            this.buffer.update(cx, |buffer, cx| {
 9064                buffer.autoindent_ranges(selections, cx);
 9065            });
 9066            let selections = this.selections.all::<usize>(cx);
 9067            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9068                s.select(selections)
 9069            });
 9070        });
 9071    }
 9072
 9073    pub fn delete_line(&mut self, _: &DeleteLine, window: &mut Window, cx: &mut Context<Self>) {
 9074        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
 9075        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 9076        let selections = self.selections.all::<Point>(cx);
 9077
 9078        let mut new_cursors = Vec::new();
 9079        let mut edit_ranges = Vec::new();
 9080        let mut selections = selections.iter().peekable();
 9081        while let Some(selection) = selections.next() {
 9082            let mut rows = selection.spanned_rows(false, &display_map);
 9083            let goal_display_column = selection.head().to_display_point(&display_map).column();
 9084
 9085            // Accumulate contiguous regions of rows that we want to delete.
 9086            while let Some(next_selection) = selections.peek() {
 9087                let next_rows = next_selection.spanned_rows(false, &display_map);
 9088                if next_rows.start <= rows.end {
 9089                    rows.end = next_rows.end;
 9090                    selections.next().unwrap();
 9091                } else {
 9092                    break;
 9093                }
 9094            }
 9095
 9096            let buffer = &display_map.buffer_snapshot;
 9097            let mut edit_start = Point::new(rows.start.0, 0).to_offset(buffer);
 9098            let edit_end;
 9099            let cursor_buffer_row;
 9100            if buffer.max_point().row >= rows.end.0 {
 9101                // If there's a line after the range, delete the \n from the end of the row range
 9102                // and position the cursor on the next line.
 9103                edit_end = Point::new(rows.end.0, 0).to_offset(buffer);
 9104                cursor_buffer_row = rows.end;
 9105            } else {
 9106                // If there isn't a line after the range, delete the \n from the line before the
 9107                // start of the row range and position the cursor there.
 9108                edit_start = edit_start.saturating_sub(1);
 9109                edit_end = buffer.len();
 9110                cursor_buffer_row = rows.start.previous_row();
 9111            }
 9112
 9113            let mut cursor = Point::new(cursor_buffer_row.0, 0).to_display_point(&display_map);
 9114            *cursor.column_mut() =
 9115                cmp::min(goal_display_column, display_map.line_len(cursor.row()));
 9116
 9117            new_cursors.push((
 9118                selection.id,
 9119                buffer.anchor_after(cursor.to_point(&display_map)),
 9120            ));
 9121            edit_ranges.push(edit_start..edit_end);
 9122        }
 9123
 9124        self.transact(window, cx, |this, window, cx| {
 9125            let buffer = this.buffer.update(cx, |buffer, cx| {
 9126                let empty_str: Arc<str> = Arc::default();
 9127                buffer.edit(
 9128                    edit_ranges
 9129                        .into_iter()
 9130                        .map(|range| (range, empty_str.clone())),
 9131                    None,
 9132                    cx,
 9133                );
 9134                buffer.snapshot(cx)
 9135            });
 9136            let new_selections = new_cursors
 9137                .into_iter()
 9138                .map(|(id, cursor)| {
 9139                    let cursor = cursor.to_point(&buffer);
 9140                    Selection {
 9141                        id,
 9142                        start: cursor,
 9143                        end: cursor,
 9144                        reversed: false,
 9145                        goal: SelectionGoal::None,
 9146                    }
 9147                })
 9148                .collect();
 9149
 9150            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9151                s.select(new_selections);
 9152            });
 9153        });
 9154    }
 9155
 9156    pub fn join_lines_impl(
 9157        &mut self,
 9158        insert_whitespace: bool,
 9159        window: &mut Window,
 9160        cx: &mut Context<Self>,
 9161    ) {
 9162        if self.read_only(cx) {
 9163            return;
 9164        }
 9165        let mut row_ranges = Vec::<Range<MultiBufferRow>>::new();
 9166        for selection in self.selections.all::<Point>(cx) {
 9167            let start = MultiBufferRow(selection.start.row);
 9168            // Treat single line selections as if they include the next line. Otherwise this action
 9169            // would do nothing for single line selections individual cursors.
 9170            let end = if selection.start.row == selection.end.row {
 9171                MultiBufferRow(selection.start.row + 1)
 9172            } else {
 9173                MultiBufferRow(selection.end.row)
 9174            };
 9175
 9176            if let Some(last_row_range) = row_ranges.last_mut() {
 9177                if start <= last_row_range.end {
 9178                    last_row_range.end = end;
 9179                    continue;
 9180                }
 9181            }
 9182            row_ranges.push(start..end);
 9183        }
 9184
 9185        let snapshot = self.buffer.read(cx).snapshot(cx);
 9186        let mut cursor_positions = Vec::new();
 9187        for row_range in &row_ranges {
 9188            let anchor = snapshot.anchor_before(Point::new(
 9189                row_range.end.previous_row().0,
 9190                snapshot.line_len(row_range.end.previous_row()),
 9191            ));
 9192            cursor_positions.push(anchor..anchor);
 9193        }
 9194
 9195        self.transact(window, cx, |this, window, cx| {
 9196            for row_range in row_ranges.into_iter().rev() {
 9197                for row in row_range.iter_rows().rev() {
 9198                    let end_of_line = Point::new(row.0, snapshot.line_len(row));
 9199                    let next_line_row = row.next_row();
 9200                    let indent = snapshot.indent_size_for_line(next_line_row);
 9201                    let start_of_next_line = Point::new(next_line_row.0, indent.len);
 9202
 9203                    let replace =
 9204                        if snapshot.line_len(next_line_row) > indent.len && insert_whitespace {
 9205                            " "
 9206                        } else {
 9207                            ""
 9208                        };
 9209
 9210                    this.buffer.update(cx, |buffer, cx| {
 9211                        buffer.edit([(end_of_line..start_of_next_line, replace)], None, cx)
 9212                    });
 9213                }
 9214            }
 9215
 9216            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9217                s.select_anchor_ranges(cursor_positions)
 9218            });
 9219        });
 9220    }
 9221
 9222    pub fn join_lines(&mut self, _: &JoinLines, window: &mut Window, cx: &mut Context<Self>) {
 9223        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
 9224        self.join_lines_impl(true, window, cx);
 9225    }
 9226
 9227    pub fn sort_lines_case_sensitive(
 9228        &mut self,
 9229        _: &SortLinesCaseSensitive,
 9230        window: &mut Window,
 9231        cx: &mut Context<Self>,
 9232    ) {
 9233        self.manipulate_lines(window, cx, |lines| lines.sort())
 9234    }
 9235
 9236    pub fn sort_lines_case_insensitive(
 9237        &mut self,
 9238        _: &SortLinesCaseInsensitive,
 9239        window: &mut Window,
 9240        cx: &mut Context<Self>,
 9241    ) {
 9242        self.manipulate_lines(window, cx, |lines| {
 9243            lines.sort_by_key(|line| line.to_lowercase())
 9244        })
 9245    }
 9246
 9247    pub fn unique_lines_case_insensitive(
 9248        &mut self,
 9249        _: &UniqueLinesCaseInsensitive,
 9250        window: &mut Window,
 9251        cx: &mut Context<Self>,
 9252    ) {
 9253        self.manipulate_lines(window, cx, |lines| {
 9254            let mut seen = HashSet::default();
 9255            lines.retain(|line| seen.insert(line.to_lowercase()));
 9256        })
 9257    }
 9258
 9259    pub fn unique_lines_case_sensitive(
 9260        &mut self,
 9261        _: &UniqueLinesCaseSensitive,
 9262        window: &mut Window,
 9263        cx: &mut Context<Self>,
 9264    ) {
 9265        self.manipulate_lines(window, cx, |lines| {
 9266            let mut seen = HashSet::default();
 9267            lines.retain(|line| seen.insert(*line));
 9268        })
 9269    }
 9270
 9271    pub fn reload_file(&mut self, _: &ReloadFile, window: &mut Window, cx: &mut Context<Self>) {
 9272        let Some(project) = self.project.clone() else {
 9273            return;
 9274        };
 9275        self.reload(project, window, cx)
 9276            .detach_and_notify_err(window, cx);
 9277    }
 9278
 9279    pub fn restore_file(
 9280        &mut self,
 9281        _: &::git::RestoreFile,
 9282        window: &mut Window,
 9283        cx: &mut Context<Self>,
 9284    ) {
 9285        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
 9286        let mut buffer_ids = HashSet::default();
 9287        let snapshot = self.buffer().read(cx).snapshot(cx);
 9288        for selection in self.selections.all::<usize>(cx) {
 9289            buffer_ids.extend(snapshot.buffer_ids_for_range(selection.range()))
 9290        }
 9291
 9292        let buffer = self.buffer().read(cx);
 9293        let ranges = buffer_ids
 9294            .into_iter()
 9295            .flat_map(|buffer_id| buffer.excerpt_ranges_for_buffer(buffer_id, cx))
 9296            .collect::<Vec<_>>();
 9297
 9298        self.restore_hunks_in_ranges(ranges, window, cx);
 9299    }
 9300
 9301    pub fn git_restore(&mut self, _: &Restore, window: &mut Window, cx: &mut Context<Self>) {
 9302        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
 9303        let selections = self
 9304            .selections
 9305            .all(cx)
 9306            .into_iter()
 9307            .map(|s| s.range())
 9308            .collect();
 9309        self.restore_hunks_in_ranges(selections, window, cx);
 9310    }
 9311
 9312    pub fn restore_hunks_in_ranges(
 9313        &mut self,
 9314        ranges: Vec<Range<Point>>,
 9315        window: &mut Window,
 9316        cx: &mut Context<Editor>,
 9317    ) {
 9318        let mut revert_changes = HashMap::default();
 9319        let chunk_by = self
 9320            .snapshot(window, cx)
 9321            .hunks_for_ranges(ranges)
 9322            .into_iter()
 9323            .chunk_by(|hunk| hunk.buffer_id);
 9324        for (buffer_id, hunks) in &chunk_by {
 9325            let hunks = hunks.collect::<Vec<_>>();
 9326            for hunk in &hunks {
 9327                self.prepare_restore_change(&mut revert_changes, hunk, cx);
 9328            }
 9329            self.do_stage_or_unstage(false, buffer_id, hunks.into_iter(), cx);
 9330        }
 9331        drop(chunk_by);
 9332        if !revert_changes.is_empty() {
 9333            self.transact(window, cx, |editor, window, cx| {
 9334                editor.restore(revert_changes, window, cx);
 9335            });
 9336        }
 9337    }
 9338
 9339    pub fn open_active_item_in_terminal(
 9340        &mut self,
 9341        _: &OpenInTerminal,
 9342        window: &mut Window,
 9343        cx: &mut Context<Self>,
 9344    ) {
 9345        if let Some(working_directory) = self.active_excerpt(cx).and_then(|(_, buffer, _)| {
 9346            let project_path = buffer.read(cx).project_path(cx)?;
 9347            let project = self.project.as_ref()?.read(cx);
 9348            let entry = project.entry_for_path(&project_path, cx)?;
 9349            let parent = match &entry.canonical_path {
 9350                Some(canonical_path) => canonical_path.to_path_buf(),
 9351                None => project.absolute_path(&project_path, cx)?,
 9352            }
 9353            .parent()?
 9354            .to_path_buf();
 9355            Some(parent)
 9356        }) {
 9357            window.dispatch_action(OpenTerminal { working_directory }.boxed_clone(), cx);
 9358        }
 9359    }
 9360
 9361    fn set_breakpoint_context_menu(
 9362        &mut self,
 9363        display_row: DisplayRow,
 9364        position: Option<Anchor>,
 9365        clicked_point: gpui::Point<Pixels>,
 9366        window: &mut Window,
 9367        cx: &mut Context<Self>,
 9368    ) {
 9369        if !cx.has_flag::<DebuggerFeatureFlag>() {
 9370            return;
 9371        }
 9372        let source = self
 9373            .buffer
 9374            .read(cx)
 9375            .snapshot(cx)
 9376            .anchor_before(Point::new(display_row.0, 0u32));
 9377
 9378        let context_menu = self.breakpoint_context_menu(position.unwrap_or(source), window, cx);
 9379
 9380        self.mouse_context_menu = MouseContextMenu::pinned_to_editor(
 9381            self,
 9382            source,
 9383            clicked_point,
 9384            context_menu,
 9385            window,
 9386            cx,
 9387        );
 9388    }
 9389
 9390    fn add_edit_breakpoint_block(
 9391        &mut self,
 9392        anchor: Anchor,
 9393        breakpoint: &Breakpoint,
 9394        edit_action: BreakpointPromptEditAction,
 9395        window: &mut Window,
 9396        cx: &mut Context<Self>,
 9397    ) {
 9398        let weak_editor = cx.weak_entity();
 9399        let bp_prompt = cx.new(|cx| {
 9400            BreakpointPromptEditor::new(
 9401                weak_editor,
 9402                anchor,
 9403                breakpoint.clone(),
 9404                edit_action,
 9405                window,
 9406                cx,
 9407            )
 9408        });
 9409
 9410        let height = bp_prompt.update(cx, |this, cx| {
 9411            this.prompt
 9412                .update(cx, |prompt, cx| prompt.max_point(cx).row().0 + 1 + 2)
 9413        });
 9414        let cloned_prompt = bp_prompt.clone();
 9415        let blocks = vec![BlockProperties {
 9416            style: BlockStyle::Sticky,
 9417            placement: BlockPlacement::Above(anchor),
 9418            height: Some(height),
 9419            render: Arc::new(move |cx| {
 9420                *cloned_prompt.read(cx).editor_margins.lock() = *cx.margins;
 9421                cloned_prompt.clone().into_any_element()
 9422            }),
 9423            priority: 0,
 9424            render_in_minimap: true,
 9425        }];
 9426
 9427        let focus_handle = bp_prompt.focus_handle(cx);
 9428        window.focus(&focus_handle);
 9429
 9430        let block_ids = self.insert_blocks(blocks, None, cx);
 9431        bp_prompt.update(cx, |prompt, _| {
 9432            prompt.add_block_ids(block_ids);
 9433        });
 9434    }
 9435
 9436    pub(crate) fn breakpoint_at_row(
 9437        &self,
 9438        row: u32,
 9439        window: &mut Window,
 9440        cx: &mut Context<Self>,
 9441    ) -> Option<(Anchor, Breakpoint)> {
 9442        let snapshot = self.snapshot(window, cx);
 9443        let breakpoint_position = snapshot.buffer_snapshot.anchor_before(Point::new(row, 0));
 9444
 9445        self.breakpoint_at_anchor(breakpoint_position, &snapshot, cx)
 9446    }
 9447
 9448    pub(crate) fn breakpoint_at_anchor(
 9449        &self,
 9450        breakpoint_position: Anchor,
 9451        snapshot: &EditorSnapshot,
 9452        cx: &mut Context<Self>,
 9453    ) -> Option<(Anchor, Breakpoint)> {
 9454        let project = self.project.clone()?;
 9455
 9456        let buffer_id = breakpoint_position.buffer_id.or_else(|| {
 9457            snapshot
 9458                .buffer_snapshot
 9459                .buffer_id_for_excerpt(breakpoint_position.excerpt_id)
 9460        })?;
 9461
 9462        let enclosing_excerpt = breakpoint_position.excerpt_id;
 9463        let buffer = project.read_with(cx, |project, cx| project.buffer_for_id(buffer_id, cx))?;
 9464        let buffer_snapshot = buffer.read(cx).snapshot();
 9465
 9466        let row = buffer_snapshot
 9467            .summary_for_anchor::<text::PointUtf16>(&breakpoint_position.text_anchor)
 9468            .row;
 9469
 9470        let line_len = snapshot.buffer_snapshot.line_len(MultiBufferRow(row));
 9471        let anchor_end = snapshot
 9472            .buffer_snapshot
 9473            .anchor_after(Point::new(row, line_len));
 9474
 9475        let bp = self
 9476            .breakpoint_store
 9477            .as_ref()?
 9478            .read_with(cx, |breakpoint_store, cx| {
 9479                breakpoint_store
 9480                    .breakpoints(
 9481                        &buffer,
 9482                        Some(breakpoint_position.text_anchor..anchor_end.text_anchor),
 9483                        &buffer_snapshot,
 9484                        cx,
 9485                    )
 9486                    .next()
 9487                    .and_then(|(anchor, bp)| {
 9488                        let breakpoint_row = buffer_snapshot
 9489                            .summary_for_anchor::<text::PointUtf16>(anchor)
 9490                            .row;
 9491
 9492                        if breakpoint_row == row {
 9493                            snapshot
 9494                                .buffer_snapshot
 9495                                .anchor_in_excerpt(enclosing_excerpt, *anchor)
 9496                                .map(|anchor| (anchor, bp.clone()))
 9497                        } else {
 9498                            None
 9499                        }
 9500                    })
 9501            });
 9502        bp
 9503    }
 9504
 9505    pub fn edit_log_breakpoint(
 9506        &mut self,
 9507        _: &EditLogBreakpoint,
 9508        window: &mut Window,
 9509        cx: &mut Context<Self>,
 9510    ) {
 9511        for (anchor, breakpoint) in self.breakpoints_at_cursors(window, cx) {
 9512            let breakpoint = breakpoint.unwrap_or_else(|| Breakpoint {
 9513                message: None,
 9514                state: BreakpointState::Enabled,
 9515                condition: None,
 9516                hit_condition: None,
 9517            });
 9518
 9519            self.add_edit_breakpoint_block(
 9520                anchor,
 9521                &breakpoint,
 9522                BreakpointPromptEditAction::Log,
 9523                window,
 9524                cx,
 9525            );
 9526        }
 9527    }
 9528
 9529    fn breakpoints_at_cursors(
 9530        &self,
 9531        window: &mut Window,
 9532        cx: &mut Context<Self>,
 9533    ) -> Vec<(Anchor, Option<Breakpoint>)> {
 9534        let snapshot = self.snapshot(window, cx);
 9535        let cursors = self
 9536            .selections
 9537            .disjoint_anchors()
 9538            .into_iter()
 9539            .map(|selection| {
 9540                let cursor_position: Point = selection.head().to_point(&snapshot.buffer_snapshot);
 9541
 9542                let breakpoint_position = self
 9543                    .breakpoint_at_row(cursor_position.row, window, cx)
 9544                    .map(|bp| bp.0)
 9545                    .unwrap_or_else(|| {
 9546                        snapshot
 9547                            .display_snapshot
 9548                            .buffer_snapshot
 9549                            .anchor_after(Point::new(cursor_position.row, 0))
 9550                    });
 9551
 9552                let breakpoint = self
 9553                    .breakpoint_at_anchor(breakpoint_position, &snapshot, cx)
 9554                    .map(|(anchor, breakpoint)| (anchor, Some(breakpoint)));
 9555
 9556                breakpoint.unwrap_or_else(|| (breakpoint_position, None))
 9557            })
 9558            // 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.
 9559            .collect::<HashMap<Anchor, _>>();
 9560
 9561        cursors.into_iter().collect()
 9562    }
 9563
 9564    pub fn enable_breakpoint(
 9565        &mut self,
 9566        _: &crate::actions::EnableBreakpoint,
 9567        window: &mut Window,
 9568        cx: &mut Context<Self>,
 9569    ) {
 9570        for (anchor, breakpoint) in self.breakpoints_at_cursors(window, cx) {
 9571            let Some(breakpoint) = breakpoint.filter(|breakpoint| breakpoint.is_disabled()) else {
 9572                continue;
 9573            };
 9574            self.edit_breakpoint_at_anchor(
 9575                anchor,
 9576                breakpoint,
 9577                BreakpointEditAction::InvertState,
 9578                cx,
 9579            );
 9580        }
 9581    }
 9582
 9583    pub fn disable_breakpoint(
 9584        &mut self,
 9585        _: &crate::actions::DisableBreakpoint,
 9586        window: &mut Window,
 9587        cx: &mut Context<Self>,
 9588    ) {
 9589        for (anchor, breakpoint) in self.breakpoints_at_cursors(window, cx) {
 9590            let Some(breakpoint) = breakpoint.filter(|breakpoint| breakpoint.is_enabled()) else {
 9591                continue;
 9592            };
 9593            self.edit_breakpoint_at_anchor(
 9594                anchor,
 9595                breakpoint,
 9596                BreakpointEditAction::InvertState,
 9597                cx,
 9598            );
 9599        }
 9600    }
 9601
 9602    pub fn toggle_breakpoint(
 9603        &mut self,
 9604        _: &crate::actions::ToggleBreakpoint,
 9605        window: &mut Window,
 9606        cx: &mut Context<Self>,
 9607    ) {
 9608        for (anchor, breakpoint) in self.breakpoints_at_cursors(window, cx) {
 9609            if let Some(breakpoint) = breakpoint {
 9610                self.edit_breakpoint_at_anchor(
 9611                    anchor,
 9612                    breakpoint,
 9613                    BreakpointEditAction::Toggle,
 9614                    cx,
 9615                );
 9616            } else {
 9617                self.edit_breakpoint_at_anchor(
 9618                    anchor,
 9619                    Breakpoint::new_standard(),
 9620                    BreakpointEditAction::Toggle,
 9621                    cx,
 9622                );
 9623            }
 9624        }
 9625    }
 9626
 9627    pub fn edit_breakpoint_at_anchor(
 9628        &mut self,
 9629        breakpoint_position: Anchor,
 9630        breakpoint: Breakpoint,
 9631        edit_action: BreakpointEditAction,
 9632        cx: &mut Context<Self>,
 9633    ) {
 9634        let Some(breakpoint_store) = &self.breakpoint_store else {
 9635            return;
 9636        };
 9637
 9638        let Some(buffer_id) = breakpoint_position.buffer_id.or_else(|| {
 9639            if breakpoint_position == Anchor::min() {
 9640                self.buffer()
 9641                    .read(cx)
 9642                    .excerpt_buffer_ids()
 9643                    .into_iter()
 9644                    .next()
 9645            } else {
 9646                None
 9647            }
 9648        }) else {
 9649            return;
 9650        };
 9651
 9652        let Some(buffer) = self.buffer().read(cx).buffer(buffer_id) else {
 9653            return;
 9654        };
 9655
 9656        breakpoint_store.update(cx, |breakpoint_store, cx| {
 9657            breakpoint_store.toggle_breakpoint(
 9658                buffer,
 9659                (breakpoint_position.text_anchor, breakpoint),
 9660                edit_action,
 9661                cx,
 9662            );
 9663        });
 9664
 9665        cx.notify();
 9666    }
 9667
 9668    #[cfg(any(test, feature = "test-support"))]
 9669    pub fn breakpoint_store(&self) -> Option<Entity<BreakpointStore>> {
 9670        self.breakpoint_store.clone()
 9671    }
 9672
 9673    pub fn prepare_restore_change(
 9674        &self,
 9675        revert_changes: &mut HashMap<BufferId, Vec<(Range<text::Anchor>, Rope)>>,
 9676        hunk: &MultiBufferDiffHunk,
 9677        cx: &mut App,
 9678    ) -> Option<()> {
 9679        if hunk.is_created_file() {
 9680            return None;
 9681        }
 9682        let buffer = self.buffer.read(cx);
 9683        let diff = buffer.diff_for(hunk.buffer_id)?;
 9684        let buffer = buffer.buffer(hunk.buffer_id)?;
 9685        let buffer = buffer.read(cx);
 9686        let original_text = diff
 9687            .read(cx)
 9688            .base_text()
 9689            .as_rope()
 9690            .slice(hunk.diff_base_byte_range.clone());
 9691        let buffer_snapshot = buffer.snapshot();
 9692        let buffer_revert_changes = revert_changes.entry(buffer.remote_id()).or_default();
 9693        if let Err(i) = buffer_revert_changes.binary_search_by(|probe| {
 9694            probe
 9695                .0
 9696                .start
 9697                .cmp(&hunk.buffer_range.start, &buffer_snapshot)
 9698                .then(probe.0.end.cmp(&hunk.buffer_range.end, &buffer_snapshot))
 9699        }) {
 9700            buffer_revert_changes.insert(i, (hunk.buffer_range.clone(), original_text));
 9701            Some(())
 9702        } else {
 9703            None
 9704        }
 9705    }
 9706
 9707    pub fn reverse_lines(&mut self, _: &ReverseLines, window: &mut Window, cx: &mut Context<Self>) {
 9708        self.manipulate_lines(window, cx, |lines| lines.reverse())
 9709    }
 9710
 9711    pub fn shuffle_lines(&mut self, _: &ShuffleLines, window: &mut Window, cx: &mut Context<Self>) {
 9712        self.manipulate_lines(window, cx, |lines| lines.shuffle(&mut thread_rng()))
 9713    }
 9714
 9715    fn manipulate_lines<Fn>(
 9716        &mut self,
 9717        window: &mut Window,
 9718        cx: &mut Context<Self>,
 9719        mut callback: Fn,
 9720    ) where
 9721        Fn: FnMut(&mut Vec<&str>),
 9722    {
 9723        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
 9724
 9725        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 9726        let buffer = self.buffer.read(cx).snapshot(cx);
 9727
 9728        let mut edits = Vec::new();
 9729
 9730        let selections = self.selections.all::<Point>(cx);
 9731        let mut selections = selections.iter().peekable();
 9732        let mut contiguous_row_selections = Vec::new();
 9733        let mut new_selections = Vec::new();
 9734        let mut added_lines = 0;
 9735        let mut removed_lines = 0;
 9736
 9737        while let Some(selection) = selections.next() {
 9738            let (start_row, end_row) = consume_contiguous_rows(
 9739                &mut contiguous_row_selections,
 9740                selection,
 9741                &display_map,
 9742                &mut selections,
 9743            );
 9744
 9745            let start_point = Point::new(start_row.0, 0);
 9746            let end_point = Point::new(
 9747                end_row.previous_row().0,
 9748                buffer.line_len(end_row.previous_row()),
 9749            );
 9750            let text = buffer
 9751                .text_for_range(start_point..end_point)
 9752                .collect::<String>();
 9753
 9754            let mut lines = text.split('\n').collect_vec();
 9755
 9756            let lines_before = lines.len();
 9757            callback(&mut lines);
 9758            let lines_after = lines.len();
 9759
 9760            edits.push((start_point..end_point, lines.join("\n")));
 9761
 9762            // Selections must change based on added and removed line count
 9763            let start_row =
 9764                MultiBufferRow(start_point.row + added_lines as u32 - removed_lines as u32);
 9765            let end_row = MultiBufferRow(start_row.0 + lines_after.saturating_sub(1) as u32);
 9766            new_selections.push(Selection {
 9767                id: selection.id,
 9768                start: start_row,
 9769                end: end_row,
 9770                goal: SelectionGoal::None,
 9771                reversed: selection.reversed,
 9772            });
 9773
 9774            if lines_after > lines_before {
 9775                added_lines += lines_after - lines_before;
 9776            } else if lines_before > lines_after {
 9777                removed_lines += lines_before - lines_after;
 9778            }
 9779        }
 9780
 9781        self.transact(window, cx, |this, window, cx| {
 9782            let buffer = this.buffer.update(cx, |buffer, cx| {
 9783                buffer.edit(edits, None, cx);
 9784                buffer.snapshot(cx)
 9785            });
 9786
 9787            // Recalculate offsets on newly edited buffer
 9788            let new_selections = new_selections
 9789                .iter()
 9790                .map(|s| {
 9791                    let start_point = Point::new(s.start.0, 0);
 9792                    let end_point = Point::new(s.end.0, buffer.line_len(s.end));
 9793                    Selection {
 9794                        id: s.id,
 9795                        start: buffer.point_to_offset(start_point),
 9796                        end: buffer.point_to_offset(end_point),
 9797                        goal: s.goal,
 9798                        reversed: s.reversed,
 9799                    }
 9800                })
 9801                .collect();
 9802
 9803            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9804                s.select(new_selections);
 9805            });
 9806
 9807            this.request_autoscroll(Autoscroll::fit(), cx);
 9808        });
 9809    }
 9810
 9811    pub fn toggle_case(&mut self, _: &ToggleCase, window: &mut Window, cx: &mut Context<Self>) {
 9812        self.manipulate_text(window, cx, |text| {
 9813            let has_upper_case_characters = text.chars().any(|c| c.is_uppercase());
 9814            if has_upper_case_characters {
 9815                text.to_lowercase()
 9816            } else {
 9817                text.to_uppercase()
 9818            }
 9819        })
 9820    }
 9821
 9822    pub fn convert_to_upper_case(
 9823        &mut self,
 9824        _: &ConvertToUpperCase,
 9825        window: &mut Window,
 9826        cx: &mut Context<Self>,
 9827    ) {
 9828        self.manipulate_text(window, cx, |text| text.to_uppercase())
 9829    }
 9830
 9831    pub fn convert_to_lower_case(
 9832        &mut self,
 9833        _: &ConvertToLowerCase,
 9834        window: &mut Window,
 9835        cx: &mut Context<Self>,
 9836    ) {
 9837        self.manipulate_text(window, cx, |text| text.to_lowercase())
 9838    }
 9839
 9840    pub fn convert_to_title_case(
 9841        &mut self,
 9842        _: &ConvertToTitleCase,
 9843        window: &mut Window,
 9844        cx: &mut Context<Self>,
 9845    ) {
 9846        self.manipulate_text(window, cx, |text| {
 9847            text.split('\n')
 9848                .map(|line| line.to_case(Case::Title))
 9849                .join("\n")
 9850        })
 9851    }
 9852
 9853    pub fn convert_to_snake_case(
 9854        &mut self,
 9855        _: &ConvertToSnakeCase,
 9856        window: &mut Window,
 9857        cx: &mut Context<Self>,
 9858    ) {
 9859        self.manipulate_text(window, cx, |text| text.to_case(Case::Snake))
 9860    }
 9861
 9862    pub fn convert_to_kebab_case(
 9863        &mut self,
 9864        _: &ConvertToKebabCase,
 9865        window: &mut Window,
 9866        cx: &mut Context<Self>,
 9867    ) {
 9868        self.manipulate_text(window, cx, |text| text.to_case(Case::Kebab))
 9869    }
 9870
 9871    pub fn convert_to_upper_camel_case(
 9872        &mut self,
 9873        _: &ConvertToUpperCamelCase,
 9874        window: &mut Window,
 9875        cx: &mut Context<Self>,
 9876    ) {
 9877        self.manipulate_text(window, cx, |text| {
 9878            text.split('\n')
 9879                .map(|line| line.to_case(Case::UpperCamel))
 9880                .join("\n")
 9881        })
 9882    }
 9883
 9884    pub fn convert_to_lower_camel_case(
 9885        &mut self,
 9886        _: &ConvertToLowerCamelCase,
 9887        window: &mut Window,
 9888        cx: &mut Context<Self>,
 9889    ) {
 9890        self.manipulate_text(window, cx, |text| text.to_case(Case::Camel))
 9891    }
 9892
 9893    pub fn convert_to_opposite_case(
 9894        &mut self,
 9895        _: &ConvertToOppositeCase,
 9896        window: &mut Window,
 9897        cx: &mut Context<Self>,
 9898    ) {
 9899        self.manipulate_text(window, cx, |text| {
 9900            text.chars()
 9901                .fold(String::with_capacity(text.len()), |mut t, c| {
 9902                    if c.is_uppercase() {
 9903                        t.extend(c.to_lowercase());
 9904                    } else {
 9905                        t.extend(c.to_uppercase());
 9906                    }
 9907                    t
 9908                })
 9909        })
 9910    }
 9911
 9912    pub fn convert_to_rot13(
 9913        &mut self,
 9914        _: &ConvertToRot13,
 9915        window: &mut Window,
 9916        cx: &mut Context<Self>,
 9917    ) {
 9918        self.manipulate_text(window, cx, |text| {
 9919            text.chars()
 9920                .map(|c| match c {
 9921                    'A'..='M' | 'a'..='m' => ((c as u8) + 13) as char,
 9922                    'N'..='Z' | 'n'..='z' => ((c as u8) - 13) as char,
 9923                    _ => c,
 9924                })
 9925                .collect()
 9926        })
 9927    }
 9928
 9929    pub fn convert_to_rot47(
 9930        &mut self,
 9931        _: &ConvertToRot47,
 9932        window: &mut Window,
 9933        cx: &mut Context<Self>,
 9934    ) {
 9935        self.manipulate_text(window, cx, |text| {
 9936            text.chars()
 9937                .map(|c| {
 9938                    let code_point = c as u32;
 9939                    if code_point >= 33 && code_point <= 126 {
 9940                        return char::from_u32(33 + ((code_point + 14) % 94)).unwrap();
 9941                    }
 9942                    c
 9943                })
 9944                .collect()
 9945        })
 9946    }
 9947
 9948    fn manipulate_text<Fn>(&mut self, window: &mut Window, cx: &mut Context<Self>, mut callback: Fn)
 9949    where
 9950        Fn: FnMut(&str) -> String,
 9951    {
 9952        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 9953        let buffer = self.buffer.read(cx).snapshot(cx);
 9954
 9955        let mut new_selections = Vec::new();
 9956        let mut edits = Vec::new();
 9957        let mut selection_adjustment = 0i32;
 9958
 9959        for selection in self.selections.all::<usize>(cx) {
 9960            let selection_is_empty = selection.is_empty();
 9961
 9962            let (start, end) = if selection_is_empty {
 9963                let word_range = movement::surrounding_word(
 9964                    &display_map,
 9965                    selection.start.to_display_point(&display_map),
 9966                );
 9967                let start = word_range.start.to_offset(&display_map, Bias::Left);
 9968                let end = word_range.end.to_offset(&display_map, Bias::Left);
 9969                (start, end)
 9970            } else {
 9971                (selection.start, selection.end)
 9972            };
 9973
 9974            let text = buffer.text_for_range(start..end).collect::<String>();
 9975            let old_length = text.len() as i32;
 9976            let text = callback(&text);
 9977
 9978            new_selections.push(Selection {
 9979                start: (start as i32 - selection_adjustment) as usize,
 9980                end: ((start + text.len()) as i32 - selection_adjustment) as usize,
 9981                goal: SelectionGoal::None,
 9982                ..selection
 9983            });
 9984
 9985            selection_adjustment += old_length - text.len() as i32;
 9986
 9987            edits.push((start..end, text));
 9988        }
 9989
 9990        self.transact(window, cx, |this, window, cx| {
 9991            this.buffer.update(cx, |buffer, cx| {
 9992                buffer.edit(edits, None, cx);
 9993            });
 9994
 9995            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9996                s.select(new_selections);
 9997            });
 9998
 9999            this.request_autoscroll(Autoscroll::fit(), cx);
10000        });
10001    }
10002
10003    pub fn duplicate(
10004        &mut self,
10005        upwards: bool,
10006        whole_lines: bool,
10007        window: &mut Window,
10008        cx: &mut Context<Self>,
10009    ) {
10010        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
10011
10012        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10013        let buffer = &display_map.buffer_snapshot;
10014        let selections = self.selections.all::<Point>(cx);
10015
10016        let mut edits = Vec::new();
10017        let mut selections_iter = selections.iter().peekable();
10018        while let Some(selection) = selections_iter.next() {
10019            let mut rows = selection.spanned_rows(false, &display_map);
10020            // duplicate line-wise
10021            if whole_lines || selection.start == selection.end {
10022                // Avoid duplicating the same lines twice.
10023                while let Some(next_selection) = selections_iter.peek() {
10024                    let next_rows = next_selection.spanned_rows(false, &display_map);
10025                    if next_rows.start < rows.end {
10026                        rows.end = next_rows.end;
10027                        selections_iter.next().unwrap();
10028                    } else {
10029                        break;
10030                    }
10031                }
10032
10033                // Copy the text from the selected row region and splice it either at the start
10034                // or end of the region.
10035                let start = Point::new(rows.start.0, 0);
10036                let end = Point::new(
10037                    rows.end.previous_row().0,
10038                    buffer.line_len(rows.end.previous_row()),
10039                );
10040                let text = buffer
10041                    .text_for_range(start..end)
10042                    .chain(Some("\n"))
10043                    .collect::<String>();
10044                let insert_location = if upwards {
10045                    Point::new(rows.end.0, 0)
10046                } else {
10047                    start
10048                };
10049                edits.push((insert_location..insert_location, text));
10050            } else {
10051                // duplicate character-wise
10052                let start = selection.start;
10053                let end = selection.end;
10054                let text = buffer.text_for_range(start..end).collect::<String>();
10055                edits.push((selection.end..selection.end, text));
10056            }
10057        }
10058
10059        self.transact(window, cx, |this, _, cx| {
10060            this.buffer.update(cx, |buffer, cx| {
10061                buffer.edit(edits, None, cx);
10062            });
10063
10064            this.request_autoscroll(Autoscroll::fit(), cx);
10065        });
10066    }
10067
10068    pub fn duplicate_line_up(
10069        &mut self,
10070        _: &DuplicateLineUp,
10071        window: &mut Window,
10072        cx: &mut Context<Self>,
10073    ) {
10074        self.duplicate(true, true, window, cx);
10075    }
10076
10077    pub fn duplicate_line_down(
10078        &mut self,
10079        _: &DuplicateLineDown,
10080        window: &mut Window,
10081        cx: &mut Context<Self>,
10082    ) {
10083        self.duplicate(false, true, window, cx);
10084    }
10085
10086    pub fn duplicate_selection(
10087        &mut self,
10088        _: &DuplicateSelection,
10089        window: &mut Window,
10090        cx: &mut Context<Self>,
10091    ) {
10092        self.duplicate(false, false, window, cx);
10093    }
10094
10095    pub fn move_line_up(&mut self, _: &MoveLineUp, window: &mut Window, cx: &mut Context<Self>) {
10096        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
10097
10098        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10099        let buffer = self.buffer.read(cx).snapshot(cx);
10100
10101        let mut edits = Vec::new();
10102        let mut unfold_ranges = Vec::new();
10103        let mut refold_creases = Vec::new();
10104
10105        let selections = self.selections.all::<Point>(cx);
10106        let mut selections = selections.iter().peekable();
10107        let mut contiguous_row_selections = Vec::new();
10108        let mut new_selections = Vec::new();
10109
10110        while let Some(selection) = selections.next() {
10111            // Find all the selections that span a contiguous row range
10112            let (start_row, end_row) = consume_contiguous_rows(
10113                &mut contiguous_row_selections,
10114                selection,
10115                &display_map,
10116                &mut selections,
10117            );
10118
10119            // Move the text spanned by the row range to be before the line preceding the row range
10120            if start_row.0 > 0 {
10121                let range_to_move = Point::new(
10122                    start_row.previous_row().0,
10123                    buffer.line_len(start_row.previous_row()),
10124                )
10125                    ..Point::new(
10126                        end_row.previous_row().0,
10127                        buffer.line_len(end_row.previous_row()),
10128                    );
10129                let insertion_point = display_map
10130                    .prev_line_boundary(Point::new(start_row.previous_row().0, 0))
10131                    .0;
10132
10133                // Don't move lines across excerpts
10134                if buffer
10135                    .excerpt_containing(insertion_point..range_to_move.end)
10136                    .is_some()
10137                {
10138                    let text = buffer
10139                        .text_for_range(range_to_move.clone())
10140                        .flat_map(|s| s.chars())
10141                        .skip(1)
10142                        .chain(['\n'])
10143                        .collect::<String>();
10144
10145                    edits.push((
10146                        buffer.anchor_after(range_to_move.start)
10147                            ..buffer.anchor_before(range_to_move.end),
10148                        String::new(),
10149                    ));
10150                    let insertion_anchor = buffer.anchor_after(insertion_point);
10151                    edits.push((insertion_anchor..insertion_anchor, text));
10152
10153                    let row_delta = range_to_move.start.row - insertion_point.row + 1;
10154
10155                    // Move selections up
10156                    new_selections.extend(contiguous_row_selections.drain(..).map(
10157                        |mut selection| {
10158                            selection.start.row -= row_delta;
10159                            selection.end.row -= row_delta;
10160                            selection
10161                        },
10162                    ));
10163
10164                    // Move folds up
10165                    unfold_ranges.push(range_to_move.clone());
10166                    for fold in display_map.folds_in_range(
10167                        buffer.anchor_before(range_to_move.start)
10168                            ..buffer.anchor_after(range_to_move.end),
10169                    ) {
10170                        let mut start = fold.range.start.to_point(&buffer);
10171                        let mut end = fold.range.end.to_point(&buffer);
10172                        start.row -= row_delta;
10173                        end.row -= row_delta;
10174                        refold_creases.push(Crease::simple(start..end, fold.placeholder.clone()));
10175                    }
10176                }
10177            }
10178
10179            // If we didn't move line(s), preserve the existing selections
10180            new_selections.append(&mut contiguous_row_selections);
10181        }
10182
10183        self.transact(window, cx, |this, window, cx| {
10184            this.unfold_ranges(&unfold_ranges, true, true, cx);
10185            this.buffer.update(cx, |buffer, cx| {
10186                for (range, text) in edits {
10187                    buffer.edit([(range, text)], None, cx);
10188                }
10189            });
10190            this.fold_creases(refold_creases, true, window, cx);
10191            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10192                s.select(new_selections);
10193            })
10194        });
10195    }
10196
10197    pub fn move_line_down(
10198        &mut self,
10199        _: &MoveLineDown,
10200        window: &mut Window,
10201        cx: &mut Context<Self>,
10202    ) {
10203        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
10204
10205        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10206        let buffer = self.buffer.read(cx).snapshot(cx);
10207
10208        let mut edits = Vec::new();
10209        let mut unfold_ranges = Vec::new();
10210        let mut refold_creases = Vec::new();
10211
10212        let selections = self.selections.all::<Point>(cx);
10213        let mut selections = selections.iter().peekable();
10214        let mut contiguous_row_selections = Vec::new();
10215        let mut new_selections = Vec::new();
10216
10217        while let Some(selection) = selections.next() {
10218            // Find all the selections that span a contiguous row range
10219            let (start_row, end_row) = consume_contiguous_rows(
10220                &mut contiguous_row_selections,
10221                selection,
10222                &display_map,
10223                &mut selections,
10224            );
10225
10226            // Move the text spanned by the row range to be after the last line of the row range
10227            if end_row.0 <= buffer.max_point().row {
10228                let range_to_move =
10229                    MultiBufferPoint::new(start_row.0, 0)..MultiBufferPoint::new(end_row.0, 0);
10230                let insertion_point = display_map
10231                    .next_line_boundary(MultiBufferPoint::new(end_row.0, 0))
10232                    .0;
10233
10234                // Don't move lines across excerpt boundaries
10235                if buffer
10236                    .excerpt_containing(range_to_move.start..insertion_point)
10237                    .is_some()
10238                {
10239                    let mut text = String::from("\n");
10240                    text.extend(buffer.text_for_range(range_to_move.clone()));
10241                    text.pop(); // Drop trailing newline
10242                    edits.push((
10243                        buffer.anchor_after(range_to_move.start)
10244                            ..buffer.anchor_before(range_to_move.end),
10245                        String::new(),
10246                    ));
10247                    let insertion_anchor = buffer.anchor_after(insertion_point);
10248                    edits.push((insertion_anchor..insertion_anchor, text));
10249
10250                    let row_delta = insertion_point.row - range_to_move.end.row + 1;
10251
10252                    // Move selections down
10253                    new_selections.extend(contiguous_row_selections.drain(..).map(
10254                        |mut selection| {
10255                            selection.start.row += row_delta;
10256                            selection.end.row += row_delta;
10257                            selection
10258                        },
10259                    ));
10260
10261                    // Move folds down
10262                    unfold_ranges.push(range_to_move.clone());
10263                    for fold in display_map.folds_in_range(
10264                        buffer.anchor_before(range_to_move.start)
10265                            ..buffer.anchor_after(range_to_move.end),
10266                    ) {
10267                        let mut start = fold.range.start.to_point(&buffer);
10268                        let mut end = fold.range.end.to_point(&buffer);
10269                        start.row += row_delta;
10270                        end.row += row_delta;
10271                        refold_creases.push(Crease::simple(start..end, fold.placeholder.clone()));
10272                    }
10273                }
10274            }
10275
10276            // If we didn't move line(s), preserve the existing selections
10277            new_selections.append(&mut contiguous_row_selections);
10278        }
10279
10280        self.transact(window, cx, |this, window, cx| {
10281            this.unfold_ranges(&unfold_ranges, true, true, cx);
10282            this.buffer.update(cx, |buffer, cx| {
10283                for (range, text) in edits {
10284                    buffer.edit([(range, text)], None, cx);
10285                }
10286            });
10287            this.fold_creases(refold_creases, true, window, cx);
10288            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10289                s.select(new_selections)
10290            });
10291        });
10292    }
10293
10294    pub fn transpose(&mut self, _: &Transpose, window: &mut Window, cx: &mut Context<Self>) {
10295        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
10296        let text_layout_details = &self.text_layout_details(window);
10297        self.transact(window, cx, |this, window, cx| {
10298            let edits = this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10299                let mut edits: Vec<(Range<usize>, String)> = Default::default();
10300                s.move_with(|display_map, selection| {
10301                    if !selection.is_empty() {
10302                        return;
10303                    }
10304
10305                    let mut head = selection.head();
10306                    let mut transpose_offset = head.to_offset(display_map, Bias::Right);
10307                    if head.column() == display_map.line_len(head.row()) {
10308                        transpose_offset = display_map
10309                            .buffer_snapshot
10310                            .clip_offset(transpose_offset.saturating_sub(1), Bias::Left);
10311                    }
10312
10313                    if transpose_offset == 0 {
10314                        return;
10315                    }
10316
10317                    *head.column_mut() += 1;
10318                    head = display_map.clip_point(head, Bias::Right);
10319                    let goal = SelectionGoal::HorizontalPosition(
10320                        display_map
10321                            .x_for_display_point(head, text_layout_details)
10322                            .into(),
10323                    );
10324                    selection.collapse_to(head, goal);
10325
10326                    let transpose_start = display_map
10327                        .buffer_snapshot
10328                        .clip_offset(transpose_offset.saturating_sub(1), Bias::Left);
10329                    if edits.last().map_or(true, |e| e.0.end <= transpose_start) {
10330                        let transpose_end = display_map
10331                            .buffer_snapshot
10332                            .clip_offset(transpose_offset + 1, Bias::Right);
10333                        if let Some(ch) =
10334                            display_map.buffer_snapshot.chars_at(transpose_start).next()
10335                        {
10336                            edits.push((transpose_start..transpose_offset, String::new()));
10337                            edits.push((transpose_end..transpose_end, ch.to_string()));
10338                        }
10339                    }
10340                });
10341                edits
10342            });
10343            this.buffer
10344                .update(cx, |buffer, cx| buffer.edit(edits, None, cx));
10345            let selections = this.selections.all::<usize>(cx);
10346            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10347                s.select(selections);
10348            });
10349        });
10350    }
10351
10352    pub fn rewrap(&mut self, _: &Rewrap, _: &mut Window, cx: &mut Context<Self>) {
10353        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
10354        self.rewrap_impl(RewrapOptions::default(), cx)
10355    }
10356
10357    pub fn rewrap_impl(&mut self, options: RewrapOptions, cx: &mut Context<Self>) {
10358        let buffer = self.buffer.read(cx).snapshot(cx);
10359        let selections = self.selections.all::<Point>(cx);
10360        let mut selections = selections.iter().peekable();
10361
10362        let mut edits = Vec::new();
10363        let mut rewrapped_row_ranges = Vec::<RangeInclusive<u32>>::new();
10364
10365        while let Some(selection) = selections.next() {
10366            let mut start_row = selection.start.row;
10367            let mut end_row = selection.end.row;
10368
10369            // Skip selections that overlap with a range that has already been rewrapped.
10370            let selection_range = start_row..end_row;
10371            if rewrapped_row_ranges
10372                .iter()
10373                .any(|range| range.overlaps(&selection_range))
10374            {
10375                continue;
10376            }
10377
10378            let tab_size = buffer.language_settings_at(selection.head(), cx).tab_size;
10379
10380            // Since not all lines in the selection may be at the same indent
10381            // level, choose the indent size that is the most common between all
10382            // of the lines.
10383            //
10384            // If there is a tie, we use the deepest indent.
10385            let (indent_size, indent_end) = {
10386                let mut indent_size_occurrences = HashMap::default();
10387                let mut rows_by_indent_size = HashMap::<IndentSize, Vec<u32>>::default();
10388
10389                for row in start_row..=end_row {
10390                    let indent = buffer.indent_size_for_line(MultiBufferRow(row));
10391                    rows_by_indent_size.entry(indent).or_default().push(row);
10392                    *indent_size_occurrences.entry(indent).or_insert(0) += 1;
10393                }
10394
10395                let indent_size = indent_size_occurrences
10396                    .into_iter()
10397                    .max_by_key(|(indent, count)| (*count, indent.len_with_expanded_tabs(tab_size)))
10398                    .map(|(indent, _)| indent)
10399                    .unwrap_or_default();
10400                let row = rows_by_indent_size[&indent_size][0];
10401                let indent_end = Point::new(row, indent_size.len);
10402
10403                (indent_size, indent_end)
10404            };
10405
10406            let mut line_prefix = indent_size.chars().collect::<String>();
10407
10408            let mut inside_comment = false;
10409            if let Some(comment_prefix) =
10410                buffer
10411                    .language_scope_at(selection.head())
10412                    .and_then(|language| {
10413                        language
10414                            .line_comment_prefixes()
10415                            .iter()
10416                            .find(|prefix| buffer.contains_str_at(indent_end, prefix))
10417                            .cloned()
10418                    })
10419            {
10420                line_prefix.push_str(&comment_prefix);
10421                inside_comment = true;
10422            }
10423
10424            let language_settings = buffer.language_settings_at(selection.head(), cx);
10425            let allow_rewrap_based_on_language = match language_settings.allow_rewrap {
10426                RewrapBehavior::InComments => inside_comment,
10427                RewrapBehavior::InSelections => !selection.is_empty(),
10428                RewrapBehavior::Anywhere => true,
10429            };
10430
10431            let should_rewrap = options.override_language_settings
10432                || allow_rewrap_based_on_language
10433                || self.hard_wrap.is_some();
10434            if !should_rewrap {
10435                continue;
10436            }
10437
10438            if selection.is_empty() {
10439                'expand_upwards: while start_row > 0 {
10440                    let prev_row = start_row - 1;
10441                    if buffer.contains_str_at(Point::new(prev_row, 0), &line_prefix)
10442                        && buffer.line_len(MultiBufferRow(prev_row)) as usize > line_prefix.len()
10443                    {
10444                        start_row = prev_row;
10445                    } else {
10446                        break 'expand_upwards;
10447                    }
10448                }
10449
10450                'expand_downwards: while end_row < buffer.max_point().row {
10451                    let next_row = end_row + 1;
10452                    if buffer.contains_str_at(Point::new(next_row, 0), &line_prefix)
10453                        && buffer.line_len(MultiBufferRow(next_row)) as usize > line_prefix.len()
10454                    {
10455                        end_row = next_row;
10456                    } else {
10457                        break 'expand_downwards;
10458                    }
10459                }
10460            }
10461
10462            let start = Point::new(start_row, 0);
10463            let start_offset = start.to_offset(&buffer);
10464            let end = Point::new(end_row, buffer.line_len(MultiBufferRow(end_row)));
10465            let selection_text = buffer.text_for_range(start..end).collect::<String>();
10466            let Some(lines_without_prefixes) = selection_text
10467                .lines()
10468                .map(|line| {
10469                    line.strip_prefix(&line_prefix)
10470                        .or_else(|| line.trim_start().strip_prefix(&line_prefix.trim_start()))
10471                        .ok_or_else(|| {
10472                            anyhow!("line did not start with prefix {line_prefix:?}: {line:?}")
10473                        })
10474                })
10475                .collect::<Result<Vec<_>, _>>()
10476                .log_err()
10477            else {
10478                continue;
10479            };
10480
10481            let wrap_column = self.hard_wrap.unwrap_or_else(|| {
10482                buffer
10483                    .language_settings_at(Point::new(start_row, 0), cx)
10484                    .preferred_line_length as usize
10485            });
10486            let wrapped_text = wrap_with_prefix(
10487                line_prefix,
10488                lines_without_prefixes.join("\n"),
10489                wrap_column,
10490                tab_size,
10491                options.preserve_existing_whitespace,
10492            );
10493
10494            // TODO: should always use char-based diff while still supporting cursor behavior that
10495            // matches vim.
10496            let mut diff_options = DiffOptions::default();
10497            if options.override_language_settings {
10498                diff_options.max_word_diff_len = 0;
10499                diff_options.max_word_diff_line_count = 0;
10500            } else {
10501                diff_options.max_word_diff_len = usize::MAX;
10502                diff_options.max_word_diff_line_count = usize::MAX;
10503            }
10504
10505            for (old_range, new_text) in
10506                text_diff_with_options(&selection_text, &wrapped_text, diff_options)
10507            {
10508                let edit_start = buffer.anchor_after(start_offset + old_range.start);
10509                let edit_end = buffer.anchor_after(start_offset + old_range.end);
10510                edits.push((edit_start..edit_end, new_text));
10511            }
10512
10513            rewrapped_row_ranges.push(start_row..=end_row);
10514        }
10515
10516        self.buffer
10517            .update(cx, |buffer, cx| buffer.edit(edits, None, cx));
10518    }
10519
10520    pub fn cut_common(&mut self, window: &mut Window, cx: &mut Context<Self>) -> ClipboardItem {
10521        let mut text = String::new();
10522        let buffer = self.buffer.read(cx).snapshot(cx);
10523        let mut selections = self.selections.all::<Point>(cx);
10524        let mut clipboard_selections = Vec::with_capacity(selections.len());
10525        {
10526            let max_point = buffer.max_point();
10527            let mut is_first = true;
10528            for selection in &mut selections {
10529                let is_entire_line = selection.is_empty() || self.selections.line_mode;
10530                if is_entire_line {
10531                    selection.start = Point::new(selection.start.row, 0);
10532                    if !selection.is_empty() && selection.end.column == 0 {
10533                        selection.end = cmp::min(max_point, selection.end);
10534                    } else {
10535                        selection.end = cmp::min(max_point, Point::new(selection.end.row + 1, 0));
10536                    }
10537                    selection.goal = SelectionGoal::None;
10538                }
10539                if is_first {
10540                    is_first = false;
10541                } else {
10542                    text += "\n";
10543                }
10544                let mut len = 0;
10545                for chunk in buffer.text_for_range(selection.start..selection.end) {
10546                    text.push_str(chunk);
10547                    len += chunk.len();
10548                }
10549                clipboard_selections.push(ClipboardSelection {
10550                    len,
10551                    is_entire_line,
10552                    first_line_indent: buffer
10553                        .indent_size_for_line(MultiBufferRow(selection.start.row))
10554                        .len,
10555                });
10556            }
10557        }
10558
10559        self.transact(window, cx, |this, window, cx| {
10560            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10561                s.select(selections);
10562            });
10563            this.insert("", window, cx);
10564        });
10565        ClipboardItem::new_string_with_json_metadata(text, clipboard_selections)
10566    }
10567
10568    pub fn cut(&mut self, _: &Cut, window: &mut Window, cx: &mut Context<Self>) {
10569        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
10570        let item = self.cut_common(window, cx);
10571        cx.write_to_clipboard(item);
10572    }
10573
10574    pub fn kill_ring_cut(&mut self, _: &KillRingCut, window: &mut Window, cx: &mut Context<Self>) {
10575        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
10576        self.change_selections(None, window, cx, |s| {
10577            s.move_with(|snapshot, sel| {
10578                if sel.is_empty() {
10579                    sel.end = DisplayPoint::new(sel.end.row(), snapshot.line_len(sel.end.row()))
10580                }
10581            });
10582        });
10583        let item = self.cut_common(window, cx);
10584        cx.set_global(KillRing(item))
10585    }
10586
10587    pub fn kill_ring_yank(
10588        &mut self,
10589        _: &KillRingYank,
10590        window: &mut Window,
10591        cx: &mut Context<Self>,
10592    ) {
10593        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
10594        let (text, metadata) = if let Some(KillRing(item)) = cx.try_global() {
10595            if let Some(ClipboardEntry::String(kill_ring)) = item.entries().first() {
10596                (kill_ring.text().to_string(), kill_ring.metadata_json())
10597            } else {
10598                return;
10599            }
10600        } else {
10601            return;
10602        };
10603        self.do_paste(&text, metadata, false, window, cx);
10604    }
10605
10606    pub fn copy_and_trim(&mut self, _: &CopyAndTrim, _: &mut Window, cx: &mut Context<Self>) {
10607        self.do_copy(true, cx);
10608    }
10609
10610    pub fn copy(&mut self, _: &Copy, _: &mut Window, cx: &mut Context<Self>) {
10611        self.do_copy(false, cx);
10612    }
10613
10614    fn do_copy(&self, strip_leading_indents: bool, cx: &mut Context<Self>) {
10615        let selections = self.selections.all::<Point>(cx);
10616        let buffer = self.buffer.read(cx).read(cx);
10617        let mut text = String::new();
10618
10619        let mut clipboard_selections = Vec::with_capacity(selections.len());
10620        {
10621            let max_point = buffer.max_point();
10622            let mut is_first = true;
10623            for selection in &selections {
10624                let mut start = selection.start;
10625                let mut end = selection.end;
10626                let is_entire_line = selection.is_empty() || self.selections.line_mode;
10627                if is_entire_line {
10628                    start = Point::new(start.row, 0);
10629                    end = cmp::min(max_point, Point::new(end.row + 1, 0));
10630                }
10631
10632                let mut trimmed_selections = Vec::new();
10633                if strip_leading_indents && end.row.saturating_sub(start.row) > 0 {
10634                    let row = MultiBufferRow(start.row);
10635                    let first_indent = buffer.indent_size_for_line(row);
10636                    if first_indent.len == 0 || start.column > first_indent.len {
10637                        trimmed_selections.push(start..end);
10638                    } else {
10639                        trimmed_selections.push(
10640                            Point::new(row.0, first_indent.len)
10641                                ..Point::new(row.0, buffer.line_len(row)),
10642                        );
10643                        for row in start.row + 1..=end.row {
10644                            let mut line_len = buffer.line_len(MultiBufferRow(row));
10645                            if row == end.row {
10646                                line_len = end.column;
10647                            }
10648                            if line_len == 0 {
10649                                trimmed_selections
10650                                    .push(Point::new(row, 0)..Point::new(row, line_len));
10651                                continue;
10652                            }
10653                            let row_indent_size = buffer.indent_size_for_line(MultiBufferRow(row));
10654                            if row_indent_size.len >= first_indent.len {
10655                                trimmed_selections.push(
10656                                    Point::new(row, first_indent.len)..Point::new(row, line_len),
10657                                );
10658                            } else {
10659                                trimmed_selections.clear();
10660                                trimmed_selections.push(start..end);
10661                                break;
10662                            }
10663                        }
10664                    }
10665                } else {
10666                    trimmed_selections.push(start..end);
10667                }
10668
10669                for trimmed_range in trimmed_selections {
10670                    if is_first {
10671                        is_first = false;
10672                    } else {
10673                        text += "\n";
10674                    }
10675                    let mut len = 0;
10676                    for chunk in buffer.text_for_range(trimmed_range.start..trimmed_range.end) {
10677                        text.push_str(chunk);
10678                        len += chunk.len();
10679                    }
10680                    clipboard_selections.push(ClipboardSelection {
10681                        len,
10682                        is_entire_line,
10683                        first_line_indent: buffer
10684                            .indent_size_for_line(MultiBufferRow(trimmed_range.start.row))
10685                            .len,
10686                    });
10687                }
10688            }
10689        }
10690
10691        cx.write_to_clipboard(ClipboardItem::new_string_with_json_metadata(
10692            text,
10693            clipboard_selections,
10694        ));
10695    }
10696
10697    pub fn do_paste(
10698        &mut self,
10699        text: &String,
10700        clipboard_selections: Option<Vec<ClipboardSelection>>,
10701        handle_entire_lines: bool,
10702        window: &mut Window,
10703        cx: &mut Context<Self>,
10704    ) {
10705        if self.read_only(cx) {
10706            return;
10707        }
10708
10709        let clipboard_text = Cow::Borrowed(text);
10710
10711        self.transact(window, cx, |this, window, cx| {
10712            if let Some(mut clipboard_selections) = clipboard_selections {
10713                let old_selections = this.selections.all::<usize>(cx);
10714                let all_selections_were_entire_line =
10715                    clipboard_selections.iter().all(|s| s.is_entire_line);
10716                let first_selection_indent_column =
10717                    clipboard_selections.first().map(|s| s.first_line_indent);
10718                if clipboard_selections.len() != old_selections.len() {
10719                    clipboard_selections.drain(..);
10720                }
10721                let cursor_offset = this.selections.last::<usize>(cx).head();
10722                let mut auto_indent_on_paste = true;
10723
10724                this.buffer.update(cx, |buffer, cx| {
10725                    let snapshot = buffer.read(cx);
10726                    auto_indent_on_paste = snapshot
10727                        .language_settings_at(cursor_offset, cx)
10728                        .auto_indent_on_paste;
10729
10730                    let mut start_offset = 0;
10731                    let mut edits = Vec::new();
10732                    let mut original_indent_columns = Vec::new();
10733                    for (ix, selection) in old_selections.iter().enumerate() {
10734                        let to_insert;
10735                        let entire_line;
10736                        let original_indent_column;
10737                        if let Some(clipboard_selection) = clipboard_selections.get(ix) {
10738                            let end_offset = start_offset + clipboard_selection.len;
10739                            to_insert = &clipboard_text[start_offset..end_offset];
10740                            entire_line = clipboard_selection.is_entire_line;
10741                            start_offset = end_offset + 1;
10742                            original_indent_column = Some(clipboard_selection.first_line_indent);
10743                        } else {
10744                            to_insert = clipboard_text.as_str();
10745                            entire_line = all_selections_were_entire_line;
10746                            original_indent_column = first_selection_indent_column
10747                        }
10748
10749                        // If the corresponding selection was empty when this slice of the
10750                        // clipboard text was written, then the entire line containing the
10751                        // selection was copied. If this selection is also currently empty,
10752                        // then paste the line before the current line of the buffer.
10753                        let range = if selection.is_empty() && handle_entire_lines && entire_line {
10754                            let column = selection.start.to_point(&snapshot).column as usize;
10755                            let line_start = selection.start - column;
10756                            line_start..line_start
10757                        } else {
10758                            selection.range()
10759                        };
10760
10761                        edits.push((range, to_insert));
10762                        original_indent_columns.push(original_indent_column);
10763                    }
10764                    drop(snapshot);
10765
10766                    buffer.edit(
10767                        edits,
10768                        if auto_indent_on_paste {
10769                            Some(AutoindentMode::Block {
10770                                original_indent_columns,
10771                            })
10772                        } else {
10773                            None
10774                        },
10775                        cx,
10776                    );
10777                });
10778
10779                let selections = this.selections.all::<usize>(cx);
10780                this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10781                    s.select(selections)
10782                });
10783            } else {
10784                this.insert(&clipboard_text, window, cx);
10785            }
10786        });
10787    }
10788
10789    pub fn paste(&mut self, _: &Paste, window: &mut Window, cx: &mut Context<Self>) {
10790        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
10791        if let Some(item) = cx.read_from_clipboard() {
10792            let entries = item.entries();
10793
10794            match entries.first() {
10795                // For now, we only support applying metadata if there's one string. In the future, we can incorporate all the selections
10796                // of all the pasted entries.
10797                Some(ClipboardEntry::String(clipboard_string)) if entries.len() == 1 => self
10798                    .do_paste(
10799                        clipboard_string.text(),
10800                        clipboard_string.metadata_json::<Vec<ClipboardSelection>>(),
10801                        true,
10802                        window,
10803                        cx,
10804                    ),
10805                _ => self.do_paste(&item.text().unwrap_or_default(), None, true, window, cx),
10806            }
10807        }
10808    }
10809
10810    pub fn undo(&mut self, _: &Undo, window: &mut Window, cx: &mut Context<Self>) {
10811        if self.read_only(cx) {
10812            return;
10813        }
10814
10815        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
10816
10817        if let Some(transaction_id) = self.buffer.update(cx, |buffer, cx| buffer.undo(cx)) {
10818            if let Some((selections, _)) =
10819                self.selection_history.transaction(transaction_id).cloned()
10820            {
10821                self.change_selections(None, window, cx, |s| {
10822                    s.select_anchors(selections.to_vec());
10823                });
10824            } else {
10825                log::error!(
10826                    "No entry in selection_history found for undo. \
10827                     This may correspond to a bug where undo does not update the selection. \
10828                     If this is occurring, please add details to \
10829                     https://github.com/zed-industries/zed/issues/22692"
10830                );
10831            }
10832            self.request_autoscroll(Autoscroll::fit(), cx);
10833            self.unmark_text(window, cx);
10834            self.refresh_inline_completion(true, false, window, cx);
10835            cx.emit(EditorEvent::Edited { transaction_id });
10836            cx.emit(EditorEvent::TransactionUndone { transaction_id });
10837        }
10838    }
10839
10840    pub fn redo(&mut self, _: &Redo, window: &mut Window, cx: &mut Context<Self>) {
10841        if self.read_only(cx) {
10842            return;
10843        }
10844
10845        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
10846
10847        if let Some(transaction_id) = self.buffer.update(cx, |buffer, cx| buffer.redo(cx)) {
10848            if let Some((_, Some(selections))) =
10849                self.selection_history.transaction(transaction_id).cloned()
10850            {
10851                self.change_selections(None, window, cx, |s| {
10852                    s.select_anchors(selections.to_vec());
10853                });
10854            } else {
10855                log::error!(
10856                    "No entry in selection_history found for redo. \
10857                     This may correspond to a bug where undo does not update the selection. \
10858                     If this is occurring, please add details to \
10859                     https://github.com/zed-industries/zed/issues/22692"
10860                );
10861            }
10862            self.request_autoscroll(Autoscroll::fit(), cx);
10863            self.unmark_text(window, cx);
10864            self.refresh_inline_completion(true, false, window, cx);
10865            cx.emit(EditorEvent::Edited { transaction_id });
10866        }
10867    }
10868
10869    pub fn finalize_last_transaction(&mut self, cx: &mut Context<Self>) {
10870        self.buffer
10871            .update(cx, |buffer, cx| buffer.finalize_last_transaction(cx));
10872    }
10873
10874    pub fn group_until_transaction(&mut self, tx_id: TransactionId, cx: &mut Context<Self>) {
10875        self.buffer
10876            .update(cx, |buffer, cx| buffer.group_until_transaction(tx_id, cx));
10877    }
10878
10879    pub fn move_left(&mut self, _: &MoveLeft, window: &mut Window, cx: &mut Context<Self>) {
10880        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
10881        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10882            s.move_with(|map, selection| {
10883                let cursor = if selection.is_empty() {
10884                    movement::left(map, selection.start)
10885                } else {
10886                    selection.start
10887                };
10888                selection.collapse_to(cursor, SelectionGoal::None);
10889            });
10890        })
10891    }
10892
10893    pub fn select_left(&mut self, _: &SelectLeft, window: &mut Window, cx: &mut Context<Self>) {
10894        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
10895        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10896            s.move_heads_with(|map, head, _| (movement::left(map, head), SelectionGoal::None));
10897        })
10898    }
10899
10900    pub fn move_right(&mut self, _: &MoveRight, window: &mut Window, cx: &mut Context<Self>) {
10901        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
10902        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10903            s.move_with(|map, selection| {
10904                let cursor = if selection.is_empty() {
10905                    movement::right(map, selection.end)
10906                } else {
10907                    selection.end
10908                };
10909                selection.collapse_to(cursor, SelectionGoal::None)
10910            });
10911        })
10912    }
10913
10914    pub fn select_right(&mut self, _: &SelectRight, window: &mut Window, cx: &mut Context<Self>) {
10915        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
10916        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10917            s.move_heads_with(|map, head, _| (movement::right(map, head), SelectionGoal::None));
10918        })
10919    }
10920
10921    pub fn move_up(&mut self, _: &MoveUp, window: &mut Window, cx: &mut Context<Self>) {
10922        if self.take_rename(true, window, cx).is_some() {
10923            return;
10924        }
10925
10926        if matches!(self.mode, EditorMode::SingleLine { .. }) {
10927            cx.propagate();
10928            return;
10929        }
10930
10931        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
10932
10933        let text_layout_details = &self.text_layout_details(window);
10934        let selection_count = self.selections.count();
10935        let first_selection = self.selections.first_anchor();
10936
10937        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10938            s.move_with(|map, selection| {
10939                if !selection.is_empty() {
10940                    selection.goal = SelectionGoal::None;
10941                }
10942                let (cursor, goal) = movement::up(
10943                    map,
10944                    selection.start,
10945                    selection.goal,
10946                    false,
10947                    text_layout_details,
10948                );
10949                selection.collapse_to(cursor, goal);
10950            });
10951        });
10952
10953        if selection_count == 1 && first_selection.range() == self.selections.first_anchor().range()
10954        {
10955            cx.propagate();
10956        }
10957    }
10958
10959    pub fn move_up_by_lines(
10960        &mut self,
10961        action: &MoveUpByLines,
10962        window: &mut Window,
10963        cx: &mut Context<Self>,
10964    ) {
10965        if self.take_rename(true, window, cx).is_some() {
10966            return;
10967        }
10968
10969        if matches!(self.mode, EditorMode::SingleLine { .. }) {
10970            cx.propagate();
10971            return;
10972        }
10973
10974        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
10975
10976        let text_layout_details = &self.text_layout_details(window);
10977
10978        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10979            s.move_with(|map, selection| {
10980                if !selection.is_empty() {
10981                    selection.goal = SelectionGoal::None;
10982                }
10983                let (cursor, goal) = movement::up_by_rows(
10984                    map,
10985                    selection.start,
10986                    action.lines,
10987                    selection.goal,
10988                    false,
10989                    text_layout_details,
10990                );
10991                selection.collapse_to(cursor, goal);
10992            });
10993        })
10994    }
10995
10996    pub fn move_down_by_lines(
10997        &mut self,
10998        action: &MoveDownByLines,
10999        window: &mut Window,
11000        cx: &mut Context<Self>,
11001    ) {
11002        if self.take_rename(true, window, cx).is_some() {
11003            return;
11004        }
11005
11006        if matches!(self.mode, EditorMode::SingleLine { .. }) {
11007            cx.propagate();
11008            return;
11009        }
11010
11011        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11012
11013        let text_layout_details = &self.text_layout_details(window);
11014
11015        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11016            s.move_with(|map, selection| {
11017                if !selection.is_empty() {
11018                    selection.goal = SelectionGoal::None;
11019                }
11020                let (cursor, goal) = movement::down_by_rows(
11021                    map,
11022                    selection.start,
11023                    action.lines,
11024                    selection.goal,
11025                    false,
11026                    text_layout_details,
11027                );
11028                selection.collapse_to(cursor, goal);
11029            });
11030        })
11031    }
11032
11033    pub fn select_down_by_lines(
11034        &mut self,
11035        action: &SelectDownByLines,
11036        window: &mut Window,
11037        cx: &mut Context<Self>,
11038    ) {
11039        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11040        let text_layout_details = &self.text_layout_details(window);
11041        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11042            s.move_heads_with(|map, head, goal| {
11043                movement::down_by_rows(map, head, action.lines, goal, false, text_layout_details)
11044            })
11045        })
11046    }
11047
11048    pub fn select_up_by_lines(
11049        &mut self,
11050        action: &SelectUpByLines,
11051        window: &mut Window,
11052        cx: &mut Context<Self>,
11053    ) {
11054        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11055        let text_layout_details = &self.text_layout_details(window);
11056        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11057            s.move_heads_with(|map, head, goal| {
11058                movement::up_by_rows(map, head, action.lines, goal, false, text_layout_details)
11059            })
11060        })
11061    }
11062
11063    pub fn select_page_up(
11064        &mut self,
11065        _: &SelectPageUp,
11066        window: &mut Window,
11067        cx: &mut Context<Self>,
11068    ) {
11069        let Some(row_count) = self.visible_row_count() else {
11070            return;
11071        };
11072
11073        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11074
11075        let text_layout_details = &self.text_layout_details(window);
11076
11077        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11078            s.move_heads_with(|map, head, goal| {
11079                movement::up_by_rows(map, head, row_count, goal, false, text_layout_details)
11080            })
11081        })
11082    }
11083
11084    pub fn move_page_up(
11085        &mut self,
11086        action: &MovePageUp,
11087        window: &mut Window,
11088        cx: &mut Context<Self>,
11089    ) {
11090        if self.take_rename(true, window, cx).is_some() {
11091            return;
11092        }
11093
11094        if self
11095            .context_menu
11096            .borrow_mut()
11097            .as_mut()
11098            .map(|menu| menu.select_first(self.completion_provider.as_deref(), cx))
11099            .unwrap_or(false)
11100        {
11101            return;
11102        }
11103
11104        if matches!(self.mode, EditorMode::SingleLine { .. }) {
11105            cx.propagate();
11106            return;
11107        }
11108
11109        let Some(row_count) = self.visible_row_count() else {
11110            return;
11111        };
11112
11113        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11114
11115        let autoscroll = if action.center_cursor {
11116            Autoscroll::center()
11117        } else {
11118            Autoscroll::fit()
11119        };
11120
11121        let text_layout_details = &self.text_layout_details(window);
11122
11123        self.change_selections(Some(autoscroll), window, cx, |s| {
11124            s.move_with(|map, selection| {
11125                if !selection.is_empty() {
11126                    selection.goal = SelectionGoal::None;
11127                }
11128                let (cursor, goal) = movement::up_by_rows(
11129                    map,
11130                    selection.end,
11131                    row_count,
11132                    selection.goal,
11133                    false,
11134                    text_layout_details,
11135                );
11136                selection.collapse_to(cursor, goal);
11137            });
11138        });
11139    }
11140
11141    pub fn select_up(&mut self, _: &SelectUp, window: &mut Window, cx: &mut Context<Self>) {
11142        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11143        let text_layout_details = &self.text_layout_details(window);
11144        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11145            s.move_heads_with(|map, head, goal| {
11146                movement::up(map, head, goal, false, text_layout_details)
11147            })
11148        })
11149    }
11150
11151    pub fn move_down(&mut self, _: &MoveDown, window: &mut Window, cx: &mut Context<Self>) {
11152        self.take_rename(true, window, cx);
11153
11154        if matches!(self.mode, EditorMode::SingleLine { .. }) {
11155            cx.propagate();
11156            return;
11157        }
11158
11159        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11160
11161        let text_layout_details = &self.text_layout_details(window);
11162        let selection_count = self.selections.count();
11163        let first_selection = self.selections.first_anchor();
11164
11165        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11166            s.move_with(|map, selection| {
11167                if !selection.is_empty() {
11168                    selection.goal = SelectionGoal::None;
11169                }
11170                let (cursor, goal) = movement::down(
11171                    map,
11172                    selection.end,
11173                    selection.goal,
11174                    false,
11175                    text_layout_details,
11176                );
11177                selection.collapse_to(cursor, goal);
11178            });
11179        });
11180
11181        if selection_count == 1 && first_selection.range() == self.selections.first_anchor().range()
11182        {
11183            cx.propagate();
11184        }
11185    }
11186
11187    pub fn select_page_down(
11188        &mut self,
11189        _: &SelectPageDown,
11190        window: &mut Window,
11191        cx: &mut Context<Self>,
11192    ) {
11193        let Some(row_count) = self.visible_row_count() else {
11194            return;
11195        };
11196
11197        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11198
11199        let text_layout_details = &self.text_layout_details(window);
11200
11201        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11202            s.move_heads_with(|map, head, goal| {
11203                movement::down_by_rows(map, head, row_count, goal, false, text_layout_details)
11204            })
11205        })
11206    }
11207
11208    pub fn move_page_down(
11209        &mut self,
11210        action: &MovePageDown,
11211        window: &mut Window,
11212        cx: &mut Context<Self>,
11213    ) {
11214        if self.take_rename(true, window, cx).is_some() {
11215            return;
11216        }
11217
11218        if self
11219            .context_menu
11220            .borrow_mut()
11221            .as_mut()
11222            .map(|menu| menu.select_last(self.completion_provider.as_deref(), cx))
11223            .unwrap_or(false)
11224        {
11225            return;
11226        }
11227
11228        if matches!(self.mode, EditorMode::SingleLine { .. }) {
11229            cx.propagate();
11230            return;
11231        }
11232
11233        let Some(row_count) = self.visible_row_count() else {
11234            return;
11235        };
11236
11237        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11238
11239        let autoscroll = if action.center_cursor {
11240            Autoscroll::center()
11241        } else {
11242            Autoscroll::fit()
11243        };
11244
11245        let text_layout_details = &self.text_layout_details(window);
11246        self.change_selections(Some(autoscroll), window, cx, |s| {
11247            s.move_with(|map, selection| {
11248                if !selection.is_empty() {
11249                    selection.goal = SelectionGoal::None;
11250                }
11251                let (cursor, goal) = movement::down_by_rows(
11252                    map,
11253                    selection.end,
11254                    row_count,
11255                    selection.goal,
11256                    false,
11257                    text_layout_details,
11258                );
11259                selection.collapse_to(cursor, goal);
11260            });
11261        });
11262    }
11263
11264    pub fn select_down(&mut self, _: &SelectDown, window: &mut Window, cx: &mut Context<Self>) {
11265        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11266        let text_layout_details = &self.text_layout_details(window);
11267        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11268            s.move_heads_with(|map, head, goal| {
11269                movement::down(map, head, goal, false, text_layout_details)
11270            })
11271        });
11272    }
11273
11274    pub fn context_menu_first(
11275        &mut self,
11276        _: &ContextMenuFirst,
11277        _window: &mut Window,
11278        cx: &mut Context<Self>,
11279    ) {
11280        if let Some(context_menu) = self.context_menu.borrow_mut().as_mut() {
11281            context_menu.select_first(self.completion_provider.as_deref(), cx);
11282        }
11283    }
11284
11285    pub fn context_menu_prev(
11286        &mut self,
11287        _: &ContextMenuPrevious,
11288        _window: &mut Window,
11289        cx: &mut Context<Self>,
11290    ) {
11291        if let Some(context_menu) = self.context_menu.borrow_mut().as_mut() {
11292            context_menu.select_prev(self.completion_provider.as_deref(), cx);
11293        }
11294    }
11295
11296    pub fn context_menu_next(
11297        &mut self,
11298        _: &ContextMenuNext,
11299        _window: &mut Window,
11300        cx: &mut Context<Self>,
11301    ) {
11302        if let Some(context_menu) = self.context_menu.borrow_mut().as_mut() {
11303            context_menu.select_next(self.completion_provider.as_deref(), cx);
11304        }
11305    }
11306
11307    pub fn context_menu_last(
11308        &mut self,
11309        _: &ContextMenuLast,
11310        _window: &mut Window,
11311        cx: &mut Context<Self>,
11312    ) {
11313        if let Some(context_menu) = self.context_menu.borrow_mut().as_mut() {
11314            context_menu.select_last(self.completion_provider.as_deref(), cx);
11315        }
11316    }
11317
11318    pub fn move_to_previous_word_start(
11319        &mut self,
11320        _: &MoveToPreviousWordStart,
11321        window: &mut Window,
11322        cx: &mut Context<Self>,
11323    ) {
11324        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11325        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11326            s.move_cursors_with(|map, head, _| {
11327                (
11328                    movement::previous_word_start(map, head),
11329                    SelectionGoal::None,
11330                )
11331            });
11332        })
11333    }
11334
11335    pub fn move_to_previous_subword_start(
11336        &mut self,
11337        _: &MoveToPreviousSubwordStart,
11338        window: &mut Window,
11339        cx: &mut Context<Self>,
11340    ) {
11341        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11342        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11343            s.move_cursors_with(|map, head, _| {
11344                (
11345                    movement::previous_subword_start(map, head),
11346                    SelectionGoal::None,
11347                )
11348            });
11349        })
11350    }
11351
11352    pub fn select_to_previous_word_start(
11353        &mut self,
11354        _: &SelectToPreviousWordStart,
11355        window: &mut Window,
11356        cx: &mut Context<Self>,
11357    ) {
11358        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11359        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11360            s.move_heads_with(|map, head, _| {
11361                (
11362                    movement::previous_word_start(map, head),
11363                    SelectionGoal::None,
11364                )
11365            });
11366        })
11367    }
11368
11369    pub fn select_to_previous_subword_start(
11370        &mut self,
11371        _: &SelectToPreviousSubwordStart,
11372        window: &mut Window,
11373        cx: &mut Context<Self>,
11374    ) {
11375        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11376        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11377            s.move_heads_with(|map, head, _| {
11378                (
11379                    movement::previous_subword_start(map, head),
11380                    SelectionGoal::None,
11381                )
11382            });
11383        })
11384    }
11385
11386    pub fn delete_to_previous_word_start(
11387        &mut self,
11388        action: &DeleteToPreviousWordStart,
11389        window: &mut Window,
11390        cx: &mut Context<Self>,
11391    ) {
11392        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
11393        self.transact(window, cx, |this, window, cx| {
11394            this.select_autoclose_pair(window, cx);
11395            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11396                s.move_with(|map, selection| {
11397                    if selection.is_empty() {
11398                        let cursor = if action.ignore_newlines {
11399                            movement::previous_word_start(map, selection.head())
11400                        } else {
11401                            movement::previous_word_start_or_newline(map, selection.head())
11402                        };
11403                        selection.set_head(cursor, SelectionGoal::None);
11404                    }
11405                });
11406            });
11407            this.insert("", window, cx);
11408        });
11409    }
11410
11411    pub fn delete_to_previous_subword_start(
11412        &mut self,
11413        _: &DeleteToPreviousSubwordStart,
11414        window: &mut Window,
11415        cx: &mut Context<Self>,
11416    ) {
11417        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
11418        self.transact(window, cx, |this, window, cx| {
11419            this.select_autoclose_pair(window, cx);
11420            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11421                s.move_with(|map, selection| {
11422                    if selection.is_empty() {
11423                        let cursor = movement::previous_subword_start(map, selection.head());
11424                        selection.set_head(cursor, SelectionGoal::None);
11425                    }
11426                });
11427            });
11428            this.insert("", window, cx);
11429        });
11430    }
11431
11432    pub fn move_to_next_word_end(
11433        &mut self,
11434        _: &MoveToNextWordEnd,
11435        window: &mut Window,
11436        cx: &mut Context<Self>,
11437    ) {
11438        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11439        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11440            s.move_cursors_with(|map, head, _| {
11441                (movement::next_word_end(map, head), SelectionGoal::None)
11442            });
11443        })
11444    }
11445
11446    pub fn move_to_next_subword_end(
11447        &mut self,
11448        _: &MoveToNextSubwordEnd,
11449        window: &mut Window,
11450        cx: &mut Context<Self>,
11451    ) {
11452        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11453        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11454            s.move_cursors_with(|map, head, _| {
11455                (movement::next_subword_end(map, head), SelectionGoal::None)
11456            });
11457        })
11458    }
11459
11460    pub fn select_to_next_word_end(
11461        &mut self,
11462        _: &SelectToNextWordEnd,
11463        window: &mut Window,
11464        cx: &mut Context<Self>,
11465    ) {
11466        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11467        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11468            s.move_heads_with(|map, head, _| {
11469                (movement::next_word_end(map, head), SelectionGoal::None)
11470            });
11471        })
11472    }
11473
11474    pub fn select_to_next_subword_end(
11475        &mut self,
11476        _: &SelectToNextSubwordEnd,
11477        window: &mut Window,
11478        cx: &mut Context<Self>,
11479    ) {
11480        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11481        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11482            s.move_heads_with(|map, head, _| {
11483                (movement::next_subword_end(map, head), SelectionGoal::None)
11484            });
11485        })
11486    }
11487
11488    pub fn delete_to_next_word_end(
11489        &mut self,
11490        action: &DeleteToNextWordEnd,
11491        window: &mut Window,
11492        cx: &mut Context<Self>,
11493    ) {
11494        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
11495        self.transact(window, cx, |this, window, cx| {
11496            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11497                s.move_with(|map, selection| {
11498                    if selection.is_empty() {
11499                        let cursor = if action.ignore_newlines {
11500                            movement::next_word_end(map, selection.head())
11501                        } else {
11502                            movement::next_word_end_or_newline(map, selection.head())
11503                        };
11504                        selection.set_head(cursor, SelectionGoal::None);
11505                    }
11506                });
11507            });
11508            this.insert("", window, cx);
11509        });
11510    }
11511
11512    pub fn delete_to_next_subword_end(
11513        &mut self,
11514        _: &DeleteToNextSubwordEnd,
11515        window: &mut Window,
11516        cx: &mut Context<Self>,
11517    ) {
11518        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
11519        self.transact(window, cx, |this, window, cx| {
11520            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11521                s.move_with(|map, selection| {
11522                    if selection.is_empty() {
11523                        let cursor = movement::next_subword_end(map, selection.head());
11524                        selection.set_head(cursor, SelectionGoal::None);
11525                    }
11526                });
11527            });
11528            this.insert("", window, cx);
11529        });
11530    }
11531
11532    pub fn move_to_beginning_of_line(
11533        &mut self,
11534        action: &MoveToBeginningOfLine,
11535        window: &mut Window,
11536        cx: &mut Context<Self>,
11537    ) {
11538        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11539        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11540            s.move_cursors_with(|map, head, _| {
11541                (
11542                    movement::indented_line_beginning(
11543                        map,
11544                        head,
11545                        action.stop_at_soft_wraps,
11546                        action.stop_at_indent,
11547                    ),
11548                    SelectionGoal::None,
11549                )
11550            });
11551        })
11552    }
11553
11554    pub fn select_to_beginning_of_line(
11555        &mut self,
11556        action: &SelectToBeginningOfLine,
11557        window: &mut Window,
11558        cx: &mut Context<Self>,
11559    ) {
11560        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11561        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11562            s.move_heads_with(|map, head, _| {
11563                (
11564                    movement::indented_line_beginning(
11565                        map,
11566                        head,
11567                        action.stop_at_soft_wraps,
11568                        action.stop_at_indent,
11569                    ),
11570                    SelectionGoal::None,
11571                )
11572            });
11573        });
11574    }
11575
11576    pub fn delete_to_beginning_of_line(
11577        &mut self,
11578        action: &DeleteToBeginningOfLine,
11579        window: &mut Window,
11580        cx: &mut Context<Self>,
11581    ) {
11582        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
11583        self.transact(window, cx, |this, window, cx| {
11584            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11585                s.move_with(|_, selection| {
11586                    selection.reversed = true;
11587                });
11588            });
11589
11590            this.select_to_beginning_of_line(
11591                &SelectToBeginningOfLine {
11592                    stop_at_soft_wraps: false,
11593                    stop_at_indent: action.stop_at_indent,
11594                },
11595                window,
11596                cx,
11597            );
11598            this.backspace(&Backspace, window, cx);
11599        });
11600    }
11601
11602    pub fn move_to_end_of_line(
11603        &mut self,
11604        action: &MoveToEndOfLine,
11605        window: &mut Window,
11606        cx: &mut Context<Self>,
11607    ) {
11608        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11609        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11610            s.move_cursors_with(|map, head, _| {
11611                (
11612                    movement::line_end(map, head, action.stop_at_soft_wraps),
11613                    SelectionGoal::None,
11614                )
11615            });
11616        })
11617    }
11618
11619    pub fn select_to_end_of_line(
11620        &mut self,
11621        action: &SelectToEndOfLine,
11622        window: &mut Window,
11623        cx: &mut Context<Self>,
11624    ) {
11625        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11626        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11627            s.move_heads_with(|map, head, _| {
11628                (
11629                    movement::line_end(map, head, action.stop_at_soft_wraps),
11630                    SelectionGoal::None,
11631                )
11632            });
11633        })
11634    }
11635
11636    pub fn delete_to_end_of_line(
11637        &mut self,
11638        _: &DeleteToEndOfLine,
11639        window: &mut Window,
11640        cx: &mut Context<Self>,
11641    ) {
11642        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
11643        self.transact(window, cx, |this, window, cx| {
11644            this.select_to_end_of_line(
11645                &SelectToEndOfLine {
11646                    stop_at_soft_wraps: false,
11647                },
11648                window,
11649                cx,
11650            );
11651            this.delete(&Delete, window, cx);
11652        });
11653    }
11654
11655    pub fn cut_to_end_of_line(
11656        &mut self,
11657        _: &CutToEndOfLine,
11658        window: &mut Window,
11659        cx: &mut Context<Self>,
11660    ) {
11661        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
11662        self.transact(window, cx, |this, window, cx| {
11663            this.select_to_end_of_line(
11664                &SelectToEndOfLine {
11665                    stop_at_soft_wraps: false,
11666                },
11667                window,
11668                cx,
11669            );
11670            this.cut(&Cut, window, cx);
11671        });
11672    }
11673
11674    pub fn move_to_start_of_paragraph(
11675        &mut self,
11676        _: &MoveToStartOfParagraph,
11677        window: &mut Window,
11678        cx: &mut Context<Self>,
11679    ) {
11680        if matches!(self.mode, EditorMode::SingleLine { .. }) {
11681            cx.propagate();
11682            return;
11683        }
11684        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11685        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11686            s.move_with(|map, selection| {
11687                selection.collapse_to(
11688                    movement::start_of_paragraph(map, selection.head(), 1),
11689                    SelectionGoal::None,
11690                )
11691            });
11692        })
11693    }
11694
11695    pub fn move_to_end_of_paragraph(
11696        &mut self,
11697        _: &MoveToEndOfParagraph,
11698        window: &mut Window,
11699        cx: &mut Context<Self>,
11700    ) {
11701        if matches!(self.mode, EditorMode::SingleLine { .. }) {
11702            cx.propagate();
11703            return;
11704        }
11705        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11706        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11707            s.move_with(|map, selection| {
11708                selection.collapse_to(
11709                    movement::end_of_paragraph(map, selection.head(), 1),
11710                    SelectionGoal::None,
11711                )
11712            });
11713        })
11714    }
11715
11716    pub fn select_to_start_of_paragraph(
11717        &mut self,
11718        _: &SelectToStartOfParagraph,
11719        window: &mut Window,
11720        cx: &mut Context<Self>,
11721    ) {
11722        if matches!(self.mode, EditorMode::SingleLine { .. }) {
11723            cx.propagate();
11724            return;
11725        }
11726        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11727        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11728            s.move_heads_with(|map, head, _| {
11729                (
11730                    movement::start_of_paragraph(map, head, 1),
11731                    SelectionGoal::None,
11732                )
11733            });
11734        })
11735    }
11736
11737    pub fn select_to_end_of_paragraph(
11738        &mut self,
11739        _: &SelectToEndOfParagraph,
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_heads_with(|map, head, _| {
11750                (
11751                    movement::end_of_paragraph(map, head, 1),
11752                    SelectionGoal::None,
11753                )
11754            });
11755        })
11756    }
11757
11758    pub fn move_to_start_of_excerpt(
11759        &mut self,
11760        _: &MoveToStartOfExcerpt,
11761        window: &mut Window,
11762        cx: &mut Context<Self>,
11763    ) {
11764        if matches!(self.mode, EditorMode::SingleLine { .. }) {
11765            cx.propagate();
11766            return;
11767        }
11768        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11769        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11770            s.move_with(|map, selection| {
11771                selection.collapse_to(
11772                    movement::start_of_excerpt(
11773                        map,
11774                        selection.head(),
11775                        workspace::searchable::Direction::Prev,
11776                    ),
11777                    SelectionGoal::None,
11778                )
11779            });
11780        })
11781    }
11782
11783    pub fn move_to_start_of_next_excerpt(
11784        &mut self,
11785        _: &MoveToStartOfNextExcerpt,
11786        window: &mut Window,
11787        cx: &mut Context<Self>,
11788    ) {
11789        if matches!(self.mode, EditorMode::SingleLine { .. }) {
11790            cx.propagate();
11791            return;
11792        }
11793
11794        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11795            s.move_with(|map, selection| {
11796                selection.collapse_to(
11797                    movement::start_of_excerpt(
11798                        map,
11799                        selection.head(),
11800                        workspace::searchable::Direction::Next,
11801                    ),
11802                    SelectionGoal::None,
11803                )
11804            });
11805        })
11806    }
11807
11808    pub fn move_to_end_of_excerpt(
11809        &mut self,
11810        _: &MoveToEndOfExcerpt,
11811        window: &mut Window,
11812        cx: &mut Context<Self>,
11813    ) {
11814        if matches!(self.mode, EditorMode::SingleLine { .. }) {
11815            cx.propagate();
11816            return;
11817        }
11818        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11819        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11820            s.move_with(|map, selection| {
11821                selection.collapse_to(
11822                    movement::end_of_excerpt(
11823                        map,
11824                        selection.head(),
11825                        workspace::searchable::Direction::Next,
11826                    ),
11827                    SelectionGoal::None,
11828                )
11829            });
11830        })
11831    }
11832
11833    pub fn move_to_end_of_previous_excerpt(
11834        &mut self,
11835        _: &MoveToEndOfPreviousExcerpt,
11836        window: &mut Window,
11837        cx: &mut Context<Self>,
11838    ) {
11839        if matches!(self.mode, EditorMode::SingleLine { .. }) {
11840            cx.propagate();
11841            return;
11842        }
11843        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11844        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11845            s.move_with(|map, selection| {
11846                selection.collapse_to(
11847                    movement::end_of_excerpt(
11848                        map,
11849                        selection.head(),
11850                        workspace::searchable::Direction::Prev,
11851                    ),
11852                    SelectionGoal::None,
11853                )
11854            });
11855        })
11856    }
11857
11858    pub fn select_to_start_of_excerpt(
11859        &mut self,
11860        _: &SelectToStartOfExcerpt,
11861        window: &mut Window,
11862        cx: &mut Context<Self>,
11863    ) {
11864        if matches!(self.mode, EditorMode::SingleLine { .. }) {
11865            cx.propagate();
11866            return;
11867        }
11868        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11869        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11870            s.move_heads_with(|map, head, _| {
11871                (
11872                    movement::start_of_excerpt(map, head, workspace::searchable::Direction::Prev),
11873                    SelectionGoal::None,
11874                )
11875            });
11876        })
11877    }
11878
11879    pub fn select_to_start_of_next_excerpt(
11880        &mut self,
11881        _: &SelectToStartOfNextExcerpt,
11882        window: &mut Window,
11883        cx: &mut Context<Self>,
11884    ) {
11885        if matches!(self.mode, EditorMode::SingleLine { .. }) {
11886            cx.propagate();
11887            return;
11888        }
11889        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11890        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11891            s.move_heads_with(|map, head, _| {
11892                (
11893                    movement::start_of_excerpt(map, head, workspace::searchable::Direction::Next),
11894                    SelectionGoal::None,
11895                )
11896            });
11897        })
11898    }
11899
11900    pub fn select_to_end_of_excerpt(
11901        &mut self,
11902        _: &SelectToEndOfExcerpt,
11903        window: &mut Window,
11904        cx: &mut Context<Self>,
11905    ) {
11906        if matches!(self.mode, EditorMode::SingleLine { .. }) {
11907            cx.propagate();
11908            return;
11909        }
11910        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11911        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11912            s.move_heads_with(|map, head, _| {
11913                (
11914                    movement::end_of_excerpt(map, head, workspace::searchable::Direction::Next),
11915                    SelectionGoal::None,
11916                )
11917            });
11918        })
11919    }
11920
11921    pub fn select_to_end_of_previous_excerpt(
11922        &mut self,
11923        _: &SelectToEndOfPreviousExcerpt,
11924        window: &mut Window,
11925        cx: &mut Context<Self>,
11926    ) {
11927        if matches!(self.mode, EditorMode::SingleLine { .. }) {
11928            cx.propagate();
11929            return;
11930        }
11931        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11932        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11933            s.move_heads_with(|map, head, _| {
11934                (
11935                    movement::end_of_excerpt(map, head, workspace::searchable::Direction::Prev),
11936                    SelectionGoal::None,
11937                )
11938            });
11939        })
11940    }
11941
11942    pub fn move_to_beginning(
11943        &mut self,
11944        _: &MoveToBeginning,
11945        window: &mut Window,
11946        cx: &mut Context<Self>,
11947    ) {
11948        if matches!(self.mode, EditorMode::SingleLine { .. }) {
11949            cx.propagate();
11950            return;
11951        }
11952        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11953        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11954            s.select_ranges(vec![0..0]);
11955        });
11956    }
11957
11958    pub fn select_to_beginning(
11959        &mut self,
11960        _: &SelectToBeginning,
11961        window: &mut Window,
11962        cx: &mut Context<Self>,
11963    ) {
11964        let mut selection = self.selections.last::<Point>(cx);
11965        selection.set_head(Point::zero(), SelectionGoal::None);
11966        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11967        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11968            s.select(vec![selection]);
11969        });
11970    }
11971
11972    pub fn move_to_end(&mut self, _: &MoveToEnd, window: &mut Window, cx: &mut Context<Self>) {
11973        if matches!(self.mode, EditorMode::SingleLine { .. }) {
11974            cx.propagate();
11975            return;
11976        }
11977        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11978        let cursor = self.buffer.read(cx).read(cx).len();
11979        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11980            s.select_ranges(vec![cursor..cursor])
11981        });
11982    }
11983
11984    pub fn set_nav_history(&mut self, nav_history: Option<ItemNavHistory>) {
11985        self.nav_history = nav_history;
11986    }
11987
11988    pub fn nav_history(&self) -> Option<&ItemNavHistory> {
11989        self.nav_history.as_ref()
11990    }
11991
11992    pub fn create_nav_history_entry(&mut self, cx: &mut Context<Self>) {
11993        self.push_to_nav_history(self.selections.newest_anchor().head(), None, false, cx);
11994    }
11995
11996    fn push_to_nav_history(
11997        &mut self,
11998        cursor_anchor: Anchor,
11999        new_position: Option<Point>,
12000        is_deactivate: bool,
12001        cx: &mut Context<Self>,
12002    ) {
12003        if let Some(nav_history) = self.nav_history.as_mut() {
12004            let buffer = self.buffer.read(cx).read(cx);
12005            let cursor_position = cursor_anchor.to_point(&buffer);
12006            let scroll_state = self.scroll_manager.anchor();
12007            let scroll_top_row = scroll_state.top_row(&buffer);
12008            drop(buffer);
12009
12010            if let Some(new_position) = new_position {
12011                let row_delta = (new_position.row as i64 - cursor_position.row as i64).abs();
12012                if row_delta < MIN_NAVIGATION_HISTORY_ROW_DELTA {
12013                    return;
12014                }
12015            }
12016
12017            nav_history.push(
12018                Some(NavigationData {
12019                    cursor_anchor,
12020                    cursor_position,
12021                    scroll_anchor: scroll_state,
12022                    scroll_top_row,
12023                }),
12024                cx,
12025            );
12026            cx.emit(EditorEvent::PushedToNavHistory {
12027                anchor: cursor_anchor,
12028                is_deactivate,
12029            })
12030        }
12031    }
12032
12033    pub fn select_to_end(&mut self, _: &SelectToEnd, window: &mut Window, cx: &mut Context<Self>) {
12034        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
12035        let buffer = self.buffer.read(cx).snapshot(cx);
12036        let mut selection = self.selections.first::<usize>(cx);
12037        selection.set_head(buffer.len(), SelectionGoal::None);
12038        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
12039            s.select(vec![selection]);
12040        });
12041    }
12042
12043    pub fn select_all(&mut self, _: &SelectAll, window: &mut Window, cx: &mut Context<Self>) {
12044        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
12045        let end = self.buffer.read(cx).read(cx).len();
12046        self.change_selections(None, window, cx, |s| {
12047            s.select_ranges(vec![0..end]);
12048        });
12049    }
12050
12051    pub fn select_line(&mut self, _: &SelectLine, window: &mut Window, cx: &mut Context<Self>) {
12052        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
12053        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
12054        let mut selections = self.selections.all::<Point>(cx);
12055        let max_point = display_map.buffer_snapshot.max_point();
12056        for selection in &mut selections {
12057            let rows = selection.spanned_rows(true, &display_map);
12058            selection.start = Point::new(rows.start.0, 0);
12059            selection.end = cmp::min(max_point, Point::new(rows.end.0, 0));
12060            selection.reversed = false;
12061        }
12062        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
12063            s.select(selections);
12064        });
12065    }
12066
12067    pub fn split_selection_into_lines(
12068        &mut self,
12069        _: &SplitSelectionIntoLines,
12070        window: &mut Window,
12071        cx: &mut Context<Self>,
12072    ) {
12073        let selections = self
12074            .selections
12075            .all::<Point>(cx)
12076            .into_iter()
12077            .map(|selection| selection.start..selection.end)
12078            .collect::<Vec<_>>();
12079        self.unfold_ranges(&selections, true, true, cx);
12080
12081        let mut new_selection_ranges = Vec::new();
12082        {
12083            let buffer = self.buffer.read(cx).read(cx);
12084            for selection in selections {
12085                for row in selection.start.row..selection.end.row {
12086                    let cursor = Point::new(row, buffer.line_len(MultiBufferRow(row)));
12087                    new_selection_ranges.push(cursor..cursor);
12088                }
12089
12090                let is_multiline_selection = selection.start.row != selection.end.row;
12091                // Don't insert last one if it's a multi-line selection ending at the start of a line,
12092                // so this action feels more ergonomic when paired with other selection operations
12093                let should_skip_last = is_multiline_selection && selection.end.column == 0;
12094                if !should_skip_last {
12095                    new_selection_ranges.push(selection.end..selection.end);
12096                }
12097            }
12098        }
12099        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
12100            s.select_ranges(new_selection_ranges);
12101        });
12102    }
12103
12104    pub fn add_selection_above(
12105        &mut self,
12106        _: &AddSelectionAbove,
12107        window: &mut Window,
12108        cx: &mut Context<Self>,
12109    ) {
12110        self.add_selection(true, window, cx);
12111    }
12112
12113    pub fn add_selection_below(
12114        &mut self,
12115        _: &AddSelectionBelow,
12116        window: &mut Window,
12117        cx: &mut Context<Self>,
12118    ) {
12119        self.add_selection(false, window, cx);
12120    }
12121
12122    fn add_selection(&mut self, above: bool, window: &mut Window, cx: &mut Context<Self>) {
12123        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
12124
12125        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
12126        let mut selections = self.selections.all::<Point>(cx);
12127        let text_layout_details = self.text_layout_details(window);
12128        let mut state = self.add_selections_state.take().unwrap_or_else(|| {
12129            let oldest_selection = selections.iter().min_by_key(|s| s.id).unwrap().clone();
12130            let range = oldest_selection.display_range(&display_map).sorted();
12131
12132            let start_x = display_map.x_for_display_point(range.start, &text_layout_details);
12133            let end_x = display_map.x_for_display_point(range.end, &text_layout_details);
12134            let positions = start_x.min(end_x)..start_x.max(end_x);
12135
12136            selections.clear();
12137            let mut stack = Vec::new();
12138            for row in range.start.row().0..=range.end.row().0 {
12139                if let Some(selection) = self.selections.build_columnar_selection(
12140                    &display_map,
12141                    DisplayRow(row),
12142                    &positions,
12143                    oldest_selection.reversed,
12144                    &text_layout_details,
12145                ) {
12146                    stack.push(selection.id);
12147                    selections.push(selection);
12148                }
12149            }
12150
12151            if above {
12152                stack.reverse();
12153            }
12154
12155            AddSelectionsState { above, stack }
12156        });
12157
12158        let last_added_selection = *state.stack.last().unwrap();
12159        let mut new_selections = Vec::new();
12160        if above == state.above {
12161            let end_row = if above {
12162                DisplayRow(0)
12163            } else {
12164                display_map.max_point().row()
12165            };
12166
12167            'outer: for selection in selections {
12168                if selection.id == last_added_selection {
12169                    let range = selection.display_range(&display_map).sorted();
12170                    debug_assert_eq!(range.start.row(), range.end.row());
12171                    let mut row = range.start.row();
12172                    let positions =
12173                        if let SelectionGoal::HorizontalRange { start, end } = selection.goal {
12174                            px(start)..px(end)
12175                        } else {
12176                            let start_x =
12177                                display_map.x_for_display_point(range.start, &text_layout_details);
12178                            let end_x =
12179                                display_map.x_for_display_point(range.end, &text_layout_details);
12180                            start_x.min(end_x)..start_x.max(end_x)
12181                        };
12182
12183                    while row != end_row {
12184                        if above {
12185                            row.0 -= 1;
12186                        } else {
12187                            row.0 += 1;
12188                        }
12189
12190                        if let Some(new_selection) = self.selections.build_columnar_selection(
12191                            &display_map,
12192                            row,
12193                            &positions,
12194                            selection.reversed,
12195                            &text_layout_details,
12196                        ) {
12197                            state.stack.push(new_selection.id);
12198                            if above {
12199                                new_selections.push(new_selection);
12200                                new_selections.push(selection);
12201                            } else {
12202                                new_selections.push(selection);
12203                                new_selections.push(new_selection);
12204                            }
12205
12206                            continue 'outer;
12207                        }
12208                    }
12209                }
12210
12211                new_selections.push(selection);
12212            }
12213        } else {
12214            new_selections = selections;
12215            new_selections.retain(|s| s.id != last_added_selection);
12216            state.stack.pop();
12217        }
12218
12219        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
12220            s.select(new_selections);
12221        });
12222        if state.stack.len() > 1 {
12223            self.add_selections_state = Some(state);
12224        }
12225    }
12226
12227    fn select_match_ranges(
12228        &mut self,
12229        range: Range<usize>,
12230        reversed: bool,
12231        replace_newest: bool,
12232        auto_scroll: Option<Autoscroll>,
12233        window: &mut Window,
12234        cx: &mut Context<Editor>,
12235    ) {
12236        self.unfold_ranges(&[range.clone()], false, auto_scroll.is_some(), cx);
12237        self.change_selections(auto_scroll, window, cx, |s| {
12238            if replace_newest {
12239                s.delete(s.newest_anchor().id);
12240            }
12241            if reversed {
12242                s.insert_range(range.end..range.start);
12243            } else {
12244                s.insert_range(range);
12245            }
12246        });
12247    }
12248
12249    pub fn select_next_match_internal(
12250        &mut self,
12251        display_map: &DisplaySnapshot,
12252        replace_newest: bool,
12253        autoscroll: Option<Autoscroll>,
12254        window: &mut Window,
12255        cx: &mut Context<Self>,
12256    ) -> Result<()> {
12257        let buffer = &display_map.buffer_snapshot;
12258        let mut selections = self.selections.all::<usize>(cx);
12259        if let Some(mut select_next_state) = self.select_next_state.take() {
12260            let query = &select_next_state.query;
12261            if !select_next_state.done {
12262                let first_selection = selections.iter().min_by_key(|s| s.id).unwrap();
12263                let last_selection = selections.iter().max_by_key(|s| s.id).unwrap();
12264                let mut next_selected_range = None;
12265
12266                let bytes_after_last_selection =
12267                    buffer.bytes_in_range(last_selection.end..buffer.len());
12268                let bytes_before_first_selection = buffer.bytes_in_range(0..first_selection.start);
12269                let query_matches = query
12270                    .stream_find_iter(bytes_after_last_selection)
12271                    .map(|result| (last_selection.end, result))
12272                    .chain(
12273                        query
12274                            .stream_find_iter(bytes_before_first_selection)
12275                            .map(|result| (0, result)),
12276                    );
12277
12278                for (start_offset, query_match) in query_matches {
12279                    let query_match = query_match.unwrap(); // can only fail due to I/O
12280                    let offset_range =
12281                        start_offset + query_match.start()..start_offset + query_match.end();
12282                    let display_range = offset_range.start.to_display_point(display_map)
12283                        ..offset_range.end.to_display_point(display_map);
12284
12285                    if !select_next_state.wordwise
12286                        || (!movement::is_inside_word(display_map, display_range.start)
12287                            && !movement::is_inside_word(display_map, display_range.end))
12288                    {
12289                        // TODO: This is n^2, because we might check all the selections
12290                        if !selections
12291                            .iter()
12292                            .any(|selection| selection.range().overlaps(&offset_range))
12293                        {
12294                            next_selected_range = Some(offset_range);
12295                            break;
12296                        }
12297                    }
12298                }
12299
12300                if let Some(next_selected_range) = next_selected_range {
12301                    self.select_match_ranges(
12302                        next_selected_range,
12303                        last_selection.reversed,
12304                        replace_newest,
12305                        autoscroll,
12306                        window,
12307                        cx,
12308                    );
12309                } else {
12310                    select_next_state.done = true;
12311                }
12312            }
12313
12314            self.select_next_state = Some(select_next_state);
12315        } else {
12316            let mut only_carets = true;
12317            let mut same_text_selected = true;
12318            let mut selected_text = None;
12319
12320            let mut selections_iter = selections.iter().peekable();
12321            while let Some(selection) = selections_iter.next() {
12322                if selection.start != selection.end {
12323                    only_carets = false;
12324                }
12325
12326                if same_text_selected {
12327                    if selected_text.is_none() {
12328                        selected_text =
12329                            Some(buffer.text_for_range(selection.range()).collect::<String>());
12330                    }
12331
12332                    if let Some(next_selection) = selections_iter.peek() {
12333                        if next_selection.range().len() == selection.range().len() {
12334                            let next_selected_text = buffer
12335                                .text_for_range(next_selection.range())
12336                                .collect::<String>();
12337                            if Some(next_selected_text) != selected_text {
12338                                same_text_selected = false;
12339                                selected_text = None;
12340                            }
12341                        } else {
12342                            same_text_selected = false;
12343                            selected_text = None;
12344                        }
12345                    }
12346                }
12347            }
12348
12349            if only_carets {
12350                for selection in &mut selections {
12351                    let word_range = movement::surrounding_word(
12352                        display_map,
12353                        selection.start.to_display_point(display_map),
12354                    );
12355                    selection.start = word_range.start.to_offset(display_map, Bias::Left);
12356                    selection.end = word_range.end.to_offset(display_map, Bias::Left);
12357                    selection.goal = SelectionGoal::None;
12358                    selection.reversed = false;
12359                    self.select_match_ranges(
12360                        selection.start..selection.end,
12361                        selection.reversed,
12362                        replace_newest,
12363                        autoscroll,
12364                        window,
12365                        cx,
12366                    );
12367                }
12368
12369                if selections.len() == 1 {
12370                    let selection = selections
12371                        .last()
12372                        .expect("ensured that there's only one selection");
12373                    let query = buffer
12374                        .text_for_range(selection.start..selection.end)
12375                        .collect::<String>();
12376                    let is_empty = query.is_empty();
12377                    let select_state = SelectNextState {
12378                        query: AhoCorasick::new(&[query])?,
12379                        wordwise: true,
12380                        done: is_empty,
12381                    };
12382                    self.select_next_state = Some(select_state);
12383                } else {
12384                    self.select_next_state = None;
12385                }
12386            } else if let Some(selected_text) = selected_text {
12387                self.select_next_state = Some(SelectNextState {
12388                    query: AhoCorasick::new(&[selected_text])?,
12389                    wordwise: false,
12390                    done: false,
12391                });
12392                self.select_next_match_internal(
12393                    display_map,
12394                    replace_newest,
12395                    autoscroll,
12396                    window,
12397                    cx,
12398                )?;
12399            }
12400        }
12401        Ok(())
12402    }
12403
12404    pub fn select_all_matches(
12405        &mut self,
12406        _action: &SelectAllMatches,
12407        window: &mut Window,
12408        cx: &mut Context<Self>,
12409    ) -> Result<()> {
12410        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
12411
12412        self.push_to_selection_history();
12413        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
12414
12415        self.select_next_match_internal(&display_map, false, None, window, cx)?;
12416        let Some(select_next_state) = self.select_next_state.as_mut() else {
12417            return Ok(());
12418        };
12419        if select_next_state.done {
12420            return Ok(());
12421        }
12422
12423        let mut new_selections = Vec::new();
12424
12425        let reversed = self.selections.oldest::<usize>(cx).reversed;
12426        let buffer = &display_map.buffer_snapshot;
12427        let query_matches = select_next_state
12428            .query
12429            .stream_find_iter(buffer.bytes_in_range(0..buffer.len()));
12430
12431        for query_match in query_matches.into_iter() {
12432            let query_match = query_match.context("query match for select all action")?; // can only fail due to I/O
12433            let offset_range = if reversed {
12434                query_match.end()..query_match.start()
12435            } else {
12436                query_match.start()..query_match.end()
12437            };
12438            let display_range = offset_range.start.to_display_point(&display_map)
12439                ..offset_range.end.to_display_point(&display_map);
12440
12441            if !select_next_state.wordwise
12442                || (!movement::is_inside_word(&display_map, display_range.start)
12443                    && !movement::is_inside_word(&display_map, display_range.end))
12444            {
12445                new_selections.push(offset_range.start..offset_range.end);
12446            }
12447        }
12448
12449        select_next_state.done = true;
12450        self.unfold_ranges(&new_selections.clone(), false, false, cx);
12451        self.change_selections(None, window, cx, |selections| {
12452            selections.select_ranges(new_selections)
12453        });
12454
12455        Ok(())
12456    }
12457
12458    pub fn select_next(
12459        &mut self,
12460        action: &SelectNext,
12461        window: &mut Window,
12462        cx: &mut Context<Self>,
12463    ) -> Result<()> {
12464        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
12465        self.push_to_selection_history();
12466        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
12467        self.select_next_match_internal(
12468            &display_map,
12469            action.replace_newest,
12470            Some(Autoscroll::newest()),
12471            window,
12472            cx,
12473        )?;
12474        Ok(())
12475    }
12476
12477    pub fn select_previous(
12478        &mut self,
12479        action: &SelectPrevious,
12480        window: &mut Window,
12481        cx: &mut Context<Self>,
12482    ) -> Result<()> {
12483        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
12484        self.push_to_selection_history();
12485        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
12486        let buffer = &display_map.buffer_snapshot;
12487        let mut selections = self.selections.all::<usize>(cx);
12488        if let Some(mut select_prev_state) = self.select_prev_state.take() {
12489            let query = &select_prev_state.query;
12490            if !select_prev_state.done {
12491                let first_selection = selections.iter().min_by_key(|s| s.id).unwrap();
12492                let last_selection = selections.iter().max_by_key(|s| s.id).unwrap();
12493                let mut next_selected_range = None;
12494                // When we're iterating matches backwards, the oldest match will actually be the furthest one in the buffer.
12495                let bytes_before_last_selection =
12496                    buffer.reversed_bytes_in_range(0..last_selection.start);
12497                let bytes_after_first_selection =
12498                    buffer.reversed_bytes_in_range(first_selection.end..buffer.len());
12499                let query_matches = query
12500                    .stream_find_iter(bytes_before_last_selection)
12501                    .map(|result| (last_selection.start, result))
12502                    .chain(
12503                        query
12504                            .stream_find_iter(bytes_after_first_selection)
12505                            .map(|result| (buffer.len(), result)),
12506                    );
12507                for (end_offset, query_match) in query_matches {
12508                    let query_match = query_match.unwrap(); // can only fail due to I/O
12509                    let offset_range =
12510                        end_offset - query_match.end()..end_offset - query_match.start();
12511                    let display_range = offset_range.start.to_display_point(&display_map)
12512                        ..offset_range.end.to_display_point(&display_map);
12513
12514                    if !select_prev_state.wordwise
12515                        || (!movement::is_inside_word(&display_map, display_range.start)
12516                            && !movement::is_inside_word(&display_map, display_range.end))
12517                    {
12518                        next_selected_range = Some(offset_range);
12519                        break;
12520                    }
12521                }
12522
12523                if let Some(next_selected_range) = next_selected_range {
12524                    self.select_match_ranges(
12525                        next_selected_range,
12526                        last_selection.reversed,
12527                        action.replace_newest,
12528                        Some(Autoscroll::newest()),
12529                        window,
12530                        cx,
12531                    );
12532                } else {
12533                    select_prev_state.done = true;
12534                }
12535            }
12536
12537            self.select_prev_state = Some(select_prev_state);
12538        } else {
12539            let mut only_carets = true;
12540            let mut same_text_selected = true;
12541            let mut selected_text = None;
12542
12543            let mut selections_iter = selections.iter().peekable();
12544            while let Some(selection) = selections_iter.next() {
12545                if selection.start != selection.end {
12546                    only_carets = false;
12547                }
12548
12549                if same_text_selected {
12550                    if selected_text.is_none() {
12551                        selected_text =
12552                            Some(buffer.text_for_range(selection.range()).collect::<String>());
12553                    }
12554
12555                    if let Some(next_selection) = selections_iter.peek() {
12556                        if next_selection.range().len() == selection.range().len() {
12557                            let next_selected_text = buffer
12558                                .text_for_range(next_selection.range())
12559                                .collect::<String>();
12560                            if Some(next_selected_text) != selected_text {
12561                                same_text_selected = false;
12562                                selected_text = None;
12563                            }
12564                        } else {
12565                            same_text_selected = false;
12566                            selected_text = None;
12567                        }
12568                    }
12569                }
12570            }
12571
12572            if only_carets {
12573                for selection in &mut selections {
12574                    let word_range = movement::surrounding_word(
12575                        &display_map,
12576                        selection.start.to_display_point(&display_map),
12577                    );
12578                    selection.start = word_range.start.to_offset(&display_map, Bias::Left);
12579                    selection.end = word_range.end.to_offset(&display_map, Bias::Left);
12580                    selection.goal = SelectionGoal::None;
12581                    selection.reversed = false;
12582                    self.select_match_ranges(
12583                        selection.start..selection.end,
12584                        selection.reversed,
12585                        action.replace_newest,
12586                        Some(Autoscroll::newest()),
12587                        window,
12588                        cx,
12589                    );
12590                }
12591                if selections.len() == 1 {
12592                    let selection = selections
12593                        .last()
12594                        .expect("ensured that there's only one selection");
12595                    let query = buffer
12596                        .text_for_range(selection.start..selection.end)
12597                        .collect::<String>();
12598                    let is_empty = query.is_empty();
12599                    let select_state = SelectNextState {
12600                        query: AhoCorasick::new(&[query.chars().rev().collect::<String>()])?,
12601                        wordwise: true,
12602                        done: is_empty,
12603                    };
12604                    self.select_prev_state = Some(select_state);
12605                } else {
12606                    self.select_prev_state = None;
12607                }
12608            } else if let Some(selected_text) = selected_text {
12609                self.select_prev_state = Some(SelectNextState {
12610                    query: AhoCorasick::new(&[selected_text.chars().rev().collect::<String>()])?,
12611                    wordwise: false,
12612                    done: false,
12613                });
12614                self.select_previous(action, window, cx)?;
12615            }
12616        }
12617        Ok(())
12618    }
12619
12620    pub fn find_next_match(
12621        &mut self,
12622        _: &FindNextMatch,
12623        window: &mut Window,
12624        cx: &mut Context<Self>,
12625    ) -> Result<()> {
12626        let selections = self.selections.disjoint_anchors();
12627        match selections.first() {
12628            Some(first) if selections.len() >= 2 => {
12629                self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
12630                    s.select_ranges([first.range()]);
12631                });
12632            }
12633            _ => self.select_next(
12634                &SelectNext {
12635                    replace_newest: true,
12636                },
12637                window,
12638                cx,
12639            )?,
12640        }
12641        Ok(())
12642    }
12643
12644    pub fn find_previous_match(
12645        &mut self,
12646        _: &FindPreviousMatch,
12647        window: &mut Window,
12648        cx: &mut Context<Self>,
12649    ) -> Result<()> {
12650        let selections = self.selections.disjoint_anchors();
12651        match selections.last() {
12652            Some(last) if selections.len() >= 2 => {
12653                self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
12654                    s.select_ranges([last.range()]);
12655                });
12656            }
12657            _ => self.select_previous(
12658                &SelectPrevious {
12659                    replace_newest: true,
12660                },
12661                window,
12662                cx,
12663            )?,
12664        }
12665        Ok(())
12666    }
12667
12668    pub fn toggle_comments(
12669        &mut self,
12670        action: &ToggleComments,
12671        window: &mut Window,
12672        cx: &mut Context<Self>,
12673    ) {
12674        if self.read_only(cx) {
12675            return;
12676        }
12677        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
12678        let text_layout_details = &self.text_layout_details(window);
12679        self.transact(window, cx, |this, window, cx| {
12680            let mut selections = this.selections.all::<MultiBufferPoint>(cx);
12681            let mut edits = Vec::new();
12682            let mut selection_edit_ranges = Vec::new();
12683            let mut last_toggled_row = None;
12684            let snapshot = this.buffer.read(cx).read(cx);
12685            let empty_str: Arc<str> = Arc::default();
12686            let mut suffixes_inserted = Vec::new();
12687            let ignore_indent = action.ignore_indent;
12688
12689            fn comment_prefix_range(
12690                snapshot: &MultiBufferSnapshot,
12691                row: MultiBufferRow,
12692                comment_prefix: &str,
12693                comment_prefix_whitespace: &str,
12694                ignore_indent: bool,
12695            ) -> Range<Point> {
12696                let indent_size = if ignore_indent {
12697                    0
12698                } else {
12699                    snapshot.indent_size_for_line(row).len
12700                };
12701
12702                let start = Point::new(row.0, indent_size);
12703
12704                let mut line_bytes = snapshot
12705                    .bytes_in_range(start..snapshot.max_point())
12706                    .flatten()
12707                    .copied();
12708
12709                // If this line currently begins with the line comment prefix, then record
12710                // the range containing the prefix.
12711                if line_bytes
12712                    .by_ref()
12713                    .take(comment_prefix.len())
12714                    .eq(comment_prefix.bytes())
12715                {
12716                    // Include any whitespace that matches the comment prefix.
12717                    let matching_whitespace_len = line_bytes
12718                        .zip(comment_prefix_whitespace.bytes())
12719                        .take_while(|(a, b)| a == b)
12720                        .count() as u32;
12721                    let end = Point::new(
12722                        start.row,
12723                        start.column + comment_prefix.len() as u32 + matching_whitespace_len,
12724                    );
12725                    start..end
12726                } else {
12727                    start..start
12728                }
12729            }
12730
12731            fn comment_suffix_range(
12732                snapshot: &MultiBufferSnapshot,
12733                row: MultiBufferRow,
12734                comment_suffix: &str,
12735                comment_suffix_has_leading_space: bool,
12736            ) -> Range<Point> {
12737                let end = Point::new(row.0, snapshot.line_len(row));
12738                let suffix_start_column = end.column.saturating_sub(comment_suffix.len() as u32);
12739
12740                let mut line_end_bytes = snapshot
12741                    .bytes_in_range(Point::new(end.row, suffix_start_column.saturating_sub(1))..end)
12742                    .flatten()
12743                    .copied();
12744
12745                let leading_space_len = if suffix_start_column > 0
12746                    && line_end_bytes.next() == Some(b' ')
12747                    && comment_suffix_has_leading_space
12748                {
12749                    1
12750                } else {
12751                    0
12752                };
12753
12754                // If this line currently begins with the line comment prefix, then record
12755                // the range containing the prefix.
12756                if line_end_bytes.by_ref().eq(comment_suffix.bytes()) {
12757                    let start = Point::new(end.row, suffix_start_column - leading_space_len);
12758                    start..end
12759                } else {
12760                    end..end
12761                }
12762            }
12763
12764            // TODO: Handle selections that cross excerpts
12765            for selection in &mut selections {
12766                let start_column = snapshot
12767                    .indent_size_for_line(MultiBufferRow(selection.start.row))
12768                    .len;
12769                let language = if let Some(language) =
12770                    snapshot.language_scope_at(Point::new(selection.start.row, start_column))
12771                {
12772                    language
12773                } else {
12774                    continue;
12775                };
12776
12777                selection_edit_ranges.clear();
12778
12779                // If multiple selections contain a given row, avoid processing that
12780                // row more than once.
12781                let mut start_row = MultiBufferRow(selection.start.row);
12782                if last_toggled_row == Some(start_row) {
12783                    start_row = start_row.next_row();
12784                }
12785                let end_row =
12786                    if selection.end.row > selection.start.row && selection.end.column == 0 {
12787                        MultiBufferRow(selection.end.row - 1)
12788                    } else {
12789                        MultiBufferRow(selection.end.row)
12790                    };
12791                last_toggled_row = Some(end_row);
12792
12793                if start_row > end_row {
12794                    continue;
12795                }
12796
12797                // If the language has line comments, toggle those.
12798                let mut full_comment_prefixes = language.line_comment_prefixes().to_vec();
12799
12800                // If ignore_indent is set, trim spaces from the right side of all full_comment_prefixes
12801                if ignore_indent {
12802                    full_comment_prefixes = full_comment_prefixes
12803                        .into_iter()
12804                        .map(|s| Arc::from(s.trim_end()))
12805                        .collect();
12806                }
12807
12808                if !full_comment_prefixes.is_empty() {
12809                    let first_prefix = full_comment_prefixes
12810                        .first()
12811                        .expect("prefixes is non-empty");
12812                    let prefix_trimmed_lengths = full_comment_prefixes
12813                        .iter()
12814                        .map(|p| p.trim_end_matches(' ').len())
12815                        .collect::<SmallVec<[usize; 4]>>();
12816
12817                    let mut all_selection_lines_are_comments = true;
12818
12819                    for row in start_row.0..=end_row.0 {
12820                        let row = MultiBufferRow(row);
12821                        if start_row < end_row && snapshot.is_line_blank(row) {
12822                            continue;
12823                        }
12824
12825                        let prefix_range = full_comment_prefixes
12826                            .iter()
12827                            .zip(prefix_trimmed_lengths.iter().copied())
12828                            .map(|(prefix, trimmed_prefix_len)| {
12829                                comment_prefix_range(
12830                                    snapshot.deref(),
12831                                    row,
12832                                    &prefix[..trimmed_prefix_len],
12833                                    &prefix[trimmed_prefix_len..],
12834                                    ignore_indent,
12835                                )
12836                            })
12837                            .max_by_key(|range| range.end.column - range.start.column)
12838                            .expect("prefixes is non-empty");
12839
12840                        if prefix_range.is_empty() {
12841                            all_selection_lines_are_comments = false;
12842                        }
12843
12844                        selection_edit_ranges.push(prefix_range);
12845                    }
12846
12847                    if all_selection_lines_are_comments {
12848                        edits.extend(
12849                            selection_edit_ranges
12850                                .iter()
12851                                .cloned()
12852                                .map(|range| (range, empty_str.clone())),
12853                        );
12854                    } else {
12855                        let min_column = selection_edit_ranges
12856                            .iter()
12857                            .map(|range| range.start.column)
12858                            .min()
12859                            .unwrap_or(0);
12860                        edits.extend(selection_edit_ranges.iter().map(|range| {
12861                            let position = Point::new(range.start.row, min_column);
12862                            (position..position, first_prefix.clone())
12863                        }));
12864                    }
12865                } else if let Some((full_comment_prefix, comment_suffix)) =
12866                    language.block_comment_delimiters()
12867                {
12868                    let comment_prefix = full_comment_prefix.trim_end_matches(' ');
12869                    let comment_prefix_whitespace = &full_comment_prefix[comment_prefix.len()..];
12870                    let prefix_range = comment_prefix_range(
12871                        snapshot.deref(),
12872                        start_row,
12873                        comment_prefix,
12874                        comment_prefix_whitespace,
12875                        ignore_indent,
12876                    );
12877                    let suffix_range = comment_suffix_range(
12878                        snapshot.deref(),
12879                        end_row,
12880                        comment_suffix.trim_start_matches(' '),
12881                        comment_suffix.starts_with(' '),
12882                    );
12883
12884                    if prefix_range.is_empty() || suffix_range.is_empty() {
12885                        edits.push((
12886                            prefix_range.start..prefix_range.start,
12887                            full_comment_prefix.clone(),
12888                        ));
12889                        edits.push((suffix_range.end..suffix_range.end, comment_suffix.clone()));
12890                        suffixes_inserted.push((end_row, comment_suffix.len()));
12891                    } else {
12892                        edits.push((prefix_range, empty_str.clone()));
12893                        edits.push((suffix_range, empty_str.clone()));
12894                    }
12895                } else {
12896                    continue;
12897                }
12898            }
12899
12900            drop(snapshot);
12901            this.buffer.update(cx, |buffer, cx| {
12902                buffer.edit(edits, None, cx);
12903            });
12904
12905            // Adjust selections so that they end before any comment suffixes that
12906            // were inserted.
12907            let mut suffixes_inserted = suffixes_inserted.into_iter().peekable();
12908            let mut selections = this.selections.all::<Point>(cx);
12909            let snapshot = this.buffer.read(cx).read(cx);
12910            for selection in &mut selections {
12911                while let Some((row, suffix_len)) = suffixes_inserted.peek().copied() {
12912                    match row.cmp(&MultiBufferRow(selection.end.row)) {
12913                        Ordering::Less => {
12914                            suffixes_inserted.next();
12915                            continue;
12916                        }
12917                        Ordering::Greater => break,
12918                        Ordering::Equal => {
12919                            if selection.end.column == snapshot.line_len(row) {
12920                                if selection.is_empty() {
12921                                    selection.start.column -= suffix_len as u32;
12922                                }
12923                                selection.end.column -= suffix_len as u32;
12924                            }
12925                            break;
12926                        }
12927                    }
12928                }
12929            }
12930
12931            drop(snapshot);
12932            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
12933                s.select(selections)
12934            });
12935
12936            let selections = this.selections.all::<Point>(cx);
12937            let selections_on_single_row = selections.windows(2).all(|selections| {
12938                selections[0].start.row == selections[1].start.row
12939                    && selections[0].end.row == selections[1].end.row
12940                    && selections[0].start.row == selections[0].end.row
12941            });
12942            let selections_selecting = selections
12943                .iter()
12944                .any(|selection| selection.start != selection.end);
12945            let advance_downwards = action.advance_downwards
12946                && selections_on_single_row
12947                && !selections_selecting
12948                && !matches!(this.mode, EditorMode::SingleLine { .. });
12949
12950            if advance_downwards {
12951                let snapshot = this.buffer.read(cx).snapshot(cx);
12952
12953                this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
12954                    s.move_cursors_with(|display_snapshot, display_point, _| {
12955                        let mut point = display_point.to_point(display_snapshot);
12956                        point.row += 1;
12957                        point = snapshot.clip_point(point, Bias::Left);
12958                        let display_point = point.to_display_point(display_snapshot);
12959                        let goal = SelectionGoal::HorizontalPosition(
12960                            display_snapshot
12961                                .x_for_display_point(display_point, text_layout_details)
12962                                .into(),
12963                        );
12964                        (display_point, goal)
12965                    })
12966                });
12967            }
12968        });
12969    }
12970
12971    pub fn select_enclosing_symbol(
12972        &mut self,
12973        _: &SelectEnclosingSymbol,
12974        window: &mut Window,
12975        cx: &mut Context<Self>,
12976    ) {
12977        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
12978
12979        let buffer = self.buffer.read(cx).snapshot(cx);
12980        let old_selections = self.selections.all::<usize>(cx).into_boxed_slice();
12981
12982        fn update_selection(
12983            selection: &Selection<usize>,
12984            buffer_snap: &MultiBufferSnapshot,
12985        ) -> Option<Selection<usize>> {
12986            let cursor = selection.head();
12987            let (_buffer_id, symbols) = buffer_snap.symbols_containing(cursor, None)?;
12988            for symbol in symbols.iter().rev() {
12989                let start = symbol.range.start.to_offset(buffer_snap);
12990                let end = symbol.range.end.to_offset(buffer_snap);
12991                let new_range = start..end;
12992                if start < selection.start || end > selection.end {
12993                    return Some(Selection {
12994                        id: selection.id,
12995                        start: new_range.start,
12996                        end: new_range.end,
12997                        goal: SelectionGoal::None,
12998                        reversed: selection.reversed,
12999                    });
13000                }
13001            }
13002            None
13003        }
13004
13005        let mut selected_larger_symbol = false;
13006        let new_selections = old_selections
13007            .iter()
13008            .map(|selection| match update_selection(selection, &buffer) {
13009                Some(new_selection) => {
13010                    if new_selection.range() != selection.range() {
13011                        selected_larger_symbol = true;
13012                    }
13013                    new_selection
13014                }
13015                None => selection.clone(),
13016            })
13017            .collect::<Vec<_>>();
13018
13019        if selected_larger_symbol {
13020            self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
13021                s.select(new_selections);
13022            });
13023        }
13024    }
13025
13026    pub fn select_larger_syntax_node(
13027        &mut self,
13028        _: &SelectLargerSyntaxNode,
13029        window: &mut Window,
13030        cx: &mut Context<Self>,
13031    ) {
13032        let Some(visible_row_count) = self.visible_row_count() else {
13033            return;
13034        };
13035        let old_selections: Box<[_]> = self.selections.all::<usize>(cx).into();
13036        if old_selections.is_empty() {
13037            return;
13038        }
13039
13040        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
13041
13042        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
13043        let buffer = self.buffer.read(cx).snapshot(cx);
13044
13045        let mut selected_larger_node = false;
13046        let mut new_selections = old_selections
13047            .iter()
13048            .map(|selection| {
13049                let old_range = selection.start..selection.end;
13050
13051                if let Some((node, _)) = buffer.syntax_ancestor(old_range.clone()) {
13052                    // manually select word at selection
13053                    if ["string_content", "inline"].contains(&node.kind()) {
13054                        let word_range = {
13055                            let display_point = buffer
13056                                .offset_to_point(old_range.start)
13057                                .to_display_point(&display_map);
13058                            let Range { start, end } =
13059                                movement::surrounding_word(&display_map, display_point);
13060                            start.to_point(&display_map).to_offset(&buffer)
13061                                ..end.to_point(&display_map).to_offset(&buffer)
13062                        };
13063                        // ignore if word is already selected
13064                        if !word_range.is_empty() && old_range != word_range {
13065                            let last_word_range = {
13066                                let display_point = buffer
13067                                    .offset_to_point(old_range.end)
13068                                    .to_display_point(&display_map);
13069                                let Range { start, end } =
13070                                    movement::surrounding_word(&display_map, display_point);
13071                                start.to_point(&display_map).to_offset(&buffer)
13072                                    ..end.to_point(&display_map).to_offset(&buffer)
13073                            };
13074                            // only select word if start and end point belongs to same word
13075                            if word_range == last_word_range {
13076                                selected_larger_node = true;
13077                                return Selection {
13078                                    id: selection.id,
13079                                    start: word_range.start,
13080                                    end: word_range.end,
13081                                    goal: SelectionGoal::None,
13082                                    reversed: selection.reversed,
13083                                };
13084                            }
13085                        }
13086                    }
13087                }
13088
13089                let mut new_range = old_range.clone();
13090                while let Some((_node, containing_range)) =
13091                    buffer.syntax_ancestor(new_range.clone())
13092                {
13093                    new_range = match containing_range {
13094                        MultiOrSingleBufferOffsetRange::Single(_) => break,
13095                        MultiOrSingleBufferOffsetRange::Multi(range) => range,
13096                    };
13097                    if !display_map.intersects_fold(new_range.start)
13098                        && !display_map.intersects_fold(new_range.end)
13099                    {
13100                        break;
13101                    }
13102                }
13103
13104                selected_larger_node |= new_range != old_range;
13105                Selection {
13106                    id: selection.id,
13107                    start: new_range.start,
13108                    end: new_range.end,
13109                    goal: SelectionGoal::None,
13110                    reversed: selection.reversed,
13111                }
13112            })
13113            .collect::<Vec<_>>();
13114
13115        if !selected_larger_node {
13116            return; // don't put this call in the history
13117        }
13118
13119        // scroll based on transformation done to the last selection created by the user
13120        let (last_old, last_new) = old_selections
13121            .last()
13122            .zip(new_selections.last().cloned())
13123            .expect("old_selections isn't empty");
13124
13125        // revert selection
13126        let is_selection_reversed = {
13127            let should_newest_selection_be_reversed = last_old.start != last_new.start;
13128            new_selections.last_mut().expect("checked above").reversed =
13129                should_newest_selection_be_reversed;
13130            should_newest_selection_be_reversed
13131        };
13132
13133        if selected_larger_node {
13134            self.select_syntax_node_history.disable_clearing = true;
13135            self.change_selections(None, window, cx, |s| {
13136                s.select(new_selections.clone());
13137            });
13138            self.select_syntax_node_history.disable_clearing = false;
13139        }
13140
13141        let start_row = last_new.start.to_display_point(&display_map).row().0;
13142        let end_row = last_new.end.to_display_point(&display_map).row().0;
13143        let selection_height = end_row - start_row + 1;
13144        let scroll_margin_rows = self.vertical_scroll_margin() as u32;
13145
13146        let fits_on_the_screen = visible_row_count >= selection_height + scroll_margin_rows * 2;
13147        let scroll_behavior = if fits_on_the_screen {
13148            self.request_autoscroll(Autoscroll::fit(), cx);
13149            SelectSyntaxNodeScrollBehavior::FitSelection
13150        } else if is_selection_reversed {
13151            self.scroll_cursor_top(&ScrollCursorTop, window, cx);
13152            SelectSyntaxNodeScrollBehavior::CursorTop
13153        } else {
13154            self.scroll_cursor_bottom(&ScrollCursorBottom, window, cx);
13155            SelectSyntaxNodeScrollBehavior::CursorBottom
13156        };
13157
13158        self.select_syntax_node_history.push((
13159            old_selections,
13160            scroll_behavior,
13161            is_selection_reversed,
13162        ));
13163    }
13164
13165    pub fn select_smaller_syntax_node(
13166        &mut self,
13167        _: &SelectSmallerSyntaxNode,
13168        window: &mut Window,
13169        cx: &mut Context<Self>,
13170    ) {
13171        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
13172
13173        if let Some((mut selections, scroll_behavior, is_selection_reversed)) =
13174            self.select_syntax_node_history.pop()
13175        {
13176            if let Some(selection) = selections.last_mut() {
13177                selection.reversed = is_selection_reversed;
13178            }
13179
13180            self.select_syntax_node_history.disable_clearing = true;
13181            self.change_selections(None, window, cx, |s| {
13182                s.select(selections.to_vec());
13183            });
13184            self.select_syntax_node_history.disable_clearing = false;
13185
13186            match scroll_behavior {
13187                SelectSyntaxNodeScrollBehavior::CursorTop => {
13188                    self.scroll_cursor_top(&ScrollCursorTop, window, cx);
13189                }
13190                SelectSyntaxNodeScrollBehavior::FitSelection => {
13191                    self.request_autoscroll(Autoscroll::fit(), cx);
13192                }
13193                SelectSyntaxNodeScrollBehavior::CursorBottom => {
13194                    self.scroll_cursor_bottom(&ScrollCursorBottom, window, cx);
13195                }
13196            }
13197        }
13198    }
13199
13200    fn refresh_runnables(&mut self, window: &mut Window, cx: &mut Context<Self>) -> Task<()> {
13201        if !EditorSettings::get_global(cx).gutter.runnables {
13202            self.clear_tasks();
13203            return Task::ready(());
13204        }
13205        let project = self.project.as_ref().map(Entity::downgrade);
13206        let task_sources = self.lsp_task_sources(cx);
13207        cx.spawn_in(window, async move |editor, cx| {
13208            cx.background_executor().timer(UPDATE_DEBOUNCE).await;
13209            let Some(project) = project.and_then(|p| p.upgrade()) else {
13210                return;
13211            };
13212            let Ok(display_snapshot) = editor.update(cx, |this, cx| {
13213                this.display_map.update(cx, |map, cx| map.snapshot(cx))
13214            }) else {
13215                return;
13216            };
13217
13218            let hide_runnables = project
13219                .update(cx, |project, cx| {
13220                    // Do not display any test indicators in non-dev server remote projects.
13221                    project.is_via_collab() && project.ssh_connection_string(cx).is_none()
13222                })
13223                .unwrap_or(true);
13224            if hide_runnables {
13225                return;
13226            }
13227            let new_rows =
13228                cx.background_spawn({
13229                    let snapshot = display_snapshot.clone();
13230                    async move {
13231                        Self::fetch_runnable_ranges(&snapshot, Anchor::min()..Anchor::max())
13232                    }
13233                })
13234                    .await;
13235            let Ok(lsp_tasks) =
13236                cx.update(|_, cx| crate::lsp_tasks(project.clone(), &task_sources, None, cx))
13237            else {
13238                return;
13239            };
13240            let lsp_tasks = lsp_tasks.await;
13241
13242            let Ok(mut lsp_tasks_by_rows) = cx.update(|_, cx| {
13243                lsp_tasks
13244                    .into_iter()
13245                    .flat_map(|(kind, tasks)| {
13246                        tasks.into_iter().filter_map(move |(location, task)| {
13247                            Some((kind.clone(), location?, task))
13248                        })
13249                    })
13250                    .fold(HashMap::default(), |mut acc, (kind, location, task)| {
13251                        let buffer = location.target.buffer;
13252                        let buffer_snapshot = buffer.read(cx).snapshot();
13253                        let offset = display_snapshot.buffer_snapshot.excerpts().find_map(
13254                            |(excerpt_id, snapshot, _)| {
13255                                if snapshot.remote_id() == buffer_snapshot.remote_id() {
13256                                    display_snapshot
13257                                        .buffer_snapshot
13258                                        .anchor_in_excerpt(excerpt_id, location.target.range.start)
13259                                } else {
13260                                    None
13261                                }
13262                            },
13263                        );
13264                        if let Some(offset) = offset {
13265                            let task_buffer_range =
13266                                location.target.range.to_point(&buffer_snapshot);
13267                            let context_buffer_range =
13268                                task_buffer_range.to_offset(&buffer_snapshot);
13269                            let context_range = BufferOffset(context_buffer_range.start)
13270                                ..BufferOffset(context_buffer_range.end);
13271
13272                            acc.entry((buffer_snapshot.remote_id(), task_buffer_range.start.row))
13273                                .or_insert_with(|| RunnableTasks {
13274                                    templates: Vec::new(),
13275                                    offset,
13276                                    column: task_buffer_range.start.column,
13277                                    extra_variables: HashMap::default(),
13278                                    context_range,
13279                                })
13280                                .templates
13281                                .push((kind, task.original_task().clone()));
13282                        }
13283
13284                        acc
13285                    })
13286            }) else {
13287                return;
13288            };
13289
13290            let rows = Self::runnable_rows(project, display_snapshot, new_rows, cx.clone());
13291            editor
13292                .update(cx, |editor, _| {
13293                    editor.clear_tasks();
13294                    for (key, mut value) in rows {
13295                        if let Some(lsp_tasks) = lsp_tasks_by_rows.remove(&key) {
13296                            value.templates.extend(lsp_tasks.templates);
13297                        }
13298
13299                        editor.insert_tasks(key, value);
13300                    }
13301                    for (key, value) in lsp_tasks_by_rows {
13302                        editor.insert_tasks(key, value);
13303                    }
13304                })
13305                .ok();
13306        })
13307    }
13308    fn fetch_runnable_ranges(
13309        snapshot: &DisplaySnapshot,
13310        range: Range<Anchor>,
13311    ) -> Vec<language::RunnableRange> {
13312        snapshot.buffer_snapshot.runnable_ranges(range).collect()
13313    }
13314
13315    fn runnable_rows(
13316        project: Entity<Project>,
13317        snapshot: DisplaySnapshot,
13318        runnable_ranges: Vec<RunnableRange>,
13319        mut cx: AsyncWindowContext,
13320    ) -> Vec<((BufferId, BufferRow), RunnableTasks)> {
13321        runnable_ranges
13322            .into_iter()
13323            .filter_map(|mut runnable| {
13324                let tasks = cx
13325                    .update(|_, cx| Self::templates_with_tags(&project, &mut runnable.runnable, cx))
13326                    .ok()?;
13327                if tasks.is_empty() {
13328                    return None;
13329                }
13330
13331                let point = runnable.run_range.start.to_point(&snapshot.buffer_snapshot);
13332
13333                let row = snapshot
13334                    .buffer_snapshot
13335                    .buffer_line_for_row(MultiBufferRow(point.row))?
13336                    .1
13337                    .start
13338                    .row;
13339
13340                let context_range =
13341                    BufferOffset(runnable.full_range.start)..BufferOffset(runnable.full_range.end);
13342                Some((
13343                    (runnable.buffer_id, row),
13344                    RunnableTasks {
13345                        templates: tasks,
13346                        offset: snapshot
13347                            .buffer_snapshot
13348                            .anchor_before(runnable.run_range.start),
13349                        context_range,
13350                        column: point.column,
13351                        extra_variables: runnable.extra_captures,
13352                    },
13353                ))
13354            })
13355            .collect()
13356    }
13357
13358    fn templates_with_tags(
13359        project: &Entity<Project>,
13360        runnable: &mut Runnable,
13361        cx: &mut App,
13362    ) -> Vec<(TaskSourceKind, TaskTemplate)> {
13363        let (inventory, worktree_id, file) = project.read_with(cx, |project, cx| {
13364            let (worktree_id, file) = project
13365                .buffer_for_id(runnable.buffer, cx)
13366                .and_then(|buffer| buffer.read(cx).file())
13367                .map(|file| (file.worktree_id(cx), file.clone()))
13368                .unzip();
13369
13370            (
13371                project.task_store().read(cx).task_inventory().cloned(),
13372                worktree_id,
13373                file,
13374            )
13375        });
13376
13377        let mut templates_with_tags = mem::take(&mut runnable.tags)
13378            .into_iter()
13379            .flat_map(|RunnableTag(tag)| {
13380                inventory
13381                    .as_ref()
13382                    .into_iter()
13383                    .flat_map(|inventory| {
13384                        inventory.read(cx).list_tasks(
13385                            file.clone(),
13386                            Some(runnable.language.clone()),
13387                            worktree_id,
13388                            cx,
13389                        )
13390                    })
13391                    .filter(move |(_, template)| {
13392                        template.tags.iter().any(|source_tag| source_tag == &tag)
13393                    })
13394            })
13395            .sorted_by_key(|(kind, _)| kind.to_owned())
13396            .collect::<Vec<_>>();
13397        if let Some((leading_tag_source, _)) = templates_with_tags.first() {
13398            // Strongest source wins; if we have worktree tag binding, prefer that to
13399            // global and language bindings;
13400            // if we have a global binding, prefer that to language binding.
13401            let first_mismatch = templates_with_tags
13402                .iter()
13403                .position(|(tag_source, _)| tag_source != leading_tag_source);
13404            if let Some(index) = first_mismatch {
13405                templates_with_tags.truncate(index);
13406            }
13407        }
13408
13409        templates_with_tags
13410    }
13411
13412    pub fn move_to_enclosing_bracket(
13413        &mut self,
13414        _: &MoveToEnclosingBracket,
13415        window: &mut Window,
13416        cx: &mut Context<Self>,
13417    ) {
13418        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
13419        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
13420            s.move_offsets_with(|snapshot, selection| {
13421                let Some(enclosing_bracket_ranges) =
13422                    snapshot.enclosing_bracket_ranges(selection.start..selection.end)
13423                else {
13424                    return;
13425                };
13426
13427                let mut best_length = usize::MAX;
13428                let mut best_inside = false;
13429                let mut best_in_bracket_range = false;
13430                let mut best_destination = None;
13431                for (open, close) in enclosing_bracket_ranges {
13432                    let close = close.to_inclusive();
13433                    let length = close.end() - open.start;
13434                    let inside = selection.start >= open.end && selection.end <= *close.start();
13435                    let in_bracket_range = open.to_inclusive().contains(&selection.head())
13436                        || close.contains(&selection.head());
13437
13438                    // If best is next to a bracket and current isn't, skip
13439                    if !in_bracket_range && best_in_bracket_range {
13440                        continue;
13441                    }
13442
13443                    // Prefer smaller lengths unless best is inside and current isn't
13444                    if length > best_length && (best_inside || !inside) {
13445                        continue;
13446                    }
13447
13448                    best_length = length;
13449                    best_inside = inside;
13450                    best_in_bracket_range = in_bracket_range;
13451                    best_destination = Some(
13452                        if close.contains(&selection.start) && close.contains(&selection.end) {
13453                            if inside { open.end } else { open.start }
13454                        } else if inside {
13455                            *close.start()
13456                        } else {
13457                            *close.end()
13458                        },
13459                    );
13460                }
13461
13462                if let Some(destination) = best_destination {
13463                    selection.collapse_to(destination, SelectionGoal::None);
13464                }
13465            })
13466        });
13467    }
13468
13469    pub fn undo_selection(
13470        &mut self,
13471        _: &UndoSelection,
13472        window: &mut Window,
13473        cx: &mut Context<Self>,
13474    ) {
13475        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
13476        self.end_selection(window, cx);
13477        self.selection_history.mode = SelectionHistoryMode::Undoing;
13478        if let Some(entry) = self.selection_history.undo_stack.pop_back() {
13479            self.change_selections(None, window, cx, |s| {
13480                s.select_anchors(entry.selections.to_vec())
13481            });
13482            self.select_next_state = entry.select_next_state;
13483            self.select_prev_state = entry.select_prev_state;
13484            self.add_selections_state = entry.add_selections_state;
13485            self.request_autoscroll(Autoscroll::newest(), cx);
13486        }
13487        self.selection_history.mode = SelectionHistoryMode::Normal;
13488    }
13489
13490    pub fn redo_selection(
13491        &mut self,
13492        _: &RedoSelection,
13493        window: &mut Window,
13494        cx: &mut Context<Self>,
13495    ) {
13496        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
13497        self.end_selection(window, cx);
13498        self.selection_history.mode = SelectionHistoryMode::Redoing;
13499        if let Some(entry) = self.selection_history.redo_stack.pop_back() {
13500            self.change_selections(None, window, cx, |s| {
13501                s.select_anchors(entry.selections.to_vec())
13502            });
13503            self.select_next_state = entry.select_next_state;
13504            self.select_prev_state = entry.select_prev_state;
13505            self.add_selections_state = entry.add_selections_state;
13506            self.request_autoscroll(Autoscroll::newest(), cx);
13507        }
13508        self.selection_history.mode = SelectionHistoryMode::Normal;
13509    }
13510
13511    pub fn expand_excerpts(
13512        &mut self,
13513        action: &ExpandExcerpts,
13514        _: &mut Window,
13515        cx: &mut Context<Self>,
13516    ) {
13517        self.expand_excerpts_for_direction(action.lines, ExpandExcerptDirection::UpAndDown, cx)
13518    }
13519
13520    pub fn expand_excerpts_down(
13521        &mut self,
13522        action: &ExpandExcerptsDown,
13523        _: &mut Window,
13524        cx: &mut Context<Self>,
13525    ) {
13526        self.expand_excerpts_for_direction(action.lines, ExpandExcerptDirection::Down, cx)
13527    }
13528
13529    pub fn expand_excerpts_up(
13530        &mut self,
13531        action: &ExpandExcerptsUp,
13532        _: &mut Window,
13533        cx: &mut Context<Self>,
13534    ) {
13535        self.expand_excerpts_for_direction(action.lines, ExpandExcerptDirection::Up, cx)
13536    }
13537
13538    pub fn expand_excerpts_for_direction(
13539        &mut self,
13540        lines: u32,
13541        direction: ExpandExcerptDirection,
13542
13543        cx: &mut Context<Self>,
13544    ) {
13545        let selections = self.selections.disjoint_anchors();
13546
13547        let lines = if lines == 0 {
13548            EditorSettings::get_global(cx).expand_excerpt_lines
13549        } else {
13550            lines
13551        };
13552
13553        self.buffer.update(cx, |buffer, cx| {
13554            let snapshot = buffer.snapshot(cx);
13555            let mut excerpt_ids = selections
13556                .iter()
13557                .flat_map(|selection| snapshot.excerpt_ids_for_range(selection.range()))
13558                .collect::<Vec<_>>();
13559            excerpt_ids.sort();
13560            excerpt_ids.dedup();
13561            buffer.expand_excerpts(excerpt_ids, lines, direction, cx)
13562        })
13563    }
13564
13565    pub fn expand_excerpt(
13566        &mut self,
13567        excerpt: ExcerptId,
13568        direction: ExpandExcerptDirection,
13569        window: &mut Window,
13570        cx: &mut Context<Self>,
13571    ) {
13572        let current_scroll_position = self.scroll_position(cx);
13573        let lines_to_expand = EditorSettings::get_global(cx).expand_excerpt_lines;
13574        let mut should_scroll_up = false;
13575
13576        if direction == ExpandExcerptDirection::Down {
13577            let multi_buffer = self.buffer.read(cx);
13578            let snapshot = multi_buffer.snapshot(cx);
13579            if let Some(buffer_id) = snapshot.buffer_id_for_excerpt(excerpt) {
13580                if let Some(buffer) = multi_buffer.buffer(buffer_id) {
13581                    if let Some(excerpt_range) = snapshot.buffer_range_for_excerpt(excerpt) {
13582                        let buffer_snapshot = buffer.read(cx).snapshot();
13583                        let excerpt_end_row =
13584                            Point::from_anchor(&excerpt_range.end, &buffer_snapshot).row;
13585                        let last_row = buffer_snapshot.max_point().row;
13586                        let lines_below = last_row.saturating_sub(excerpt_end_row);
13587                        should_scroll_up = lines_below >= lines_to_expand;
13588                    }
13589                }
13590            }
13591        }
13592
13593        self.buffer.update(cx, |buffer, cx| {
13594            buffer.expand_excerpts([excerpt], lines_to_expand, direction, cx)
13595        });
13596
13597        if should_scroll_up {
13598            let new_scroll_position =
13599                current_scroll_position + gpui::Point::new(0.0, lines_to_expand as f32);
13600            self.set_scroll_position(new_scroll_position, window, cx);
13601        }
13602    }
13603
13604    pub fn go_to_singleton_buffer_point(
13605        &mut self,
13606        point: Point,
13607        window: &mut Window,
13608        cx: &mut Context<Self>,
13609    ) {
13610        self.go_to_singleton_buffer_range(point..point, window, cx);
13611    }
13612
13613    pub fn go_to_singleton_buffer_range(
13614        &mut self,
13615        range: Range<Point>,
13616        window: &mut Window,
13617        cx: &mut Context<Self>,
13618    ) {
13619        let multibuffer = self.buffer().read(cx);
13620        let Some(buffer) = multibuffer.as_singleton() else {
13621            return;
13622        };
13623        let Some(start) = multibuffer.buffer_point_to_anchor(&buffer, range.start, cx) else {
13624            return;
13625        };
13626        let Some(end) = multibuffer.buffer_point_to_anchor(&buffer, range.end, cx) else {
13627            return;
13628        };
13629        self.change_selections(Some(Autoscroll::center()), window, cx, |s| {
13630            s.select_anchor_ranges([start..end])
13631        });
13632    }
13633
13634    pub fn go_to_diagnostic(
13635        &mut self,
13636        _: &GoToDiagnostic,
13637        window: &mut Window,
13638        cx: &mut Context<Self>,
13639    ) {
13640        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
13641        self.go_to_diagnostic_impl(Direction::Next, window, cx)
13642    }
13643
13644    pub fn go_to_prev_diagnostic(
13645        &mut self,
13646        _: &GoToPreviousDiagnostic,
13647        window: &mut Window,
13648        cx: &mut Context<Self>,
13649    ) {
13650        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
13651        self.go_to_diagnostic_impl(Direction::Prev, window, cx)
13652    }
13653
13654    pub fn go_to_diagnostic_impl(
13655        &mut self,
13656        direction: Direction,
13657        window: &mut Window,
13658        cx: &mut Context<Self>,
13659    ) {
13660        let buffer = self.buffer.read(cx).snapshot(cx);
13661        let selection = self.selections.newest::<usize>(cx);
13662
13663        let mut active_group_id = None;
13664        if let ActiveDiagnostic::Group(active_group) = &self.active_diagnostics {
13665            if active_group.active_range.start.to_offset(&buffer) == selection.start {
13666                active_group_id = Some(active_group.group_id);
13667            }
13668        }
13669
13670        fn filtered(
13671            snapshot: EditorSnapshot,
13672            diagnostics: impl Iterator<Item = DiagnosticEntry<usize>>,
13673        ) -> impl Iterator<Item = DiagnosticEntry<usize>> {
13674            diagnostics
13675                .filter(|entry| entry.range.start != entry.range.end)
13676                .filter(|entry| !entry.diagnostic.is_unnecessary)
13677                .filter(move |entry| !snapshot.intersects_fold(entry.range.start))
13678        }
13679
13680        let snapshot = self.snapshot(window, cx);
13681        let before = filtered(
13682            snapshot.clone(),
13683            buffer
13684                .diagnostics_in_range(0..selection.start)
13685                .filter(|entry| entry.range.start <= selection.start),
13686        );
13687        let after = filtered(
13688            snapshot,
13689            buffer
13690                .diagnostics_in_range(selection.start..buffer.len())
13691                .filter(|entry| entry.range.start >= selection.start),
13692        );
13693
13694        let mut found: Option<DiagnosticEntry<usize>> = None;
13695        if direction == Direction::Prev {
13696            'outer: for prev_diagnostics in [before.collect::<Vec<_>>(), after.collect::<Vec<_>>()]
13697            {
13698                for diagnostic in prev_diagnostics.into_iter().rev() {
13699                    if diagnostic.range.start != selection.start
13700                        || active_group_id
13701                            .is_some_and(|active| diagnostic.diagnostic.group_id < active)
13702                    {
13703                        found = Some(diagnostic);
13704                        break 'outer;
13705                    }
13706                }
13707            }
13708        } else {
13709            for diagnostic in after.chain(before) {
13710                if diagnostic.range.start != selection.start
13711                    || active_group_id.is_some_and(|active| diagnostic.diagnostic.group_id > active)
13712                {
13713                    found = Some(diagnostic);
13714                    break;
13715                }
13716            }
13717        }
13718        let Some(next_diagnostic) = found else {
13719            return;
13720        };
13721
13722        let Some(buffer_id) = buffer.anchor_after(next_diagnostic.range.start).buffer_id else {
13723            return;
13724        };
13725        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
13726            s.select_ranges(vec![
13727                next_diagnostic.range.start..next_diagnostic.range.start,
13728            ])
13729        });
13730        self.activate_diagnostics(buffer_id, next_diagnostic, window, cx);
13731        self.refresh_inline_completion(false, true, window, cx);
13732    }
13733
13734    pub fn go_to_next_hunk(&mut self, _: &GoToHunk, window: &mut Window, cx: &mut Context<Self>) {
13735        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
13736        let snapshot = self.snapshot(window, cx);
13737        let selection = self.selections.newest::<Point>(cx);
13738        self.go_to_hunk_before_or_after_position(
13739            &snapshot,
13740            selection.head(),
13741            Direction::Next,
13742            window,
13743            cx,
13744        );
13745    }
13746
13747    pub fn go_to_hunk_before_or_after_position(
13748        &mut self,
13749        snapshot: &EditorSnapshot,
13750        position: Point,
13751        direction: Direction,
13752        window: &mut Window,
13753        cx: &mut Context<Editor>,
13754    ) {
13755        let row = if direction == Direction::Next {
13756            self.hunk_after_position(snapshot, position)
13757                .map(|hunk| hunk.row_range.start)
13758        } else {
13759            self.hunk_before_position(snapshot, position)
13760        };
13761
13762        if let Some(row) = row {
13763            let destination = Point::new(row.0, 0);
13764            let autoscroll = Autoscroll::center();
13765
13766            self.unfold_ranges(&[destination..destination], false, false, cx);
13767            self.change_selections(Some(autoscroll), window, cx, |s| {
13768                s.select_ranges([destination..destination]);
13769            });
13770        }
13771    }
13772
13773    fn hunk_after_position(
13774        &mut self,
13775        snapshot: &EditorSnapshot,
13776        position: Point,
13777    ) -> Option<MultiBufferDiffHunk> {
13778        snapshot
13779            .buffer_snapshot
13780            .diff_hunks_in_range(position..snapshot.buffer_snapshot.max_point())
13781            .find(|hunk| hunk.row_range.start.0 > position.row)
13782            .or_else(|| {
13783                snapshot
13784                    .buffer_snapshot
13785                    .diff_hunks_in_range(Point::zero()..position)
13786                    .find(|hunk| hunk.row_range.end.0 < position.row)
13787            })
13788    }
13789
13790    fn go_to_prev_hunk(
13791        &mut self,
13792        _: &GoToPreviousHunk,
13793        window: &mut Window,
13794        cx: &mut Context<Self>,
13795    ) {
13796        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
13797        let snapshot = self.snapshot(window, cx);
13798        let selection = self.selections.newest::<Point>(cx);
13799        self.go_to_hunk_before_or_after_position(
13800            &snapshot,
13801            selection.head(),
13802            Direction::Prev,
13803            window,
13804            cx,
13805        );
13806    }
13807
13808    fn hunk_before_position(
13809        &mut self,
13810        snapshot: &EditorSnapshot,
13811        position: Point,
13812    ) -> Option<MultiBufferRow> {
13813        snapshot
13814            .buffer_snapshot
13815            .diff_hunk_before(position)
13816            .or_else(|| snapshot.buffer_snapshot.diff_hunk_before(Point::MAX))
13817    }
13818
13819    fn go_to_next_change(
13820        &mut self,
13821        _: &GoToNextChange,
13822        window: &mut Window,
13823        cx: &mut Context<Self>,
13824    ) {
13825        if let Some(selections) = self
13826            .change_list
13827            .next_change(1, Direction::Next)
13828            .map(|s| s.to_vec())
13829        {
13830            self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
13831                let map = s.display_map();
13832                s.select_display_ranges(selections.iter().map(|a| {
13833                    let point = a.to_display_point(&map);
13834                    point..point
13835                }))
13836            })
13837        }
13838    }
13839
13840    fn go_to_previous_change(
13841        &mut self,
13842        _: &GoToPreviousChange,
13843        window: &mut Window,
13844        cx: &mut Context<Self>,
13845    ) {
13846        if let Some(selections) = self
13847            .change_list
13848            .next_change(1, Direction::Prev)
13849            .map(|s| s.to_vec())
13850        {
13851            self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
13852                let map = s.display_map();
13853                s.select_display_ranges(selections.iter().map(|a| {
13854                    let point = a.to_display_point(&map);
13855                    point..point
13856                }))
13857            })
13858        }
13859    }
13860
13861    fn go_to_line<T: 'static>(
13862        &mut self,
13863        position: Anchor,
13864        highlight_color: Option<Hsla>,
13865        window: &mut Window,
13866        cx: &mut Context<Self>,
13867    ) {
13868        let snapshot = self.snapshot(window, cx).display_snapshot;
13869        let position = position.to_point(&snapshot.buffer_snapshot);
13870        let start = snapshot
13871            .buffer_snapshot
13872            .clip_point(Point::new(position.row, 0), Bias::Left);
13873        let end = start + Point::new(1, 0);
13874        let start = snapshot.buffer_snapshot.anchor_before(start);
13875        let end = snapshot.buffer_snapshot.anchor_before(end);
13876
13877        self.highlight_rows::<T>(
13878            start..end,
13879            highlight_color
13880                .unwrap_or_else(|| cx.theme().colors().editor_highlighted_line_background),
13881            Default::default(),
13882            cx,
13883        );
13884
13885        if self.buffer.read(cx).is_singleton() {
13886            self.request_autoscroll(Autoscroll::center().for_anchor(start), cx);
13887        }
13888    }
13889
13890    pub fn go_to_definition(
13891        &mut self,
13892        _: &GoToDefinition,
13893        window: &mut Window,
13894        cx: &mut Context<Self>,
13895    ) -> Task<Result<Navigated>> {
13896        let definition =
13897            self.go_to_definition_of_kind(GotoDefinitionKind::Symbol, false, window, cx);
13898        let fallback_strategy = EditorSettings::get_global(cx).go_to_definition_fallback;
13899        cx.spawn_in(window, async move |editor, cx| {
13900            if definition.await? == Navigated::Yes {
13901                return Ok(Navigated::Yes);
13902            }
13903            match fallback_strategy {
13904                GoToDefinitionFallback::None => Ok(Navigated::No),
13905                GoToDefinitionFallback::FindAllReferences => {
13906                    match editor.update_in(cx, |editor, window, cx| {
13907                        editor.find_all_references(&FindAllReferences, window, cx)
13908                    })? {
13909                        Some(references) => references.await,
13910                        None => Ok(Navigated::No),
13911                    }
13912                }
13913            }
13914        })
13915    }
13916
13917    pub fn go_to_declaration(
13918        &mut self,
13919        _: &GoToDeclaration,
13920        window: &mut Window,
13921        cx: &mut Context<Self>,
13922    ) -> Task<Result<Navigated>> {
13923        self.go_to_definition_of_kind(GotoDefinitionKind::Declaration, false, window, cx)
13924    }
13925
13926    pub fn go_to_declaration_split(
13927        &mut self,
13928        _: &GoToDeclaration,
13929        window: &mut Window,
13930        cx: &mut Context<Self>,
13931    ) -> Task<Result<Navigated>> {
13932        self.go_to_definition_of_kind(GotoDefinitionKind::Declaration, true, window, cx)
13933    }
13934
13935    pub fn go_to_implementation(
13936        &mut self,
13937        _: &GoToImplementation,
13938        window: &mut Window,
13939        cx: &mut Context<Self>,
13940    ) -> Task<Result<Navigated>> {
13941        self.go_to_definition_of_kind(GotoDefinitionKind::Implementation, false, window, cx)
13942    }
13943
13944    pub fn go_to_implementation_split(
13945        &mut self,
13946        _: &GoToImplementationSplit,
13947        window: &mut Window,
13948        cx: &mut Context<Self>,
13949    ) -> Task<Result<Navigated>> {
13950        self.go_to_definition_of_kind(GotoDefinitionKind::Implementation, true, window, cx)
13951    }
13952
13953    pub fn go_to_type_definition(
13954        &mut self,
13955        _: &GoToTypeDefinition,
13956        window: &mut Window,
13957        cx: &mut Context<Self>,
13958    ) -> Task<Result<Navigated>> {
13959        self.go_to_definition_of_kind(GotoDefinitionKind::Type, false, window, cx)
13960    }
13961
13962    pub fn go_to_definition_split(
13963        &mut self,
13964        _: &GoToDefinitionSplit,
13965        window: &mut Window,
13966        cx: &mut Context<Self>,
13967    ) -> Task<Result<Navigated>> {
13968        self.go_to_definition_of_kind(GotoDefinitionKind::Symbol, true, window, cx)
13969    }
13970
13971    pub fn go_to_type_definition_split(
13972        &mut self,
13973        _: &GoToTypeDefinitionSplit,
13974        window: &mut Window,
13975        cx: &mut Context<Self>,
13976    ) -> Task<Result<Navigated>> {
13977        self.go_to_definition_of_kind(GotoDefinitionKind::Type, true, window, cx)
13978    }
13979
13980    fn go_to_definition_of_kind(
13981        &mut self,
13982        kind: GotoDefinitionKind,
13983        split: bool,
13984        window: &mut Window,
13985        cx: &mut Context<Self>,
13986    ) -> Task<Result<Navigated>> {
13987        let Some(provider) = self.semantics_provider.clone() else {
13988            return Task::ready(Ok(Navigated::No));
13989        };
13990        let head = self.selections.newest::<usize>(cx).head();
13991        let buffer = self.buffer.read(cx);
13992        let (buffer, head) = if let Some(text_anchor) = buffer.text_anchor_for_position(head, cx) {
13993            text_anchor
13994        } else {
13995            return Task::ready(Ok(Navigated::No));
13996        };
13997
13998        let Some(definitions) = provider.definitions(&buffer, head, kind, cx) else {
13999            return Task::ready(Ok(Navigated::No));
14000        };
14001
14002        cx.spawn_in(window, async move |editor, cx| {
14003            let definitions = definitions.await?;
14004            let navigated = editor
14005                .update_in(cx, |editor, window, cx| {
14006                    editor.navigate_to_hover_links(
14007                        Some(kind),
14008                        definitions
14009                            .into_iter()
14010                            .filter(|location| {
14011                                hover_links::exclude_link_to_position(&buffer, &head, location, cx)
14012                            })
14013                            .map(HoverLink::Text)
14014                            .collect::<Vec<_>>(),
14015                        split,
14016                        window,
14017                        cx,
14018                    )
14019                })?
14020                .await?;
14021            anyhow::Ok(navigated)
14022        })
14023    }
14024
14025    pub fn open_url(&mut self, _: &OpenUrl, window: &mut Window, cx: &mut Context<Self>) {
14026        let selection = self.selections.newest_anchor();
14027        let head = selection.head();
14028        let tail = selection.tail();
14029
14030        let Some((buffer, start_position)) =
14031            self.buffer.read(cx).text_anchor_for_position(head, cx)
14032        else {
14033            return;
14034        };
14035
14036        let end_position = if head != tail {
14037            let Some((_, pos)) = self.buffer.read(cx).text_anchor_for_position(tail, cx) else {
14038                return;
14039            };
14040            Some(pos)
14041        } else {
14042            None
14043        };
14044
14045        let url_finder = cx.spawn_in(window, async move |editor, cx| {
14046            let url = if let Some(end_pos) = end_position {
14047                find_url_from_range(&buffer, start_position..end_pos, cx.clone())
14048            } else {
14049                find_url(&buffer, start_position, cx.clone()).map(|(_, url)| url)
14050            };
14051
14052            if let Some(url) = url {
14053                editor.update(cx, |_, cx| {
14054                    cx.open_url(&url);
14055                })
14056            } else {
14057                Ok(())
14058            }
14059        });
14060
14061        url_finder.detach();
14062    }
14063
14064    pub fn open_selected_filename(
14065        &mut self,
14066        _: &OpenSelectedFilename,
14067        window: &mut Window,
14068        cx: &mut Context<Self>,
14069    ) {
14070        let Some(workspace) = self.workspace() else {
14071            return;
14072        };
14073
14074        let position = self.selections.newest_anchor().head();
14075
14076        let Some((buffer, buffer_position)) =
14077            self.buffer.read(cx).text_anchor_for_position(position, cx)
14078        else {
14079            return;
14080        };
14081
14082        let project = self.project.clone();
14083
14084        cx.spawn_in(window, async move |_, cx| {
14085            let result = find_file(&buffer, project, buffer_position, cx).await;
14086
14087            if let Some((_, path)) = result {
14088                workspace
14089                    .update_in(cx, |workspace, window, cx| {
14090                        workspace.open_resolved_path(path, window, cx)
14091                    })?
14092                    .await?;
14093            }
14094            anyhow::Ok(())
14095        })
14096        .detach();
14097    }
14098
14099    pub(crate) fn navigate_to_hover_links(
14100        &mut self,
14101        kind: Option<GotoDefinitionKind>,
14102        mut definitions: Vec<HoverLink>,
14103        split: bool,
14104        window: &mut Window,
14105        cx: &mut Context<Editor>,
14106    ) -> Task<Result<Navigated>> {
14107        // If there is one definition, just open it directly
14108        if definitions.len() == 1 {
14109            let definition = definitions.pop().unwrap();
14110
14111            enum TargetTaskResult {
14112                Location(Option<Location>),
14113                AlreadyNavigated,
14114            }
14115
14116            let target_task = match definition {
14117                HoverLink::Text(link) => {
14118                    Task::ready(anyhow::Ok(TargetTaskResult::Location(Some(link.target))))
14119                }
14120                HoverLink::InlayHint(lsp_location, server_id) => {
14121                    let computation =
14122                        self.compute_target_location(lsp_location, server_id, window, cx);
14123                    cx.background_spawn(async move {
14124                        let location = computation.await?;
14125                        Ok(TargetTaskResult::Location(location))
14126                    })
14127                }
14128                HoverLink::Url(url) => {
14129                    cx.open_url(&url);
14130                    Task::ready(Ok(TargetTaskResult::AlreadyNavigated))
14131                }
14132                HoverLink::File(path) => {
14133                    if let Some(workspace) = self.workspace() {
14134                        cx.spawn_in(window, async move |_, cx| {
14135                            workspace
14136                                .update_in(cx, |workspace, window, cx| {
14137                                    workspace.open_resolved_path(path, window, cx)
14138                                })?
14139                                .await
14140                                .map(|_| TargetTaskResult::AlreadyNavigated)
14141                        })
14142                    } else {
14143                        Task::ready(Ok(TargetTaskResult::Location(None)))
14144                    }
14145                }
14146            };
14147            cx.spawn_in(window, async move |editor, cx| {
14148                let target = match target_task.await.context("target resolution task")? {
14149                    TargetTaskResult::AlreadyNavigated => return Ok(Navigated::Yes),
14150                    TargetTaskResult::Location(None) => return Ok(Navigated::No),
14151                    TargetTaskResult::Location(Some(target)) => target,
14152                };
14153
14154                editor.update_in(cx, |editor, window, cx| {
14155                    let Some(workspace) = editor.workspace() else {
14156                        return Navigated::No;
14157                    };
14158                    let pane = workspace.read(cx).active_pane().clone();
14159
14160                    let range = target.range.to_point(target.buffer.read(cx));
14161                    let range = editor.range_for_match(&range);
14162                    let range = collapse_multiline_range(range);
14163
14164                    if !split
14165                        && Some(&target.buffer) == editor.buffer.read(cx).as_singleton().as_ref()
14166                    {
14167                        editor.go_to_singleton_buffer_range(range.clone(), window, cx);
14168                    } else {
14169                        window.defer(cx, move |window, cx| {
14170                            let target_editor: Entity<Self> =
14171                                workspace.update(cx, |workspace, cx| {
14172                                    let pane = if split {
14173                                        workspace.adjacent_pane(window, cx)
14174                                    } else {
14175                                        workspace.active_pane().clone()
14176                                    };
14177
14178                                    workspace.open_project_item(
14179                                        pane,
14180                                        target.buffer.clone(),
14181                                        true,
14182                                        true,
14183                                        window,
14184                                        cx,
14185                                    )
14186                                });
14187                            target_editor.update(cx, |target_editor, cx| {
14188                                // When selecting a definition in a different buffer, disable the nav history
14189                                // to avoid creating a history entry at the previous cursor location.
14190                                pane.update(cx, |pane, _| pane.disable_history());
14191                                target_editor.go_to_singleton_buffer_range(range, window, cx);
14192                                pane.update(cx, |pane, _| pane.enable_history());
14193                            });
14194                        });
14195                    }
14196                    Navigated::Yes
14197                })
14198            })
14199        } else if !definitions.is_empty() {
14200            cx.spawn_in(window, async move |editor, cx| {
14201                let (title, location_tasks, workspace) = editor
14202                    .update_in(cx, |editor, window, cx| {
14203                        let tab_kind = match kind {
14204                            Some(GotoDefinitionKind::Implementation) => "Implementations",
14205                            _ => "Definitions",
14206                        };
14207                        let title = definitions
14208                            .iter()
14209                            .find_map(|definition| match definition {
14210                                HoverLink::Text(link) => link.origin.as_ref().map(|origin| {
14211                                    let buffer = origin.buffer.read(cx);
14212                                    format!(
14213                                        "{} for {}",
14214                                        tab_kind,
14215                                        buffer
14216                                            .text_for_range(origin.range.clone())
14217                                            .collect::<String>()
14218                                    )
14219                                }),
14220                                HoverLink::InlayHint(_, _) => None,
14221                                HoverLink::Url(_) => None,
14222                                HoverLink::File(_) => None,
14223                            })
14224                            .unwrap_or(tab_kind.to_string());
14225                        let location_tasks = definitions
14226                            .into_iter()
14227                            .map(|definition| match definition {
14228                                HoverLink::Text(link) => Task::ready(Ok(Some(link.target))),
14229                                HoverLink::InlayHint(lsp_location, server_id) => editor
14230                                    .compute_target_location(lsp_location, server_id, window, cx),
14231                                HoverLink::Url(_) => Task::ready(Ok(None)),
14232                                HoverLink::File(_) => Task::ready(Ok(None)),
14233                            })
14234                            .collect::<Vec<_>>();
14235                        (title, location_tasks, editor.workspace().clone())
14236                    })
14237                    .context("location tasks preparation")?;
14238
14239                let locations = future::join_all(location_tasks)
14240                    .await
14241                    .into_iter()
14242                    .filter_map(|location| location.transpose())
14243                    .collect::<Result<_>>()
14244                    .context("location tasks")?;
14245
14246                let Some(workspace) = workspace else {
14247                    return Ok(Navigated::No);
14248                };
14249                let opened = workspace
14250                    .update_in(cx, |workspace, window, cx| {
14251                        Self::open_locations_in_multibuffer(
14252                            workspace,
14253                            locations,
14254                            title,
14255                            split,
14256                            MultibufferSelectionMode::First,
14257                            window,
14258                            cx,
14259                        )
14260                    })
14261                    .ok();
14262
14263                anyhow::Ok(Navigated::from_bool(opened.is_some()))
14264            })
14265        } else {
14266            Task::ready(Ok(Navigated::No))
14267        }
14268    }
14269
14270    fn compute_target_location(
14271        &self,
14272        lsp_location: lsp::Location,
14273        server_id: LanguageServerId,
14274        window: &mut Window,
14275        cx: &mut Context<Self>,
14276    ) -> Task<anyhow::Result<Option<Location>>> {
14277        let Some(project) = self.project.clone() else {
14278            return Task::ready(Ok(None));
14279        };
14280
14281        cx.spawn_in(window, async move |editor, cx| {
14282            let location_task = editor.update(cx, |_, cx| {
14283                project.update(cx, |project, cx| {
14284                    let language_server_name = project
14285                        .language_server_statuses(cx)
14286                        .find(|(id, _)| server_id == *id)
14287                        .map(|(_, status)| LanguageServerName::from(status.name.as_str()));
14288                    language_server_name.map(|language_server_name| {
14289                        project.open_local_buffer_via_lsp(
14290                            lsp_location.uri.clone(),
14291                            server_id,
14292                            language_server_name,
14293                            cx,
14294                        )
14295                    })
14296                })
14297            })?;
14298            let location = match location_task {
14299                Some(task) => Some({
14300                    let target_buffer_handle = task.await.context("open local buffer")?;
14301                    let range = target_buffer_handle.update(cx, |target_buffer, _| {
14302                        let target_start = target_buffer
14303                            .clip_point_utf16(point_from_lsp(lsp_location.range.start), Bias::Left);
14304                        let target_end = target_buffer
14305                            .clip_point_utf16(point_from_lsp(lsp_location.range.end), Bias::Left);
14306                        target_buffer.anchor_after(target_start)
14307                            ..target_buffer.anchor_before(target_end)
14308                    })?;
14309                    Location {
14310                        buffer: target_buffer_handle,
14311                        range,
14312                    }
14313                }),
14314                None => None,
14315            };
14316            Ok(location)
14317        })
14318    }
14319
14320    pub fn find_all_references(
14321        &mut self,
14322        _: &FindAllReferences,
14323        window: &mut Window,
14324        cx: &mut Context<Self>,
14325    ) -> Option<Task<Result<Navigated>>> {
14326        let selection = self.selections.newest::<usize>(cx);
14327        let multi_buffer = self.buffer.read(cx);
14328        let head = selection.head();
14329
14330        let multi_buffer_snapshot = multi_buffer.snapshot(cx);
14331        let head_anchor = multi_buffer_snapshot.anchor_at(
14332            head,
14333            if head < selection.tail() {
14334                Bias::Right
14335            } else {
14336                Bias::Left
14337            },
14338        );
14339
14340        match self
14341            .find_all_references_task_sources
14342            .binary_search_by(|anchor| anchor.cmp(&head_anchor, &multi_buffer_snapshot))
14343        {
14344            Ok(_) => {
14345                log::info!(
14346                    "Ignoring repeated FindAllReferences invocation with the position of already running task"
14347                );
14348                return None;
14349            }
14350            Err(i) => {
14351                self.find_all_references_task_sources.insert(i, head_anchor);
14352            }
14353        }
14354
14355        let (buffer, head) = multi_buffer.text_anchor_for_position(head, cx)?;
14356        let workspace = self.workspace()?;
14357        let project = workspace.read(cx).project().clone();
14358        let references = project.update(cx, |project, cx| project.references(&buffer, head, cx));
14359        Some(cx.spawn_in(window, async move |editor, cx| {
14360            let _cleanup = cx.on_drop(&editor, move |editor, _| {
14361                if let Ok(i) = editor
14362                    .find_all_references_task_sources
14363                    .binary_search_by(|anchor| anchor.cmp(&head_anchor, &multi_buffer_snapshot))
14364                {
14365                    editor.find_all_references_task_sources.remove(i);
14366                }
14367            });
14368
14369            let locations = references.await?;
14370            if locations.is_empty() {
14371                return anyhow::Ok(Navigated::No);
14372            }
14373
14374            workspace.update_in(cx, |workspace, window, cx| {
14375                let title = locations
14376                    .first()
14377                    .as_ref()
14378                    .map(|location| {
14379                        let buffer = location.buffer.read(cx);
14380                        format!(
14381                            "References to `{}`",
14382                            buffer
14383                                .text_for_range(location.range.clone())
14384                                .collect::<String>()
14385                        )
14386                    })
14387                    .unwrap();
14388                Self::open_locations_in_multibuffer(
14389                    workspace,
14390                    locations,
14391                    title,
14392                    false,
14393                    MultibufferSelectionMode::First,
14394                    window,
14395                    cx,
14396                );
14397                Navigated::Yes
14398            })
14399        }))
14400    }
14401
14402    /// Opens a multibuffer with the given project locations in it
14403    pub fn open_locations_in_multibuffer(
14404        workspace: &mut Workspace,
14405        mut locations: Vec<Location>,
14406        title: String,
14407        split: bool,
14408        multibuffer_selection_mode: MultibufferSelectionMode,
14409        window: &mut Window,
14410        cx: &mut Context<Workspace>,
14411    ) {
14412        // If there are multiple definitions, open them in a multibuffer
14413        locations.sort_by_key(|location| location.buffer.read(cx).remote_id());
14414        let mut locations = locations.into_iter().peekable();
14415        let mut ranges: Vec<Range<Anchor>> = Vec::new();
14416        let capability = workspace.project().read(cx).capability();
14417
14418        let excerpt_buffer = cx.new(|cx| {
14419            let mut multibuffer = MultiBuffer::new(capability);
14420            while let Some(location) = locations.next() {
14421                let buffer = location.buffer.read(cx);
14422                let mut ranges_for_buffer = Vec::new();
14423                let range = location.range.to_point(buffer);
14424                ranges_for_buffer.push(range.clone());
14425
14426                while let Some(next_location) = locations.peek() {
14427                    if next_location.buffer == location.buffer {
14428                        ranges_for_buffer.push(next_location.range.to_point(buffer));
14429                        locations.next();
14430                    } else {
14431                        break;
14432                    }
14433                }
14434
14435                ranges_for_buffer.sort_by_key(|range| (range.start, Reverse(range.end)));
14436                let (new_ranges, _) = multibuffer.set_excerpts_for_path(
14437                    PathKey::for_buffer(&location.buffer, cx),
14438                    location.buffer.clone(),
14439                    ranges_for_buffer,
14440                    DEFAULT_MULTIBUFFER_CONTEXT,
14441                    cx,
14442                );
14443                ranges.extend(new_ranges)
14444            }
14445
14446            multibuffer.with_title(title)
14447        });
14448
14449        let editor = cx.new(|cx| {
14450            Editor::for_multibuffer(
14451                excerpt_buffer,
14452                Some(workspace.project().clone()),
14453                window,
14454                cx,
14455            )
14456        });
14457        editor.update(cx, |editor, cx| {
14458            match multibuffer_selection_mode {
14459                MultibufferSelectionMode::First => {
14460                    if let Some(first_range) = ranges.first() {
14461                        editor.change_selections(None, window, cx, |selections| {
14462                            selections.clear_disjoint();
14463                            selections.select_anchor_ranges(std::iter::once(first_range.clone()));
14464                        });
14465                    }
14466                    editor.highlight_background::<Self>(
14467                        &ranges,
14468                        |theme| theme.editor_highlighted_line_background,
14469                        cx,
14470                    );
14471                }
14472                MultibufferSelectionMode::All => {
14473                    editor.change_selections(None, window, cx, |selections| {
14474                        selections.clear_disjoint();
14475                        selections.select_anchor_ranges(ranges);
14476                    });
14477                }
14478            }
14479            editor.register_buffers_with_language_servers(cx);
14480        });
14481
14482        let item = Box::new(editor);
14483        let item_id = item.item_id();
14484
14485        if split {
14486            workspace.split_item(SplitDirection::Right, item.clone(), window, cx);
14487        } else {
14488            if PreviewTabsSettings::get_global(cx).enable_preview_from_code_navigation {
14489                let (preview_item_id, preview_item_idx) =
14490                    workspace.active_pane().update(cx, |pane, _| {
14491                        (pane.preview_item_id(), pane.preview_item_idx())
14492                    });
14493
14494                workspace.add_item_to_active_pane(item.clone(), preview_item_idx, true, window, cx);
14495
14496                if let Some(preview_item_id) = preview_item_id {
14497                    workspace.active_pane().update(cx, |pane, cx| {
14498                        pane.remove_item(preview_item_id, false, false, window, cx);
14499                    });
14500                }
14501            } else {
14502                workspace.add_item_to_active_pane(item.clone(), None, true, window, cx);
14503            }
14504        }
14505        workspace.active_pane().update(cx, |pane, cx| {
14506            pane.set_preview_item_id(Some(item_id), cx);
14507        });
14508    }
14509
14510    pub fn rename(
14511        &mut self,
14512        _: &Rename,
14513        window: &mut Window,
14514        cx: &mut Context<Self>,
14515    ) -> Option<Task<Result<()>>> {
14516        use language::ToOffset as _;
14517
14518        let provider = self.semantics_provider.clone()?;
14519        let selection = self.selections.newest_anchor().clone();
14520        let (cursor_buffer, cursor_buffer_position) = self
14521            .buffer
14522            .read(cx)
14523            .text_anchor_for_position(selection.head(), cx)?;
14524        let (tail_buffer, cursor_buffer_position_end) = self
14525            .buffer
14526            .read(cx)
14527            .text_anchor_for_position(selection.tail(), cx)?;
14528        if tail_buffer != cursor_buffer {
14529            return None;
14530        }
14531
14532        let snapshot = cursor_buffer.read(cx).snapshot();
14533        let cursor_buffer_offset = cursor_buffer_position.to_offset(&snapshot);
14534        let cursor_buffer_offset_end = cursor_buffer_position_end.to_offset(&snapshot);
14535        let prepare_rename = provider
14536            .range_for_rename(&cursor_buffer, cursor_buffer_position, cx)
14537            .unwrap_or_else(|| Task::ready(Ok(None)));
14538        drop(snapshot);
14539
14540        Some(cx.spawn_in(window, async move |this, cx| {
14541            let rename_range = if let Some(range) = prepare_rename.await? {
14542                Some(range)
14543            } else {
14544                this.update(cx, |this, cx| {
14545                    let buffer = this.buffer.read(cx).snapshot(cx);
14546                    let mut buffer_highlights = this
14547                        .document_highlights_for_position(selection.head(), &buffer)
14548                        .filter(|highlight| {
14549                            highlight.start.excerpt_id == selection.head().excerpt_id
14550                                && highlight.end.excerpt_id == selection.head().excerpt_id
14551                        });
14552                    buffer_highlights
14553                        .next()
14554                        .map(|highlight| highlight.start.text_anchor..highlight.end.text_anchor)
14555                })?
14556            };
14557            if let Some(rename_range) = rename_range {
14558                this.update_in(cx, |this, window, cx| {
14559                    let snapshot = cursor_buffer.read(cx).snapshot();
14560                    let rename_buffer_range = rename_range.to_offset(&snapshot);
14561                    let cursor_offset_in_rename_range =
14562                        cursor_buffer_offset.saturating_sub(rename_buffer_range.start);
14563                    let cursor_offset_in_rename_range_end =
14564                        cursor_buffer_offset_end.saturating_sub(rename_buffer_range.start);
14565
14566                    this.take_rename(false, window, cx);
14567                    let buffer = this.buffer.read(cx).read(cx);
14568                    let cursor_offset = selection.head().to_offset(&buffer);
14569                    let rename_start = cursor_offset.saturating_sub(cursor_offset_in_rename_range);
14570                    let rename_end = rename_start + rename_buffer_range.len();
14571                    let range = buffer.anchor_before(rename_start)..buffer.anchor_after(rename_end);
14572                    let mut old_highlight_id = None;
14573                    let old_name: Arc<str> = buffer
14574                        .chunks(rename_start..rename_end, true)
14575                        .map(|chunk| {
14576                            if old_highlight_id.is_none() {
14577                                old_highlight_id = chunk.syntax_highlight_id;
14578                            }
14579                            chunk.text
14580                        })
14581                        .collect::<String>()
14582                        .into();
14583
14584                    drop(buffer);
14585
14586                    // Position the selection in the rename editor so that it matches the current selection.
14587                    this.show_local_selections = false;
14588                    let rename_editor = cx.new(|cx| {
14589                        let mut editor = Editor::single_line(window, cx);
14590                        editor.buffer.update(cx, |buffer, cx| {
14591                            buffer.edit([(0..0, old_name.clone())], None, cx)
14592                        });
14593                        let rename_selection_range = match cursor_offset_in_rename_range
14594                            .cmp(&cursor_offset_in_rename_range_end)
14595                        {
14596                            Ordering::Equal => {
14597                                editor.select_all(&SelectAll, window, cx);
14598                                return editor;
14599                            }
14600                            Ordering::Less => {
14601                                cursor_offset_in_rename_range..cursor_offset_in_rename_range_end
14602                            }
14603                            Ordering::Greater => {
14604                                cursor_offset_in_rename_range_end..cursor_offset_in_rename_range
14605                            }
14606                        };
14607                        if rename_selection_range.end > old_name.len() {
14608                            editor.select_all(&SelectAll, window, cx);
14609                        } else {
14610                            editor.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
14611                                s.select_ranges([rename_selection_range]);
14612                            });
14613                        }
14614                        editor
14615                    });
14616                    cx.subscribe(&rename_editor, |_, _, e: &EditorEvent, cx| {
14617                        if e == &EditorEvent::Focused {
14618                            cx.emit(EditorEvent::FocusedIn)
14619                        }
14620                    })
14621                    .detach();
14622
14623                    let write_highlights =
14624                        this.clear_background_highlights::<DocumentHighlightWrite>(cx);
14625                    let read_highlights =
14626                        this.clear_background_highlights::<DocumentHighlightRead>(cx);
14627                    let ranges = write_highlights
14628                        .iter()
14629                        .flat_map(|(_, ranges)| ranges.iter())
14630                        .chain(read_highlights.iter().flat_map(|(_, ranges)| ranges.iter()))
14631                        .cloned()
14632                        .collect();
14633
14634                    this.highlight_text::<Rename>(
14635                        ranges,
14636                        HighlightStyle {
14637                            fade_out: Some(0.6),
14638                            ..Default::default()
14639                        },
14640                        cx,
14641                    );
14642                    let rename_focus_handle = rename_editor.focus_handle(cx);
14643                    window.focus(&rename_focus_handle);
14644                    let block_id = this.insert_blocks(
14645                        [BlockProperties {
14646                            style: BlockStyle::Flex,
14647                            placement: BlockPlacement::Below(range.start),
14648                            height: Some(1),
14649                            render: Arc::new({
14650                                let rename_editor = rename_editor.clone();
14651                                move |cx: &mut BlockContext| {
14652                                    let mut text_style = cx.editor_style.text.clone();
14653                                    if let Some(highlight_style) = old_highlight_id
14654                                        .and_then(|h| h.style(&cx.editor_style.syntax))
14655                                    {
14656                                        text_style = text_style.highlight(highlight_style);
14657                                    }
14658                                    div()
14659                                        .block_mouse_down()
14660                                        .pl(cx.anchor_x)
14661                                        .child(EditorElement::new(
14662                                            &rename_editor,
14663                                            EditorStyle {
14664                                                background: cx.theme().system().transparent,
14665                                                local_player: cx.editor_style.local_player,
14666                                                text: text_style,
14667                                                scrollbar_width: cx.editor_style.scrollbar_width,
14668                                                syntax: cx.editor_style.syntax.clone(),
14669                                                status: cx.editor_style.status.clone(),
14670                                                inlay_hints_style: HighlightStyle {
14671                                                    font_weight: Some(FontWeight::BOLD),
14672                                                    ..make_inlay_hints_style(cx.app)
14673                                                },
14674                                                inline_completion_styles: make_suggestion_styles(
14675                                                    cx.app,
14676                                                ),
14677                                                ..EditorStyle::default()
14678                                            },
14679                                        ))
14680                                        .into_any_element()
14681                                }
14682                            }),
14683                            priority: 0,
14684                            render_in_minimap: true,
14685                        }],
14686                        Some(Autoscroll::fit()),
14687                        cx,
14688                    )[0];
14689                    this.pending_rename = Some(RenameState {
14690                        range,
14691                        old_name,
14692                        editor: rename_editor,
14693                        block_id,
14694                    });
14695                })?;
14696            }
14697
14698            Ok(())
14699        }))
14700    }
14701
14702    pub fn confirm_rename(
14703        &mut self,
14704        _: &ConfirmRename,
14705        window: &mut Window,
14706        cx: &mut Context<Self>,
14707    ) -> Option<Task<Result<()>>> {
14708        let rename = self.take_rename(false, window, cx)?;
14709        let workspace = self.workspace()?.downgrade();
14710        let (buffer, start) = self
14711            .buffer
14712            .read(cx)
14713            .text_anchor_for_position(rename.range.start, cx)?;
14714        let (end_buffer, _) = self
14715            .buffer
14716            .read(cx)
14717            .text_anchor_for_position(rename.range.end, cx)?;
14718        if buffer != end_buffer {
14719            return None;
14720        }
14721
14722        let old_name = rename.old_name;
14723        let new_name = rename.editor.read(cx).text(cx);
14724
14725        let rename = self.semantics_provider.as_ref()?.perform_rename(
14726            &buffer,
14727            start,
14728            new_name.clone(),
14729            cx,
14730        )?;
14731
14732        Some(cx.spawn_in(window, async move |editor, cx| {
14733            let project_transaction = rename.await?;
14734            Self::open_project_transaction(
14735                &editor,
14736                workspace,
14737                project_transaction,
14738                format!("Rename: {}{}", old_name, new_name),
14739                cx,
14740            )
14741            .await?;
14742
14743            editor.update(cx, |editor, cx| {
14744                editor.refresh_document_highlights(cx);
14745            })?;
14746            Ok(())
14747        }))
14748    }
14749
14750    fn take_rename(
14751        &mut self,
14752        moving_cursor: bool,
14753        window: &mut Window,
14754        cx: &mut Context<Self>,
14755    ) -> Option<RenameState> {
14756        let rename = self.pending_rename.take()?;
14757        if rename.editor.focus_handle(cx).is_focused(window) {
14758            window.focus(&self.focus_handle);
14759        }
14760
14761        self.remove_blocks(
14762            [rename.block_id].into_iter().collect(),
14763            Some(Autoscroll::fit()),
14764            cx,
14765        );
14766        self.clear_highlights::<Rename>(cx);
14767        self.show_local_selections = true;
14768
14769        if moving_cursor {
14770            let cursor_in_rename_editor = rename.editor.update(cx, |editor, cx| {
14771                editor.selections.newest::<usize>(cx).head()
14772            });
14773
14774            // Update the selection to match the position of the selection inside
14775            // the rename editor.
14776            let snapshot = self.buffer.read(cx).read(cx);
14777            let rename_range = rename.range.to_offset(&snapshot);
14778            let cursor_in_editor = snapshot
14779                .clip_offset(rename_range.start + cursor_in_rename_editor, Bias::Left)
14780                .min(rename_range.end);
14781            drop(snapshot);
14782
14783            self.change_selections(None, window, cx, |s| {
14784                s.select_ranges(vec![cursor_in_editor..cursor_in_editor])
14785            });
14786        } else {
14787            self.refresh_document_highlights(cx);
14788        }
14789
14790        Some(rename)
14791    }
14792
14793    pub fn pending_rename(&self) -> Option<&RenameState> {
14794        self.pending_rename.as_ref()
14795    }
14796
14797    fn format(
14798        &mut self,
14799        _: &Format,
14800        window: &mut Window,
14801        cx: &mut Context<Self>,
14802    ) -> Option<Task<Result<()>>> {
14803        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
14804
14805        let project = match &self.project {
14806            Some(project) => project.clone(),
14807            None => return None,
14808        };
14809
14810        Some(self.perform_format(
14811            project,
14812            FormatTrigger::Manual,
14813            FormatTarget::Buffers,
14814            window,
14815            cx,
14816        ))
14817    }
14818
14819    fn format_selections(
14820        &mut self,
14821        _: &FormatSelections,
14822        window: &mut Window,
14823        cx: &mut Context<Self>,
14824    ) -> Option<Task<Result<()>>> {
14825        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
14826
14827        let project = match &self.project {
14828            Some(project) => project.clone(),
14829            None => return None,
14830        };
14831
14832        let ranges = self
14833            .selections
14834            .all_adjusted(cx)
14835            .into_iter()
14836            .map(|selection| selection.range())
14837            .collect_vec();
14838
14839        Some(self.perform_format(
14840            project,
14841            FormatTrigger::Manual,
14842            FormatTarget::Ranges(ranges),
14843            window,
14844            cx,
14845        ))
14846    }
14847
14848    fn perform_format(
14849        &mut self,
14850        project: Entity<Project>,
14851        trigger: FormatTrigger,
14852        target: FormatTarget,
14853        window: &mut Window,
14854        cx: &mut Context<Self>,
14855    ) -> Task<Result<()>> {
14856        let buffer = self.buffer.clone();
14857        let (buffers, target) = match target {
14858            FormatTarget::Buffers => {
14859                let mut buffers = buffer.read(cx).all_buffers();
14860                if trigger == FormatTrigger::Save {
14861                    buffers.retain(|buffer| buffer.read(cx).is_dirty());
14862                }
14863                (buffers, LspFormatTarget::Buffers)
14864            }
14865            FormatTarget::Ranges(selection_ranges) => {
14866                let multi_buffer = buffer.read(cx);
14867                let snapshot = multi_buffer.read(cx);
14868                let mut buffers = HashSet::default();
14869                let mut buffer_id_to_ranges: BTreeMap<BufferId, Vec<Range<text::Anchor>>> =
14870                    BTreeMap::new();
14871                for selection_range in selection_ranges {
14872                    for (buffer, buffer_range, _) in
14873                        snapshot.range_to_buffer_ranges(selection_range)
14874                    {
14875                        let buffer_id = buffer.remote_id();
14876                        let start = buffer.anchor_before(buffer_range.start);
14877                        let end = buffer.anchor_after(buffer_range.end);
14878                        buffers.insert(multi_buffer.buffer(buffer_id).unwrap());
14879                        buffer_id_to_ranges
14880                            .entry(buffer_id)
14881                            .and_modify(|buffer_ranges| buffer_ranges.push(start..end))
14882                            .or_insert_with(|| vec![start..end]);
14883                    }
14884                }
14885                (buffers, LspFormatTarget::Ranges(buffer_id_to_ranges))
14886            }
14887        };
14888
14889        let transaction_id_prev = buffer.read_with(cx, |b, cx| b.last_transaction_id(cx));
14890        let selections_prev = transaction_id_prev
14891            .and_then(|transaction_id_prev| {
14892                // default to selections as they were after the last edit, if we have them,
14893                // instead of how they are now.
14894                // This will make it so that editing, moving somewhere else, formatting, then undoing the format
14895                // will take you back to where you made the last edit, instead of staying where you scrolled
14896                self.selection_history
14897                    .transaction(transaction_id_prev)
14898                    .map(|t| t.0.clone())
14899            })
14900            .unwrap_or_else(|| {
14901                log::info!("Failed to determine selections from before format. Falling back to selections when format was initiated");
14902                self.selections.disjoint_anchors()
14903            });
14904
14905        let mut timeout = cx.background_executor().timer(FORMAT_TIMEOUT).fuse();
14906        let format = project.update(cx, |project, cx| {
14907            project.format(buffers, target, true, trigger, cx)
14908        });
14909
14910        cx.spawn_in(window, async move |editor, cx| {
14911            let transaction = futures::select_biased! {
14912                transaction = format.log_err().fuse() => transaction,
14913                () = timeout => {
14914                    log::warn!("timed out waiting for formatting");
14915                    None
14916                }
14917            };
14918
14919            buffer
14920                .update(cx, |buffer, cx| {
14921                    if let Some(transaction) = transaction {
14922                        if !buffer.is_singleton() {
14923                            buffer.push_transaction(&transaction.0, cx);
14924                        }
14925                    }
14926                    cx.notify();
14927                })
14928                .ok();
14929
14930            if let Some(transaction_id_now) =
14931                buffer.read_with(cx, |b, cx| b.last_transaction_id(cx))?
14932            {
14933                let has_new_transaction = transaction_id_prev != Some(transaction_id_now);
14934                if has_new_transaction {
14935                    _ = editor.update(cx, |editor, _| {
14936                        editor
14937                            .selection_history
14938                            .insert_transaction(transaction_id_now, selections_prev);
14939                    });
14940                }
14941            }
14942
14943            Ok(())
14944        })
14945    }
14946
14947    fn organize_imports(
14948        &mut self,
14949        _: &OrganizeImports,
14950        window: &mut Window,
14951        cx: &mut Context<Self>,
14952    ) -> Option<Task<Result<()>>> {
14953        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
14954        let project = match &self.project {
14955            Some(project) => project.clone(),
14956            None => return None,
14957        };
14958        Some(self.perform_code_action_kind(
14959            project,
14960            CodeActionKind::SOURCE_ORGANIZE_IMPORTS,
14961            window,
14962            cx,
14963        ))
14964    }
14965
14966    fn perform_code_action_kind(
14967        &mut self,
14968        project: Entity<Project>,
14969        kind: CodeActionKind,
14970        window: &mut Window,
14971        cx: &mut Context<Self>,
14972    ) -> Task<Result<()>> {
14973        let buffer = self.buffer.clone();
14974        let buffers = buffer.read(cx).all_buffers();
14975        let mut timeout = cx.background_executor().timer(CODE_ACTION_TIMEOUT).fuse();
14976        let apply_action = project.update(cx, |project, cx| {
14977            project.apply_code_action_kind(buffers, kind, true, cx)
14978        });
14979        cx.spawn_in(window, async move |_, cx| {
14980            let transaction = futures::select_biased! {
14981                () = timeout => {
14982                    log::warn!("timed out waiting for executing code action");
14983                    None
14984                }
14985                transaction = apply_action.log_err().fuse() => transaction,
14986            };
14987            buffer
14988                .update(cx, |buffer, cx| {
14989                    // check if we need this
14990                    if let Some(transaction) = transaction {
14991                        if !buffer.is_singleton() {
14992                            buffer.push_transaction(&transaction.0, cx);
14993                        }
14994                    }
14995                    cx.notify();
14996                })
14997                .ok();
14998            Ok(())
14999        })
15000    }
15001
15002    fn restart_language_server(
15003        &mut self,
15004        _: &RestartLanguageServer,
15005        _: &mut Window,
15006        cx: &mut Context<Self>,
15007    ) {
15008        if let Some(project) = self.project.clone() {
15009            self.buffer.update(cx, |multi_buffer, cx| {
15010                project.update(cx, |project, cx| {
15011                    project.restart_language_servers_for_buffers(
15012                        multi_buffer.all_buffers().into_iter().collect(),
15013                        cx,
15014                    );
15015                });
15016            })
15017        }
15018    }
15019
15020    fn stop_language_server(
15021        &mut self,
15022        _: &StopLanguageServer,
15023        _: &mut Window,
15024        cx: &mut Context<Self>,
15025    ) {
15026        if let Some(project) = self.project.clone() {
15027            self.buffer.update(cx, |multi_buffer, cx| {
15028                project.update(cx, |project, cx| {
15029                    project.stop_language_servers_for_buffers(
15030                        multi_buffer.all_buffers().into_iter().collect(),
15031                        cx,
15032                    );
15033                    cx.emit(project::Event::RefreshInlayHints);
15034                });
15035            });
15036        }
15037    }
15038
15039    fn cancel_language_server_work(
15040        workspace: &mut Workspace,
15041        _: &actions::CancelLanguageServerWork,
15042        _: &mut Window,
15043        cx: &mut Context<Workspace>,
15044    ) {
15045        let project = workspace.project();
15046        let buffers = workspace
15047            .active_item(cx)
15048            .and_then(|item| item.act_as::<Editor>(cx))
15049            .map_or(HashSet::default(), |editor| {
15050                editor.read(cx).buffer.read(cx).all_buffers()
15051            });
15052        project.update(cx, |project, cx| {
15053            project.cancel_language_server_work_for_buffers(buffers, cx);
15054        });
15055    }
15056
15057    fn show_character_palette(
15058        &mut self,
15059        _: &ShowCharacterPalette,
15060        window: &mut Window,
15061        _: &mut Context<Self>,
15062    ) {
15063        window.show_character_palette();
15064    }
15065
15066    fn refresh_active_diagnostics(&mut self, cx: &mut Context<Editor>) {
15067        if self.mode.is_minimap() {
15068            return;
15069        }
15070
15071        if let ActiveDiagnostic::Group(active_diagnostics) = &mut self.active_diagnostics {
15072            let buffer = self.buffer.read(cx).snapshot(cx);
15073            let primary_range_start = active_diagnostics.active_range.start.to_offset(&buffer);
15074            let primary_range_end = active_diagnostics.active_range.end.to_offset(&buffer);
15075            let is_valid = buffer
15076                .diagnostics_in_range::<usize>(primary_range_start..primary_range_end)
15077                .any(|entry| {
15078                    entry.diagnostic.is_primary
15079                        && !entry.range.is_empty()
15080                        && entry.range.start == primary_range_start
15081                        && entry.diagnostic.message == active_diagnostics.active_message
15082                });
15083
15084            if !is_valid {
15085                self.dismiss_diagnostics(cx);
15086            }
15087        }
15088    }
15089
15090    pub fn active_diagnostic_group(&self) -> Option<&ActiveDiagnosticGroup> {
15091        match &self.active_diagnostics {
15092            ActiveDiagnostic::Group(group) => Some(group),
15093            _ => None,
15094        }
15095    }
15096
15097    pub fn set_all_diagnostics_active(&mut self, cx: &mut Context<Self>) {
15098        self.dismiss_diagnostics(cx);
15099        self.active_diagnostics = ActiveDiagnostic::All;
15100    }
15101
15102    fn activate_diagnostics(
15103        &mut self,
15104        buffer_id: BufferId,
15105        diagnostic: DiagnosticEntry<usize>,
15106        window: &mut Window,
15107        cx: &mut Context<Self>,
15108    ) {
15109        if matches!(self.active_diagnostics, ActiveDiagnostic::All) {
15110            return;
15111        }
15112        self.dismiss_diagnostics(cx);
15113        let snapshot = self.snapshot(window, cx);
15114        let buffer = self.buffer.read(cx).snapshot(cx);
15115        let Some(renderer) = GlobalDiagnosticRenderer::global(cx) else {
15116            return;
15117        };
15118
15119        let diagnostic_group = buffer
15120            .diagnostic_group(buffer_id, diagnostic.diagnostic.group_id)
15121            .collect::<Vec<_>>();
15122
15123        let blocks =
15124            renderer.render_group(diagnostic_group, buffer_id, snapshot, cx.weak_entity(), cx);
15125
15126        let blocks = self.display_map.update(cx, |display_map, cx| {
15127            display_map.insert_blocks(blocks, cx).into_iter().collect()
15128        });
15129        self.active_diagnostics = ActiveDiagnostic::Group(ActiveDiagnosticGroup {
15130            active_range: buffer.anchor_before(diagnostic.range.start)
15131                ..buffer.anchor_after(diagnostic.range.end),
15132            active_message: diagnostic.diagnostic.message.clone(),
15133            group_id: diagnostic.diagnostic.group_id,
15134            blocks,
15135        });
15136        cx.notify();
15137    }
15138
15139    fn dismiss_diagnostics(&mut self, cx: &mut Context<Self>) {
15140        if matches!(self.active_diagnostics, ActiveDiagnostic::All) {
15141            return;
15142        };
15143
15144        let prev = mem::replace(&mut self.active_diagnostics, ActiveDiagnostic::None);
15145        if let ActiveDiagnostic::Group(group) = prev {
15146            self.display_map.update(cx, |display_map, cx| {
15147                display_map.remove_blocks(group.blocks, cx);
15148            });
15149            cx.notify();
15150        }
15151    }
15152
15153    /// Disable inline diagnostics rendering for this editor.
15154    pub fn disable_inline_diagnostics(&mut self) {
15155        self.inline_diagnostics_enabled = false;
15156        self.inline_diagnostics_update = Task::ready(());
15157        self.inline_diagnostics.clear();
15158    }
15159
15160    pub fn diagnostics_enabled(&self) -> bool {
15161        self.mode.is_full()
15162    }
15163
15164    pub fn inline_diagnostics_enabled(&self) -> bool {
15165        self.diagnostics_enabled() && self.inline_diagnostics_enabled
15166    }
15167
15168    pub fn show_inline_diagnostics(&self) -> bool {
15169        self.show_inline_diagnostics
15170    }
15171
15172    pub fn toggle_inline_diagnostics(
15173        &mut self,
15174        _: &ToggleInlineDiagnostics,
15175        window: &mut Window,
15176        cx: &mut Context<Editor>,
15177    ) {
15178        self.show_inline_diagnostics = !self.show_inline_diagnostics;
15179        self.refresh_inline_diagnostics(false, window, cx);
15180    }
15181
15182    pub fn set_max_diagnostics_severity(&mut self, severity: DiagnosticSeverity, cx: &mut App) {
15183        self.diagnostics_max_severity = severity;
15184        self.display_map.update(cx, |display_map, _| {
15185            display_map.diagnostics_max_severity = self.diagnostics_max_severity;
15186        });
15187    }
15188
15189    pub fn toggle_diagnostics(
15190        &mut self,
15191        _: &ToggleDiagnostics,
15192        window: &mut Window,
15193        cx: &mut Context<Editor>,
15194    ) {
15195        if !self.diagnostics_enabled() {
15196            return;
15197        }
15198
15199        let new_severity = if self.diagnostics_max_severity == DiagnosticSeverity::Off {
15200            EditorSettings::get_global(cx)
15201                .diagnostics_max_severity
15202                .filter(|severity| severity != &DiagnosticSeverity::Off)
15203                .unwrap_or(DiagnosticSeverity::Hint)
15204        } else {
15205            DiagnosticSeverity::Off
15206        };
15207        self.set_max_diagnostics_severity(new_severity, cx);
15208        if self.diagnostics_max_severity == DiagnosticSeverity::Off {
15209            self.active_diagnostics = ActiveDiagnostic::None;
15210            self.inline_diagnostics_update = Task::ready(());
15211            self.inline_diagnostics.clear();
15212        } else {
15213            self.refresh_inline_diagnostics(false, window, cx);
15214        }
15215
15216        cx.notify();
15217    }
15218
15219    pub fn toggle_minimap(
15220        &mut self,
15221        _: &ToggleMinimap,
15222        window: &mut Window,
15223        cx: &mut Context<Editor>,
15224    ) {
15225        if self.supports_minimap(cx) {
15226            self.set_minimap_visibility(self.minimap_visibility.toggle_visibility(), window, cx);
15227        }
15228    }
15229
15230    fn refresh_inline_diagnostics(
15231        &mut self,
15232        debounce: bool,
15233        window: &mut Window,
15234        cx: &mut Context<Self>,
15235    ) {
15236        let max_severity = ProjectSettings::get_global(cx)
15237            .diagnostics
15238            .inline
15239            .max_severity
15240            .unwrap_or(self.diagnostics_max_severity);
15241
15242        if self.mode.is_minimap()
15243            || !self.inline_diagnostics_enabled()
15244            || !self.show_inline_diagnostics
15245            || max_severity == DiagnosticSeverity::Off
15246        {
15247            self.inline_diagnostics_update = Task::ready(());
15248            self.inline_diagnostics.clear();
15249            return;
15250        }
15251
15252        let debounce_ms = ProjectSettings::get_global(cx)
15253            .diagnostics
15254            .inline
15255            .update_debounce_ms;
15256        let debounce = if debounce && debounce_ms > 0 {
15257            Some(Duration::from_millis(debounce_ms))
15258        } else {
15259            None
15260        };
15261        self.inline_diagnostics_update = cx.spawn_in(window, async move |editor, cx| {
15262            let editor = editor.upgrade().unwrap();
15263
15264            if let Some(debounce) = debounce {
15265                cx.background_executor().timer(debounce).await;
15266            }
15267            let Some(snapshot) = editor
15268                .update(cx, |editor, cx| editor.buffer().read(cx).snapshot(cx))
15269                .ok()
15270            else {
15271                return;
15272            };
15273
15274            let new_inline_diagnostics = cx
15275                .background_spawn(async move {
15276                    let mut inline_diagnostics = Vec::<(Anchor, InlineDiagnostic)>::new();
15277                    for diagnostic_entry in snapshot.diagnostics_in_range(0..snapshot.len()) {
15278                        let message = diagnostic_entry
15279                            .diagnostic
15280                            .message
15281                            .split_once('\n')
15282                            .map(|(line, _)| line)
15283                            .map(SharedString::new)
15284                            .unwrap_or_else(|| {
15285                                SharedString::from(diagnostic_entry.diagnostic.message)
15286                            });
15287                        let start_anchor = snapshot.anchor_before(diagnostic_entry.range.start);
15288                        let (Ok(i) | Err(i)) = inline_diagnostics
15289                            .binary_search_by(|(probe, _)| probe.cmp(&start_anchor, &snapshot));
15290                        inline_diagnostics.insert(
15291                            i,
15292                            (
15293                                start_anchor,
15294                                InlineDiagnostic {
15295                                    message,
15296                                    group_id: diagnostic_entry.diagnostic.group_id,
15297                                    start: diagnostic_entry.range.start.to_point(&snapshot),
15298                                    is_primary: diagnostic_entry.diagnostic.is_primary,
15299                                    severity: diagnostic_entry.diagnostic.severity,
15300                                },
15301                            ),
15302                        );
15303                    }
15304                    inline_diagnostics
15305                })
15306                .await;
15307
15308            editor
15309                .update(cx, |editor, cx| {
15310                    editor.inline_diagnostics = new_inline_diagnostics;
15311                    cx.notify();
15312                })
15313                .ok();
15314        });
15315    }
15316
15317    pub fn set_selections_from_remote(
15318        &mut self,
15319        selections: Vec<Selection<Anchor>>,
15320        pending_selection: Option<Selection<Anchor>>,
15321        window: &mut Window,
15322        cx: &mut Context<Self>,
15323    ) {
15324        let old_cursor_position = self.selections.newest_anchor().head();
15325        self.selections.change_with(cx, |s| {
15326            s.select_anchors(selections);
15327            if let Some(pending_selection) = pending_selection {
15328                s.set_pending(pending_selection, SelectMode::Character);
15329            } else {
15330                s.clear_pending();
15331            }
15332        });
15333        self.selections_did_change(false, &old_cursor_position, true, window, cx);
15334    }
15335
15336    fn push_to_selection_history(&mut self) {
15337        self.selection_history.push(SelectionHistoryEntry {
15338            selections: self.selections.disjoint_anchors(),
15339            select_next_state: self.select_next_state.clone(),
15340            select_prev_state: self.select_prev_state.clone(),
15341            add_selections_state: self.add_selections_state.clone(),
15342        });
15343    }
15344
15345    pub fn transact(
15346        &mut self,
15347        window: &mut Window,
15348        cx: &mut Context<Self>,
15349        update: impl FnOnce(&mut Self, &mut Window, &mut Context<Self>),
15350    ) -> Option<TransactionId> {
15351        self.start_transaction_at(Instant::now(), window, cx);
15352        update(self, window, cx);
15353        self.end_transaction_at(Instant::now(), cx)
15354    }
15355
15356    pub fn start_transaction_at(
15357        &mut self,
15358        now: Instant,
15359        window: &mut Window,
15360        cx: &mut Context<Self>,
15361    ) {
15362        self.end_selection(window, cx);
15363        if let Some(tx_id) = self
15364            .buffer
15365            .update(cx, |buffer, cx| buffer.start_transaction_at(now, cx))
15366        {
15367            self.selection_history
15368                .insert_transaction(tx_id, self.selections.disjoint_anchors());
15369            cx.emit(EditorEvent::TransactionBegun {
15370                transaction_id: tx_id,
15371            })
15372        }
15373    }
15374
15375    pub fn end_transaction_at(
15376        &mut self,
15377        now: Instant,
15378        cx: &mut Context<Self>,
15379    ) -> Option<TransactionId> {
15380        if let Some(transaction_id) = self
15381            .buffer
15382            .update(cx, |buffer, cx| buffer.end_transaction_at(now, cx))
15383        {
15384            if let Some((_, end_selections)) =
15385                self.selection_history.transaction_mut(transaction_id)
15386            {
15387                *end_selections = Some(self.selections.disjoint_anchors());
15388            } else {
15389                log::error!("unexpectedly ended a transaction that wasn't started by this editor");
15390            }
15391
15392            cx.emit(EditorEvent::Edited { transaction_id });
15393            Some(transaction_id)
15394        } else {
15395            None
15396        }
15397    }
15398
15399    pub fn set_mark(&mut self, _: &actions::SetMark, window: &mut Window, cx: &mut Context<Self>) {
15400        if self.selection_mark_mode {
15401            self.change_selections(None, window, cx, |s| {
15402                s.move_with(|_, sel| {
15403                    sel.collapse_to(sel.head(), SelectionGoal::None);
15404                });
15405            })
15406        }
15407        self.selection_mark_mode = true;
15408        cx.notify();
15409    }
15410
15411    pub fn swap_selection_ends(
15412        &mut self,
15413        _: &actions::SwapSelectionEnds,
15414        window: &mut Window,
15415        cx: &mut Context<Self>,
15416    ) {
15417        self.change_selections(None, window, cx, |s| {
15418            s.move_with(|_, sel| {
15419                if sel.start != sel.end {
15420                    sel.reversed = !sel.reversed
15421                }
15422            });
15423        });
15424        self.request_autoscroll(Autoscroll::newest(), cx);
15425        cx.notify();
15426    }
15427
15428    pub fn toggle_fold(
15429        &mut self,
15430        _: &actions::ToggleFold,
15431        window: &mut Window,
15432        cx: &mut Context<Self>,
15433    ) {
15434        if self.is_singleton(cx) {
15435            let selection = self.selections.newest::<Point>(cx);
15436
15437            let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
15438            let range = if selection.is_empty() {
15439                let point = selection.head().to_display_point(&display_map);
15440                let start = DisplayPoint::new(point.row(), 0).to_point(&display_map);
15441                let end = DisplayPoint::new(point.row(), display_map.line_len(point.row()))
15442                    .to_point(&display_map);
15443                start..end
15444            } else {
15445                selection.range()
15446            };
15447            if display_map.folds_in_range(range).next().is_some() {
15448                self.unfold_lines(&Default::default(), window, cx)
15449            } else {
15450                self.fold(&Default::default(), window, cx)
15451            }
15452        } else {
15453            let multi_buffer_snapshot = self.buffer.read(cx).snapshot(cx);
15454            let buffer_ids: HashSet<_> = self
15455                .selections
15456                .disjoint_anchor_ranges()
15457                .flat_map(|range| multi_buffer_snapshot.buffer_ids_for_range(range))
15458                .collect();
15459
15460            let should_unfold = buffer_ids
15461                .iter()
15462                .any(|buffer_id| self.is_buffer_folded(*buffer_id, cx));
15463
15464            for buffer_id in buffer_ids {
15465                if should_unfold {
15466                    self.unfold_buffer(buffer_id, cx);
15467                } else {
15468                    self.fold_buffer(buffer_id, cx);
15469                }
15470            }
15471        }
15472    }
15473
15474    pub fn toggle_fold_recursive(
15475        &mut self,
15476        _: &actions::ToggleFoldRecursive,
15477        window: &mut Window,
15478        cx: &mut Context<Self>,
15479    ) {
15480        let selection = self.selections.newest::<Point>(cx);
15481
15482        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
15483        let range = if selection.is_empty() {
15484            let point = selection.head().to_display_point(&display_map);
15485            let start = DisplayPoint::new(point.row(), 0).to_point(&display_map);
15486            let end = DisplayPoint::new(point.row(), display_map.line_len(point.row()))
15487                .to_point(&display_map);
15488            start..end
15489        } else {
15490            selection.range()
15491        };
15492        if display_map.folds_in_range(range).next().is_some() {
15493            self.unfold_recursive(&Default::default(), window, cx)
15494        } else {
15495            self.fold_recursive(&Default::default(), window, cx)
15496        }
15497    }
15498
15499    pub fn fold(&mut self, _: &actions::Fold, window: &mut Window, cx: &mut Context<Self>) {
15500        if self.is_singleton(cx) {
15501            let mut to_fold = Vec::new();
15502            let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
15503            let selections = self.selections.all_adjusted(cx);
15504
15505            for selection in selections {
15506                let range = selection.range().sorted();
15507                let buffer_start_row = range.start.row;
15508
15509                if range.start.row != range.end.row {
15510                    let mut found = false;
15511                    let mut row = range.start.row;
15512                    while row <= range.end.row {
15513                        if let Some(crease) = display_map.crease_for_buffer_row(MultiBufferRow(row))
15514                        {
15515                            found = true;
15516                            row = crease.range().end.row + 1;
15517                            to_fold.push(crease);
15518                        } else {
15519                            row += 1
15520                        }
15521                    }
15522                    if found {
15523                        continue;
15524                    }
15525                }
15526
15527                for row in (0..=range.start.row).rev() {
15528                    if let Some(crease) = display_map.crease_for_buffer_row(MultiBufferRow(row)) {
15529                        if crease.range().end.row >= buffer_start_row {
15530                            to_fold.push(crease);
15531                            if row <= range.start.row {
15532                                break;
15533                            }
15534                        }
15535                    }
15536                }
15537            }
15538
15539            self.fold_creases(to_fold, true, window, cx);
15540        } else {
15541            let multi_buffer_snapshot = self.buffer.read(cx).snapshot(cx);
15542            let buffer_ids = self
15543                .selections
15544                .disjoint_anchor_ranges()
15545                .flat_map(|range| multi_buffer_snapshot.buffer_ids_for_range(range))
15546                .collect::<HashSet<_>>();
15547            for buffer_id in buffer_ids {
15548                self.fold_buffer(buffer_id, cx);
15549            }
15550        }
15551    }
15552
15553    fn fold_at_level(
15554        &mut self,
15555        fold_at: &FoldAtLevel,
15556        window: &mut Window,
15557        cx: &mut Context<Self>,
15558    ) {
15559        if !self.buffer.read(cx).is_singleton() {
15560            return;
15561        }
15562
15563        let fold_at_level = fold_at.0;
15564        let snapshot = self.buffer.read(cx).snapshot(cx);
15565        let mut to_fold = Vec::new();
15566        let mut stack = vec![(0, snapshot.max_row().0, 1)];
15567
15568        while let Some((mut start_row, end_row, current_level)) = stack.pop() {
15569            while start_row < end_row {
15570                match self
15571                    .snapshot(window, cx)
15572                    .crease_for_buffer_row(MultiBufferRow(start_row))
15573                {
15574                    Some(crease) => {
15575                        let nested_start_row = crease.range().start.row + 1;
15576                        let nested_end_row = crease.range().end.row;
15577
15578                        if current_level < fold_at_level {
15579                            stack.push((nested_start_row, nested_end_row, current_level + 1));
15580                        } else if current_level == fold_at_level {
15581                            to_fold.push(crease);
15582                        }
15583
15584                        start_row = nested_end_row + 1;
15585                    }
15586                    None => start_row += 1,
15587                }
15588            }
15589        }
15590
15591        self.fold_creases(to_fold, true, window, cx);
15592    }
15593
15594    pub fn fold_all(&mut self, _: &actions::FoldAll, window: &mut Window, cx: &mut Context<Self>) {
15595        if self.buffer.read(cx).is_singleton() {
15596            let mut fold_ranges = Vec::new();
15597            let snapshot = self.buffer.read(cx).snapshot(cx);
15598
15599            for row in 0..snapshot.max_row().0 {
15600                if let Some(foldable_range) = self
15601                    .snapshot(window, cx)
15602                    .crease_for_buffer_row(MultiBufferRow(row))
15603                {
15604                    fold_ranges.push(foldable_range);
15605                }
15606            }
15607
15608            self.fold_creases(fold_ranges, true, window, cx);
15609        } else {
15610            self.toggle_fold_multiple_buffers = cx.spawn_in(window, async move |editor, cx| {
15611                editor
15612                    .update_in(cx, |editor, _, cx| {
15613                        for buffer_id in editor.buffer.read(cx).excerpt_buffer_ids() {
15614                            editor.fold_buffer(buffer_id, cx);
15615                        }
15616                    })
15617                    .ok();
15618            });
15619        }
15620    }
15621
15622    pub fn fold_function_bodies(
15623        &mut self,
15624        _: &actions::FoldFunctionBodies,
15625        window: &mut Window,
15626        cx: &mut Context<Self>,
15627    ) {
15628        let snapshot = self.buffer.read(cx).snapshot(cx);
15629
15630        let ranges = snapshot
15631            .text_object_ranges(0..snapshot.len(), TreeSitterOptions::default())
15632            .filter_map(|(range, obj)| (obj == TextObject::InsideFunction).then_some(range))
15633            .collect::<Vec<_>>();
15634
15635        let creases = ranges
15636            .into_iter()
15637            .map(|range| Crease::simple(range, self.display_map.read(cx).fold_placeholder.clone()))
15638            .collect();
15639
15640        self.fold_creases(creases, true, window, cx);
15641    }
15642
15643    pub fn fold_recursive(
15644        &mut self,
15645        _: &actions::FoldRecursive,
15646        window: &mut Window,
15647        cx: &mut Context<Self>,
15648    ) {
15649        let mut to_fold = Vec::new();
15650        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
15651        let selections = self.selections.all_adjusted(cx);
15652
15653        for selection in selections {
15654            let range = selection.range().sorted();
15655            let buffer_start_row = range.start.row;
15656
15657            if range.start.row != range.end.row {
15658                let mut found = false;
15659                for row in range.start.row..=range.end.row {
15660                    if let Some(crease) = display_map.crease_for_buffer_row(MultiBufferRow(row)) {
15661                        found = true;
15662                        to_fold.push(crease);
15663                    }
15664                }
15665                if found {
15666                    continue;
15667                }
15668            }
15669
15670            for row in (0..=range.start.row).rev() {
15671                if let Some(crease) = display_map.crease_for_buffer_row(MultiBufferRow(row)) {
15672                    if crease.range().end.row >= buffer_start_row {
15673                        to_fold.push(crease);
15674                    } else {
15675                        break;
15676                    }
15677                }
15678            }
15679        }
15680
15681        self.fold_creases(to_fold, true, window, cx);
15682    }
15683
15684    pub fn fold_at(
15685        &mut self,
15686        buffer_row: MultiBufferRow,
15687        window: &mut Window,
15688        cx: &mut Context<Self>,
15689    ) {
15690        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
15691
15692        if let Some(crease) = display_map.crease_for_buffer_row(buffer_row) {
15693            let autoscroll = self
15694                .selections
15695                .all::<Point>(cx)
15696                .iter()
15697                .any(|selection| crease.range().overlaps(&selection.range()));
15698
15699            self.fold_creases(vec![crease], autoscroll, window, cx);
15700        }
15701    }
15702
15703    pub fn unfold_lines(&mut self, _: &UnfoldLines, _window: &mut Window, cx: &mut Context<Self>) {
15704        if self.is_singleton(cx) {
15705            let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
15706            let buffer = &display_map.buffer_snapshot;
15707            let selections = self.selections.all::<Point>(cx);
15708            let ranges = selections
15709                .iter()
15710                .map(|s| {
15711                    let range = s.display_range(&display_map).sorted();
15712                    let mut start = range.start.to_point(&display_map);
15713                    let mut end = range.end.to_point(&display_map);
15714                    start.column = 0;
15715                    end.column = buffer.line_len(MultiBufferRow(end.row));
15716                    start..end
15717                })
15718                .collect::<Vec<_>>();
15719
15720            self.unfold_ranges(&ranges, true, true, cx);
15721        } else {
15722            let multi_buffer_snapshot = self.buffer.read(cx).snapshot(cx);
15723            let buffer_ids = self
15724                .selections
15725                .disjoint_anchor_ranges()
15726                .flat_map(|range| multi_buffer_snapshot.buffer_ids_for_range(range))
15727                .collect::<HashSet<_>>();
15728            for buffer_id in buffer_ids {
15729                self.unfold_buffer(buffer_id, cx);
15730            }
15731        }
15732    }
15733
15734    pub fn unfold_recursive(
15735        &mut self,
15736        _: &UnfoldRecursive,
15737        _window: &mut Window,
15738        cx: &mut Context<Self>,
15739    ) {
15740        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
15741        let selections = self.selections.all::<Point>(cx);
15742        let ranges = selections
15743            .iter()
15744            .map(|s| {
15745                let mut range = s.display_range(&display_map).sorted();
15746                *range.start.column_mut() = 0;
15747                *range.end.column_mut() = display_map.line_len(range.end.row());
15748                let start = range.start.to_point(&display_map);
15749                let end = range.end.to_point(&display_map);
15750                start..end
15751            })
15752            .collect::<Vec<_>>();
15753
15754        self.unfold_ranges(&ranges, true, true, cx);
15755    }
15756
15757    pub fn unfold_at(
15758        &mut self,
15759        buffer_row: MultiBufferRow,
15760        _window: &mut Window,
15761        cx: &mut Context<Self>,
15762    ) {
15763        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
15764
15765        let intersection_range = Point::new(buffer_row.0, 0)
15766            ..Point::new(
15767                buffer_row.0,
15768                display_map.buffer_snapshot.line_len(buffer_row),
15769            );
15770
15771        let autoscroll = self
15772            .selections
15773            .all::<Point>(cx)
15774            .iter()
15775            .any(|selection| RangeExt::overlaps(&selection.range(), &intersection_range));
15776
15777        self.unfold_ranges(&[intersection_range], true, autoscroll, cx);
15778    }
15779
15780    pub fn unfold_all(
15781        &mut self,
15782        _: &actions::UnfoldAll,
15783        _window: &mut Window,
15784        cx: &mut Context<Self>,
15785    ) {
15786        if self.buffer.read(cx).is_singleton() {
15787            let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
15788            self.unfold_ranges(&[0..display_map.buffer_snapshot.len()], true, true, cx);
15789        } else {
15790            self.toggle_fold_multiple_buffers = cx.spawn(async move |editor, cx| {
15791                editor
15792                    .update(cx, |editor, cx| {
15793                        for buffer_id in editor.buffer.read(cx).excerpt_buffer_ids() {
15794                            editor.unfold_buffer(buffer_id, cx);
15795                        }
15796                    })
15797                    .ok();
15798            });
15799        }
15800    }
15801
15802    pub fn fold_selected_ranges(
15803        &mut self,
15804        _: &FoldSelectedRanges,
15805        window: &mut Window,
15806        cx: &mut Context<Self>,
15807    ) {
15808        let selections = self.selections.all_adjusted(cx);
15809        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
15810        let ranges = selections
15811            .into_iter()
15812            .map(|s| Crease::simple(s.range(), display_map.fold_placeholder.clone()))
15813            .collect::<Vec<_>>();
15814        self.fold_creases(ranges, true, window, cx);
15815    }
15816
15817    pub fn fold_ranges<T: ToOffset + Clone>(
15818        &mut self,
15819        ranges: Vec<Range<T>>,
15820        auto_scroll: bool,
15821        window: &mut Window,
15822        cx: &mut Context<Self>,
15823    ) {
15824        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
15825        let ranges = ranges
15826            .into_iter()
15827            .map(|r| Crease::simple(r, display_map.fold_placeholder.clone()))
15828            .collect::<Vec<_>>();
15829        self.fold_creases(ranges, auto_scroll, window, cx);
15830    }
15831
15832    pub fn fold_creases<T: ToOffset + Clone>(
15833        &mut self,
15834        creases: Vec<Crease<T>>,
15835        auto_scroll: bool,
15836        _window: &mut Window,
15837        cx: &mut Context<Self>,
15838    ) {
15839        if creases.is_empty() {
15840            return;
15841        }
15842
15843        let mut buffers_affected = HashSet::default();
15844        let multi_buffer = self.buffer().read(cx);
15845        for crease in &creases {
15846            if let Some((_, buffer, _)) =
15847                multi_buffer.excerpt_containing(crease.range().start.clone(), cx)
15848            {
15849                buffers_affected.insert(buffer.read(cx).remote_id());
15850            };
15851        }
15852
15853        self.display_map.update(cx, |map, cx| map.fold(creases, cx));
15854
15855        if auto_scroll {
15856            self.request_autoscroll(Autoscroll::fit(), cx);
15857        }
15858
15859        cx.notify();
15860
15861        self.scrollbar_marker_state.dirty = true;
15862        self.folds_did_change(cx);
15863    }
15864
15865    /// Removes any folds whose ranges intersect any of the given ranges.
15866    pub fn unfold_ranges<T: ToOffset + Clone>(
15867        &mut self,
15868        ranges: &[Range<T>],
15869        inclusive: bool,
15870        auto_scroll: bool,
15871        cx: &mut Context<Self>,
15872    ) {
15873        self.remove_folds_with(ranges, auto_scroll, cx, |map, cx| {
15874            map.unfold_intersecting(ranges.iter().cloned(), inclusive, cx)
15875        });
15876        self.folds_did_change(cx);
15877    }
15878
15879    pub fn fold_buffer(&mut self, buffer_id: BufferId, cx: &mut Context<Self>) {
15880        if self.buffer().read(cx).is_singleton() || self.is_buffer_folded(buffer_id, cx) {
15881            return;
15882        }
15883        let folded_excerpts = self.buffer().read(cx).excerpts_for_buffer(buffer_id, cx);
15884        self.display_map.update(cx, |display_map, cx| {
15885            display_map.fold_buffers([buffer_id], cx)
15886        });
15887        cx.emit(EditorEvent::BufferFoldToggled {
15888            ids: folded_excerpts.iter().map(|&(id, _)| id).collect(),
15889            folded: true,
15890        });
15891        cx.notify();
15892    }
15893
15894    pub fn unfold_buffer(&mut self, buffer_id: BufferId, cx: &mut Context<Self>) {
15895        if self.buffer().read(cx).is_singleton() || !self.is_buffer_folded(buffer_id, cx) {
15896            return;
15897        }
15898        let unfolded_excerpts = self.buffer().read(cx).excerpts_for_buffer(buffer_id, cx);
15899        self.display_map.update(cx, |display_map, cx| {
15900            display_map.unfold_buffers([buffer_id], cx);
15901        });
15902        cx.emit(EditorEvent::BufferFoldToggled {
15903            ids: unfolded_excerpts.iter().map(|&(id, _)| id).collect(),
15904            folded: false,
15905        });
15906        cx.notify();
15907    }
15908
15909    pub fn is_buffer_folded(&self, buffer: BufferId, cx: &App) -> bool {
15910        self.display_map.read(cx).is_buffer_folded(buffer)
15911    }
15912
15913    pub fn folded_buffers<'a>(&self, cx: &'a App) -> &'a HashSet<BufferId> {
15914        self.display_map.read(cx).folded_buffers()
15915    }
15916
15917    pub fn disable_header_for_buffer(&mut self, buffer_id: BufferId, cx: &mut Context<Self>) {
15918        self.display_map.update(cx, |display_map, cx| {
15919            display_map.disable_header_for_buffer(buffer_id, cx);
15920        });
15921        cx.notify();
15922    }
15923
15924    /// Removes any folds with the given ranges.
15925    pub fn remove_folds_with_type<T: ToOffset + Clone>(
15926        &mut self,
15927        ranges: &[Range<T>],
15928        type_id: TypeId,
15929        auto_scroll: bool,
15930        cx: &mut Context<Self>,
15931    ) {
15932        self.remove_folds_with(ranges, auto_scroll, cx, |map, cx| {
15933            map.remove_folds_with_type(ranges.iter().cloned(), type_id, cx)
15934        });
15935        self.folds_did_change(cx);
15936    }
15937
15938    fn remove_folds_with<T: ToOffset + Clone>(
15939        &mut self,
15940        ranges: &[Range<T>],
15941        auto_scroll: bool,
15942        cx: &mut Context<Self>,
15943        update: impl FnOnce(&mut DisplayMap, &mut Context<DisplayMap>),
15944    ) {
15945        if ranges.is_empty() {
15946            return;
15947        }
15948
15949        let mut buffers_affected = HashSet::default();
15950        let multi_buffer = self.buffer().read(cx);
15951        for range in ranges {
15952            if let Some((_, buffer, _)) = multi_buffer.excerpt_containing(range.start.clone(), cx) {
15953                buffers_affected.insert(buffer.read(cx).remote_id());
15954            };
15955        }
15956
15957        self.display_map.update(cx, update);
15958
15959        if auto_scroll {
15960            self.request_autoscroll(Autoscroll::fit(), cx);
15961        }
15962
15963        cx.notify();
15964        self.scrollbar_marker_state.dirty = true;
15965        self.active_indent_guides_state.dirty = true;
15966    }
15967
15968    pub fn update_fold_widths(
15969        &mut self,
15970        widths: impl IntoIterator<Item = (FoldId, Pixels)>,
15971        cx: &mut Context<Self>,
15972    ) -> bool {
15973        self.display_map
15974            .update(cx, |map, cx| map.update_fold_widths(widths, cx))
15975    }
15976
15977    pub fn default_fold_placeholder(&self, cx: &App) -> FoldPlaceholder {
15978        self.display_map.read(cx).fold_placeholder.clone()
15979    }
15980
15981    pub fn set_expand_all_diff_hunks(&mut self, cx: &mut App) {
15982        self.buffer.update(cx, |buffer, cx| {
15983            buffer.set_all_diff_hunks_expanded(cx);
15984        });
15985    }
15986
15987    pub fn expand_all_diff_hunks(
15988        &mut self,
15989        _: &ExpandAllDiffHunks,
15990        _window: &mut Window,
15991        cx: &mut Context<Self>,
15992    ) {
15993        self.buffer.update(cx, |buffer, cx| {
15994            buffer.expand_diff_hunks(vec![Anchor::min()..Anchor::max()], cx)
15995        });
15996    }
15997
15998    pub fn toggle_selected_diff_hunks(
15999        &mut self,
16000        _: &ToggleSelectedDiffHunks,
16001        _window: &mut Window,
16002        cx: &mut Context<Self>,
16003    ) {
16004        let ranges: Vec<_> = self.selections.disjoint.iter().map(|s| s.range()).collect();
16005        self.toggle_diff_hunks_in_ranges(ranges, cx);
16006    }
16007
16008    pub fn diff_hunks_in_ranges<'a>(
16009        &'a self,
16010        ranges: &'a [Range<Anchor>],
16011        buffer: &'a MultiBufferSnapshot,
16012    ) -> impl 'a + Iterator<Item = MultiBufferDiffHunk> {
16013        ranges.iter().flat_map(move |range| {
16014            let end_excerpt_id = range.end.excerpt_id;
16015            let range = range.to_point(buffer);
16016            let mut peek_end = range.end;
16017            if range.end.row < buffer.max_row().0 {
16018                peek_end = Point::new(range.end.row + 1, 0);
16019            }
16020            buffer
16021                .diff_hunks_in_range(range.start..peek_end)
16022                .filter(move |hunk| hunk.excerpt_id.cmp(&end_excerpt_id, buffer).is_le())
16023        })
16024    }
16025
16026    pub fn has_stageable_diff_hunks_in_ranges(
16027        &self,
16028        ranges: &[Range<Anchor>],
16029        snapshot: &MultiBufferSnapshot,
16030    ) -> bool {
16031        let mut hunks = self.diff_hunks_in_ranges(ranges, &snapshot);
16032        hunks.any(|hunk| hunk.status().has_secondary_hunk())
16033    }
16034
16035    pub fn toggle_staged_selected_diff_hunks(
16036        &mut self,
16037        _: &::git::ToggleStaged,
16038        _: &mut Window,
16039        cx: &mut Context<Self>,
16040    ) {
16041        let snapshot = self.buffer.read(cx).snapshot(cx);
16042        let ranges: Vec<_> = self.selections.disjoint.iter().map(|s| s.range()).collect();
16043        let stage = self.has_stageable_diff_hunks_in_ranges(&ranges, &snapshot);
16044        self.stage_or_unstage_diff_hunks(stage, ranges, cx);
16045    }
16046
16047    pub fn set_render_diff_hunk_controls(
16048        &mut self,
16049        render_diff_hunk_controls: RenderDiffHunkControlsFn,
16050        cx: &mut Context<Self>,
16051    ) {
16052        self.render_diff_hunk_controls = render_diff_hunk_controls;
16053        cx.notify();
16054    }
16055
16056    pub fn stage_and_next(
16057        &mut self,
16058        _: &::git::StageAndNext,
16059        window: &mut Window,
16060        cx: &mut Context<Self>,
16061    ) {
16062        self.do_stage_or_unstage_and_next(true, window, cx);
16063    }
16064
16065    pub fn unstage_and_next(
16066        &mut self,
16067        _: &::git::UnstageAndNext,
16068        window: &mut Window,
16069        cx: &mut Context<Self>,
16070    ) {
16071        self.do_stage_or_unstage_and_next(false, window, cx);
16072    }
16073
16074    pub fn stage_or_unstage_diff_hunks(
16075        &mut self,
16076        stage: bool,
16077        ranges: Vec<Range<Anchor>>,
16078        cx: &mut Context<Self>,
16079    ) {
16080        let task = self.save_buffers_for_ranges_if_needed(&ranges, cx);
16081        cx.spawn(async move |this, cx| {
16082            task.await?;
16083            this.update(cx, |this, cx| {
16084                let snapshot = this.buffer.read(cx).snapshot(cx);
16085                let chunk_by = this
16086                    .diff_hunks_in_ranges(&ranges, &snapshot)
16087                    .chunk_by(|hunk| hunk.buffer_id);
16088                for (buffer_id, hunks) in &chunk_by {
16089                    this.do_stage_or_unstage(stage, buffer_id, hunks, cx);
16090                }
16091            })
16092        })
16093        .detach_and_log_err(cx);
16094    }
16095
16096    fn save_buffers_for_ranges_if_needed(
16097        &mut self,
16098        ranges: &[Range<Anchor>],
16099        cx: &mut Context<Editor>,
16100    ) -> Task<Result<()>> {
16101        let multibuffer = self.buffer.read(cx);
16102        let snapshot = multibuffer.read(cx);
16103        let buffer_ids: HashSet<_> = ranges
16104            .iter()
16105            .flat_map(|range| snapshot.buffer_ids_for_range(range.clone()))
16106            .collect();
16107        drop(snapshot);
16108
16109        let mut buffers = HashSet::default();
16110        for buffer_id in buffer_ids {
16111            if let Some(buffer_entity) = multibuffer.buffer(buffer_id) {
16112                let buffer = buffer_entity.read(cx);
16113                if buffer.file().is_some_and(|file| file.disk_state().exists()) && buffer.is_dirty()
16114                {
16115                    buffers.insert(buffer_entity);
16116                }
16117            }
16118        }
16119
16120        if let Some(project) = &self.project {
16121            project.update(cx, |project, cx| project.save_buffers(buffers, cx))
16122        } else {
16123            Task::ready(Ok(()))
16124        }
16125    }
16126
16127    fn do_stage_or_unstage_and_next(
16128        &mut self,
16129        stage: bool,
16130        window: &mut Window,
16131        cx: &mut Context<Self>,
16132    ) {
16133        let ranges = self.selections.disjoint_anchor_ranges().collect::<Vec<_>>();
16134
16135        if ranges.iter().any(|range| range.start != range.end) {
16136            self.stage_or_unstage_diff_hunks(stage, ranges, cx);
16137            return;
16138        }
16139
16140        self.stage_or_unstage_diff_hunks(stage, ranges, cx);
16141        let snapshot = self.snapshot(window, cx);
16142        let position = self.selections.newest::<Point>(cx).head();
16143        let mut row = snapshot
16144            .buffer_snapshot
16145            .diff_hunks_in_range(position..snapshot.buffer_snapshot.max_point())
16146            .find(|hunk| hunk.row_range.start.0 > position.row)
16147            .map(|hunk| hunk.row_range.start);
16148
16149        let all_diff_hunks_expanded = self.buffer().read(cx).all_diff_hunks_expanded();
16150        // Outside of the project diff editor, wrap around to the beginning.
16151        if !all_diff_hunks_expanded {
16152            row = row.or_else(|| {
16153                snapshot
16154                    .buffer_snapshot
16155                    .diff_hunks_in_range(Point::zero()..position)
16156                    .find(|hunk| hunk.row_range.end.0 < position.row)
16157                    .map(|hunk| hunk.row_range.start)
16158            });
16159        }
16160
16161        if let Some(row) = row {
16162            let destination = Point::new(row.0, 0);
16163            let autoscroll = Autoscroll::center();
16164
16165            self.unfold_ranges(&[destination..destination], false, false, cx);
16166            self.change_selections(Some(autoscroll), window, cx, |s| {
16167                s.select_ranges([destination..destination]);
16168            });
16169        }
16170    }
16171
16172    fn do_stage_or_unstage(
16173        &self,
16174        stage: bool,
16175        buffer_id: BufferId,
16176        hunks: impl Iterator<Item = MultiBufferDiffHunk>,
16177        cx: &mut App,
16178    ) -> Option<()> {
16179        let project = self.project.as_ref()?;
16180        let buffer = project.read(cx).buffer_for_id(buffer_id, cx)?;
16181        let diff = self.buffer.read(cx).diff_for(buffer_id)?;
16182        let buffer_snapshot = buffer.read(cx).snapshot();
16183        let file_exists = buffer_snapshot
16184            .file()
16185            .is_some_and(|file| file.disk_state().exists());
16186        diff.update(cx, |diff, cx| {
16187            diff.stage_or_unstage_hunks(
16188                stage,
16189                &hunks
16190                    .map(|hunk| buffer_diff::DiffHunk {
16191                        buffer_range: hunk.buffer_range,
16192                        diff_base_byte_range: hunk.diff_base_byte_range,
16193                        secondary_status: hunk.secondary_status,
16194                        range: Point::zero()..Point::zero(), // unused
16195                    })
16196                    .collect::<Vec<_>>(),
16197                &buffer_snapshot,
16198                file_exists,
16199                cx,
16200            )
16201        });
16202        None
16203    }
16204
16205    pub fn expand_selected_diff_hunks(&mut self, cx: &mut Context<Self>) {
16206        let ranges: Vec<_> = self.selections.disjoint.iter().map(|s| s.range()).collect();
16207        self.buffer
16208            .update(cx, |buffer, cx| buffer.expand_diff_hunks(ranges, cx))
16209    }
16210
16211    pub fn clear_expanded_diff_hunks(&mut self, cx: &mut Context<Self>) -> bool {
16212        self.buffer.update(cx, |buffer, cx| {
16213            let ranges = vec![Anchor::min()..Anchor::max()];
16214            if !buffer.all_diff_hunks_expanded()
16215                && buffer.has_expanded_diff_hunks_in_ranges(&ranges, cx)
16216            {
16217                buffer.collapse_diff_hunks(ranges, cx);
16218                true
16219            } else {
16220                false
16221            }
16222        })
16223    }
16224
16225    fn toggle_diff_hunks_in_ranges(
16226        &mut self,
16227        ranges: Vec<Range<Anchor>>,
16228        cx: &mut Context<Editor>,
16229    ) {
16230        self.buffer.update(cx, |buffer, cx| {
16231            let expand = !buffer.has_expanded_diff_hunks_in_ranges(&ranges, cx);
16232            buffer.expand_or_collapse_diff_hunks(ranges, expand, cx);
16233        })
16234    }
16235
16236    fn toggle_single_diff_hunk(&mut self, range: Range<Anchor>, cx: &mut Context<Self>) {
16237        self.buffer.update(cx, |buffer, cx| {
16238            let snapshot = buffer.snapshot(cx);
16239            let excerpt_id = range.end.excerpt_id;
16240            let point_range = range.to_point(&snapshot);
16241            let expand = !buffer.single_hunk_is_expanded(range, cx);
16242            buffer.expand_or_collapse_diff_hunks_inner([(point_range, excerpt_id)], expand, cx);
16243        })
16244    }
16245
16246    pub(crate) fn apply_all_diff_hunks(
16247        &mut self,
16248        _: &ApplyAllDiffHunks,
16249        window: &mut Window,
16250        cx: &mut Context<Self>,
16251    ) {
16252        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
16253
16254        let buffers = self.buffer.read(cx).all_buffers();
16255        for branch_buffer in buffers {
16256            branch_buffer.update(cx, |branch_buffer, cx| {
16257                branch_buffer.merge_into_base(Vec::new(), cx);
16258            });
16259        }
16260
16261        if let Some(project) = self.project.clone() {
16262            self.save(true, project, window, cx).detach_and_log_err(cx);
16263        }
16264    }
16265
16266    pub(crate) fn apply_selected_diff_hunks(
16267        &mut self,
16268        _: &ApplyDiffHunk,
16269        window: &mut Window,
16270        cx: &mut Context<Self>,
16271    ) {
16272        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
16273        let snapshot = self.snapshot(window, cx);
16274        let hunks = snapshot.hunks_for_ranges(self.selections.ranges(cx));
16275        let mut ranges_by_buffer = HashMap::default();
16276        self.transact(window, cx, |editor, _window, cx| {
16277            for hunk in hunks {
16278                if let Some(buffer) = editor.buffer.read(cx).buffer(hunk.buffer_id) {
16279                    ranges_by_buffer
16280                        .entry(buffer.clone())
16281                        .or_insert_with(Vec::new)
16282                        .push(hunk.buffer_range.to_offset(buffer.read(cx)));
16283                }
16284            }
16285
16286            for (buffer, ranges) in ranges_by_buffer {
16287                buffer.update(cx, |buffer, cx| {
16288                    buffer.merge_into_base(ranges, cx);
16289                });
16290            }
16291        });
16292
16293        if let Some(project) = self.project.clone() {
16294            self.save(true, project, window, cx).detach_and_log_err(cx);
16295        }
16296    }
16297
16298    pub fn set_gutter_hovered(&mut self, hovered: bool, cx: &mut Context<Self>) {
16299        if hovered != self.gutter_hovered {
16300            self.gutter_hovered = hovered;
16301            cx.notify();
16302        }
16303    }
16304
16305    pub fn insert_blocks(
16306        &mut self,
16307        blocks: impl IntoIterator<Item = BlockProperties<Anchor>>,
16308        autoscroll: Option<Autoscroll>,
16309        cx: &mut Context<Self>,
16310    ) -> Vec<CustomBlockId> {
16311        let blocks = self
16312            .display_map
16313            .update(cx, |display_map, cx| display_map.insert_blocks(blocks, cx));
16314        if let Some(autoscroll) = autoscroll {
16315            self.request_autoscroll(autoscroll, cx);
16316        }
16317        cx.notify();
16318        blocks
16319    }
16320
16321    pub fn resize_blocks(
16322        &mut self,
16323        heights: HashMap<CustomBlockId, u32>,
16324        autoscroll: Option<Autoscroll>,
16325        cx: &mut Context<Self>,
16326    ) {
16327        self.display_map
16328            .update(cx, |display_map, cx| display_map.resize_blocks(heights, cx));
16329        if let Some(autoscroll) = autoscroll {
16330            self.request_autoscroll(autoscroll, cx);
16331        }
16332        cx.notify();
16333    }
16334
16335    pub fn replace_blocks(
16336        &mut self,
16337        renderers: HashMap<CustomBlockId, RenderBlock>,
16338        autoscroll: Option<Autoscroll>,
16339        cx: &mut Context<Self>,
16340    ) {
16341        self.display_map
16342            .update(cx, |display_map, _cx| display_map.replace_blocks(renderers));
16343        if let Some(autoscroll) = autoscroll {
16344            self.request_autoscroll(autoscroll, cx);
16345        }
16346        cx.notify();
16347    }
16348
16349    pub fn remove_blocks(
16350        &mut self,
16351        block_ids: HashSet<CustomBlockId>,
16352        autoscroll: Option<Autoscroll>,
16353        cx: &mut Context<Self>,
16354    ) {
16355        self.display_map.update(cx, |display_map, cx| {
16356            display_map.remove_blocks(block_ids, cx)
16357        });
16358        if let Some(autoscroll) = autoscroll {
16359            self.request_autoscroll(autoscroll, cx);
16360        }
16361        cx.notify();
16362    }
16363
16364    pub fn row_for_block(
16365        &self,
16366        block_id: CustomBlockId,
16367        cx: &mut Context<Self>,
16368    ) -> Option<DisplayRow> {
16369        self.display_map
16370            .update(cx, |map, cx| map.row_for_block(block_id, cx))
16371    }
16372
16373    pub(crate) fn set_focused_block(&mut self, focused_block: FocusedBlock) {
16374        self.focused_block = Some(focused_block);
16375    }
16376
16377    pub(crate) fn take_focused_block(&mut self) -> Option<FocusedBlock> {
16378        self.focused_block.take()
16379    }
16380
16381    pub fn insert_creases(
16382        &mut self,
16383        creases: impl IntoIterator<Item = Crease<Anchor>>,
16384        cx: &mut Context<Self>,
16385    ) -> Vec<CreaseId> {
16386        self.display_map
16387            .update(cx, |map, cx| map.insert_creases(creases, cx))
16388    }
16389
16390    pub fn remove_creases(
16391        &mut self,
16392        ids: impl IntoIterator<Item = CreaseId>,
16393        cx: &mut Context<Self>,
16394    ) -> Vec<(CreaseId, Range<Anchor>)> {
16395        self.display_map
16396            .update(cx, |map, cx| map.remove_creases(ids, cx))
16397    }
16398
16399    pub fn longest_row(&self, cx: &mut App) -> DisplayRow {
16400        self.display_map
16401            .update(cx, |map, cx| map.snapshot(cx))
16402            .longest_row()
16403    }
16404
16405    pub fn max_point(&self, cx: &mut App) -> DisplayPoint {
16406        self.display_map
16407            .update(cx, |map, cx| map.snapshot(cx))
16408            .max_point()
16409    }
16410
16411    pub fn text(&self, cx: &App) -> String {
16412        self.buffer.read(cx).read(cx).text()
16413    }
16414
16415    pub fn is_empty(&self, cx: &App) -> bool {
16416        self.buffer.read(cx).read(cx).is_empty()
16417    }
16418
16419    pub fn text_option(&self, cx: &App) -> Option<String> {
16420        let text = self.text(cx);
16421        let text = text.trim();
16422
16423        if text.is_empty() {
16424            return None;
16425        }
16426
16427        Some(text.to_string())
16428    }
16429
16430    pub fn set_text(
16431        &mut self,
16432        text: impl Into<Arc<str>>,
16433        window: &mut Window,
16434        cx: &mut Context<Self>,
16435    ) {
16436        self.transact(window, cx, |this, _, cx| {
16437            this.buffer
16438                .read(cx)
16439                .as_singleton()
16440                .expect("you can only call set_text on editors for singleton buffers")
16441                .update(cx, |buffer, cx| buffer.set_text(text, cx));
16442        });
16443    }
16444
16445    pub fn display_text(&self, cx: &mut App) -> String {
16446        self.display_map
16447            .update(cx, |map, cx| map.snapshot(cx))
16448            .text()
16449    }
16450
16451    fn create_minimap(
16452        &self,
16453        minimap_settings: MinimapSettings,
16454        window: &mut Window,
16455        cx: &mut Context<Self>,
16456    ) -> Option<Entity<Self>> {
16457        (minimap_settings.minimap_enabled() && self.is_singleton(cx))
16458            .then(|| self.initialize_new_minimap(minimap_settings, window, cx))
16459    }
16460
16461    fn initialize_new_minimap(
16462        &self,
16463        minimap_settings: MinimapSettings,
16464        window: &mut Window,
16465        cx: &mut Context<Self>,
16466    ) -> Entity<Self> {
16467        const MINIMAP_FONT_WEIGHT: gpui::FontWeight = gpui::FontWeight::BLACK;
16468
16469        let mut minimap = Editor::new_internal(
16470            EditorMode::Minimap {
16471                parent: cx.weak_entity(),
16472            },
16473            self.buffer.clone(),
16474            self.project.clone(),
16475            Some(self.display_map.clone()),
16476            window,
16477            cx,
16478        );
16479        minimap.scroll_manager.clone_state(&self.scroll_manager);
16480        minimap.set_text_style_refinement(TextStyleRefinement {
16481            font_size: Some(MINIMAP_FONT_SIZE),
16482            font_weight: Some(MINIMAP_FONT_WEIGHT),
16483            ..Default::default()
16484        });
16485        minimap.update_minimap_configuration(minimap_settings, cx);
16486        cx.new(|_| minimap)
16487    }
16488
16489    fn update_minimap_configuration(&mut self, minimap_settings: MinimapSettings, cx: &App) {
16490        let current_line_highlight = minimap_settings
16491            .current_line_highlight
16492            .unwrap_or_else(|| EditorSettings::get_global(cx).current_line_highlight);
16493        self.set_current_line_highlight(Some(current_line_highlight));
16494    }
16495
16496    pub fn minimap(&self) -> Option<&Entity<Self>> {
16497        self.minimap
16498            .as_ref()
16499            .filter(|_| self.minimap_visibility.visible())
16500    }
16501
16502    pub fn wrap_guides(&self, cx: &App) -> SmallVec<[(usize, bool); 2]> {
16503        let mut wrap_guides = smallvec::smallvec![];
16504
16505        if self.show_wrap_guides == Some(false) {
16506            return wrap_guides;
16507        }
16508
16509        let settings = self.buffer.read(cx).language_settings(cx);
16510        if settings.show_wrap_guides {
16511            match self.soft_wrap_mode(cx) {
16512                SoftWrap::Column(soft_wrap) => {
16513                    wrap_guides.push((soft_wrap as usize, true));
16514                }
16515                SoftWrap::Bounded(soft_wrap) => {
16516                    wrap_guides.push((soft_wrap as usize, true));
16517                }
16518                SoftWrap::GitDiff | SoftWrap::None | SoftWrap::EditorWidth => {}
16519            }
16520            wrap_guides.extend(settings.wrap_guides.iter().map(|guide| (*guide, false)))
16521        }
16522
16523        wrap_guides
16524    }
16525
16526    pub fn soft_wrap_mode(&self, cx: &App) -> SoftWrap {
16527        let settings = self.buffer.read(cx).language_settings(cx);
16528        let mode = self.soft_wrap_mode_override.unwrap_or(settings.soft_wrap);
16529        match mode {
16530            language_settings::SoftWrap::PreferLine | language_settings::SoftWrap::None => {
16531                SoftWrap::None
16532            }
16533            language_settings::SoftWrap::EditorWidth => SoftWrap::EditorWidth,
16534            language_settings::SoftWrap::PreferredLineLength => {
16535                SoftWrap::Column(settings.preferred_line_length)
16536            }
16537            language_settings::SoftWrap::Bounded => {
16538                SoftWrap::Bounded(settings.preferred_line_length)
16539            }
16540        }
16541    }
16542
16543    pub fn set_soft_wrap_mode(
16544        &mut self,
16545        mode: language_settings::SoftWrap,
16546
16547        cx: &mut Context<Self>,
16548    ) {
16549        self.soft_wrap_mode_override = Some(mode);
16550        cx.notify();
16551    }
16552
16553    pub fn set_hard_wrap(&mut self, hard_wrap: Option<usize>, cx: &mut Context<Self>) {
16554        self.hard_wrap = hard_wrap;
16555        cx.notify();
16556    }
16557
16558    pub fn set_text_style_refinement(&mut self, style: TextStyleRefinement) {
16559        self.text_style_refinement = Some(style);
16560    }
16561
16562    /// called by the Element so we know what style we were most recently rendered with.
16563    pub(crate) fn set_style(
16564        &mut self,
16565        style: EditorStyle,
16566        window: &mut Window,
16567        cx: &mut Context<Self>,
16568    ) {
16569        // We intentionally do not inform the display map about the minimap style
16570        // so that wrapping is not recalculated and stays consistent for the editor
16571        // and its linked minimap.
16572        if !self.mode.is_minimap() {
16573            let rem_size = window.rem_size();
16574            self.display_map.update(cx, |map, cx| {
16575                map.set_font(
16576                    style.text.font(),
16577                    style.text.font_size.to_pixels(rem_size),
16578                    cx,
16579                )
16580            });
16581        }
16582        self.style = Some(style);
16583    }
16584
16585    pub fn style(&self) -> Option<&EditorStyle> {
16586        self.style.as_ref()
16587    }
16588
16589    // Called by the element. This method is not designed to be called outside of the editor
16590    // element's layout code because it does not notify when rewrapping is computed synchronously.
16591    pub(crate) fn set_wrap_width(&self, width: Option<Pixels>, cx: &mut App) -> bool {
16592        self.display_map
16593            .update(cx, |map, cx| map.set_wrap_width(width, cx))
16594    }
16595
16596    pub fn set_soft_wrap(&mut self) {
16597        self.soft_wrap_mode_override = Some(language_settings::SoftWrap::EditorWidth)
16598    }
16599
16600    pub fn toggle_soft_wrap(&mut self, _: &ToggleSoftWrap, _: &mut Window, cx: &mut Context<Self>) {
16601        if self.soft_wrap_mode_override.is_some() {
16602            self.soft_wrap_mode_override.take();
16603        } else {
16604            let soft_wrap = match self.soft_wrap_mode(cx) {
16605                SoftWrap::GitDiff => return,
16606                SoftWrap::None => language_settings::SoftWrap::EditorWidth,
16607                SoftWrap::EditorWidth | SoftWrap::Column(_) | SoftWrap::Bounded(_) => {
16608                    language_settings::SoftWrap::None
16609                }
16610            };
16611            self.soft_wrap_mode_override = Some(soft_wrap);
16612        }
16613        cx.notify();
16614    }
16615
16616    pub fn toggle_tab_bar(&mut self, _: &ToggleTabBar, _: &mut Window, cx: &mut Context<Self>) {
16617        let Some(workspace) = self.workspace() else {
16618            return;
16619        };
16620        let fs = workspace.read(cx).app_state().fs.clone();
16621        let current_show = TabBarSettings::get_global(cx).show;
16622        update_settings_file::<TabBarSettings>(fs, cx, move |setting, _| {
16623            setting.show = Some(!current_show);
16624        });
16625    }
16626
16627    pub fn toggle_indent_guides(
16628        &mut self,
16629        _: &ToggleIndentGuides,
16630        _: &mut Window,
16631        cx: &mut Context<Self>,
16632    ) {
16633        let currently_enabled = self.should_show_indent_guides().unwrap_or_else(|| {
16634            self.buffer
16635                .read(cx)
16636                .language_settings(cx)
16637                .indent_guides
16638                .enabled
16639        });
16640        self.show_indent_guides = Some(!currently_enabled);
16641        cx.notify();
16642    }
16643
16644    fn should_show_indent_guides(&self) -> Option<bool> {
16645        self.show_indent_guides
16646    }
16647
16648    pub fn toggle_line_numbers(
16649        &mut self,
16650        _: &ToggleLineNumbers,
16651        _: &mut Window,
16652        cx: &mut Context<Self>,
16653    ) {
16654        let mut editor_settings = EditorSettings::get_global(cx).clone();
16655        editor_settings.gutter.line_numbers = !editor_settings.gutter.line_numbers;
16656        EditorSettings::override_global(editor_settings, cx);
16657    }
16658
16659    pub fn line_numbers_enabled(&self, cx: &App) -> bool {
16660        if let Some(show_line_numbers) = self.show_line_numbers {
16661            return show_line_numbers;
16662        }
16663        EditorSettings::get_global(cx).gutter.line_numbers
16664    }
16665
16666    pub fn should_use_relative_line_numbers(&self, cx: &mut App) -> bool {
16667        self.use_relative_line_numbers
16668            .unwrap_or(EditorSettings::get_global(cx).relative_line_numbers)
16669    }
16670
16671    pub fn toggle_relative_line_numbers(
16672        &mut self,
16673        _: &ToggleRelativeLineNumbers,
16674        _: &mut Window,
16675        cx: &mut Context<Self>,
16676    ) {
16677        let is_relative = self.should_use_relative_line_numbers(cx);
16678        self.set_relative_line_number(Some(!is_relative), cx)
16679    }
16680
16681    pub fn set_relative_line_number(&mut self, is_relative: Option<bool>, cx: &mut Context<Self>) {
16682        self.use_relative_line_numbers = is_relative;
16683        cx.notify();
16684    }
16685
16686    pub fn set_show_gutter(&mut self, show_gutter: bool, cx: &mut Context<Self>) {
16687        self.show_gutter = show_gutter;
16688        cx.notify();
16689    }
16690
16691    pub fn set_show_scrollbars(&mut self, show_scrollbars: bool, cx: &mut Context<Self>) {
16692        self.show_scrollbars = show_scrollbars;
16693        cx.notify();
16694    }
16695
16696    pub fn set_minimap_visibility(
16697        &mut self,
16698        minimap_visibility: MinimapVisibility,
16699        window: &mut Window,
16700        cx: &mut Context<Self>,
16701    ) {
16702        if self.minimap_visibility != minimap_visibility {
16703            if minimap_visibility.visible() && self.minimap.is_none() {
16704                let minimap_settings = EditorSettings::get_global(cx).minimap;
16705                self.minimap =
16706                    self.create_minimap(minimap_settings.with_show_override(), window, cx);
16707            }
16708            self.minimap_visibility = minimap_visibility;
16709            cx.notify();
16710        }
16711    }
16712
16713    pub fn disable_scrollbars_and_minimap(&mut self, window: &mut Window, cx: &mut Context<Self>) {
16714        self.set_show_scrollbars(false, cx);
16715        self.set_minimap_visibility(MinimapVisibility::Disabled, window, cx);
16716    }
16717
16718    pub fn set_show_line_numbers(&mut self, show_line_numbers: bool, cx: &mut Context<Self>) {
16719        self.show_line_numbers = Some(show_line_numbers);
16720        cx.notify();
16721    }
16722
16723    pub fn disable_expand_excerpt_buttons(&mut self, cx: &mut Context<Self>) {
16724        self.disable_expand_excerpt_buttons = true;
16725        cx.notify();
16726    }
16727
16728    pub fn set_show_git_diff_gutter(&mut self, show_git_diff_gutter: bool, cx: &mut Context<Self>) {
16729        self.show_git_diff_gutter = Some(show_git_diff_gutter);
16730        cx.notify();
16731    }
16732
16733    pub fn set_show_code_actions(&mut self, show_code_actions: bool, cx: &mut Context<Self>) {
16734        self.show_code_actions = Some(show_code_actions);
16735        cx.notify();
16736    }
16737
16738    pub fn set_show_runnables(&mut self, show_runnables: bool, cx: &mut Context<Self>) {
16739        self.show_runnables = Some(show_runnables);
16740        cx.notify();
16741    }
16742
16743    pub fn set_show_breakpoints(&mut self, show_breakpoints: bool, cx: &mut Context<Self>) {
16744        self.show_breakpoints = Some(show_breakpoints);
16745        cx.notify();
16746    }
16747
16748    pub fn set_masked(&mut self, masked: bool, cx: &mut Context<Self>) {
16749        if self.display_map.read(cx).masked != masked {
16750            self.display_map.update(cx, |map, _| map.masked = masked);
16751        }
16752        cx.notify()
16753    }
16754
16755    pub fn set_show_wrap_guides(&mut self, show_wrap_guides: bool, cx: &mut Context<Self>) {
16756        self.show_wrap_guides = Some(show_wrap_guides);
16757        cx.notify();
16758    }
16759
16760    pub fn set_show_indent_guides(&mut self, show_indent_guides: bool, cx: &mut Context<Self>) {
16761        self.show_indent_guides = Some(show_indent_guides);
16762        cx.notify();
16763    }
16764
16765    pub fn working_directory(&self, cx: &App) -> Option<PathBuf> {
16766        if let Some(buffer) = self.buffer().read(cx).as_singleton() {
16767            if let Some(file) = buffer.read(cx).file().and_then(|f| f.as_local()) {
16768                if let Some(dir) = file.abs_path(cx).parent() {
16769                    return Some(dir.to_owned());
16770                }
16771            }
16772
16773            if let Some(project_path) = buffer.read(cx).project_path(cx) {
16774                return Some(project_path.path.to_path_buf());
16775            }
16776        }
16777
16778        None
16779    }
16780
16781    fn target_file<'a>(&self, cx: &'a App) -> Option<&'a dyn language::LocalFile> {
16782        self.active_excerpt(cx)?
16783            .1
16784            .read(cx)
16785            .file()
16786            .and_then(|f| f.as_local())
16787    }
16788
16789    pub fn target_file_abs_path(&self, cx: &mut Context<Self>) -> Option<PathBuf> {
16790        self.active_excerpt(cx).and_then(|(_, buffer, _)| {
16791            let buffer = buffer.read(cx);
16792            if let Some(project_path) = buffer.project_path(cx) {
16793                let project = self.project.as_ref()?.read(cx);
16794                project.absolute_path(&project_path, cx)
16795            } else {
16796                buffer
16797                    .file()
16798                    .and_then(|file| file.as_local().map(|file| file.abs_path(cx)))
16799            }
16800        })
16801    }
16802
16803    fn target_file_path(&self, cx: &mut Context<Self>) -> Option<PathBuf> {
16804        self.active_excerpt(cx).and_then(|(_, buffer, _)| {
16805            let project_path = buffer.read(cx).project_path(cx)?;
16806            let project = self.project.as_ref()?.read(cx);
16807            let entry = project.entry_for_path(&project_path, cx)?;
16808            let path = entry.path.to_path_buf();
16809            Some(path)
16810        })
16811    }
16812
16813    pub fn reveal_in_finder(
16814        &mut self,
16815        _: &RevealInFileManager,
16816        _window: &mut Window,
16817        cx: &mut Context<Self>,
16818    ) {
16819        if let Some(target) = self.target_file(cx) {
16820            cx.reveal_path(&target.abs_path(cx));
16821        }
16822    }
16823
16824    pub fn copy_path(
16825        &mut self,
16826        _: &zed_actions::workspace::CopyPath,
16827        _window: &mut Window,
16828        cx: &mut Context<Self>,
16829    ) {
16830        if let Some(path) = self.target_file_abs_path(cx) {
16831            if let Some(path) = path.to_str() {
16832                cx.write_to_clipboard(ClipboardItem::new_string(path.to_string()));
16833            }
16834        }
16835    }
16836
16837    pub fn copy_relative_path(
16838        &mut self,
16839        _: &zed_actions::workspace::CopyRelativePath,
16840        _window: &mut Window,
16841        cx: &mut Context<Self>,
16842    ) {
16843        if let Some(path) = self.target_file_path(cx) {
16844            if let Some(path) = path.to_str() {
16845                cx.write_to_clipboard(ClipboardItem::new_string(path.to_string()));
16846            }
16847        }
16848    }
16849
16850    pub fn project_path(&self, cx: &App) -> Option<ProjectPath> {
16851        if let Some(buffer) = self.buffer.read(cx).as_singleton() {
16852            buffer.read(cx).project_path(cx)
16853        } else {
16854            None
16855        }
16856    }
16857
16858    // Returns true if the editor handled a go-to-line request
16859    pub fn go_to_active_debug_line(&mut self, window: &mut Window, cx: &mut Context<Self>) -> bool {
16860        maybe!({
16861            let breakpoint_store = self.breakpoint_store.as_ref()?;
16862
16863            let Some(active_stack_frame) = breakpoint_store.read(cx).active_position().cloned()
16864            else {
16865                self.clear_row_highlights::<ActiveDebugLine>();
16866                return None;
16867            };
16868
16869            let position = active_stack_frame.position;
16870            let buffer_id = position.buffer_id?;
16871            let snapshot = self
16872                .project
16873                .as_ref()?
16874                .read(cx)
16875                .buffer_for_id(buffer_id, cx)?
16876                .read(cx)
16877                .snapshot();
16878
16879            let mut handled = false;
16880            for (id, ExcerptRange { context, .. }) in
16881                self.buffer.read(cx).excerpts_for_buffer(buffer_id, cx)
16882            {
16883                if context.start.cmp(&position, &snapshot).is_ge()
16884                    || context.end.cmp(&position, &snapshot).is_lt()
16885                {
16886                    continue;
16887                }
16888                let snapshot = self.buffer.read(cx).snapshot(cx);
16889                let multibuffer_anchor = snapshot.anchor_in_excerpt(id, position)?;
16890
16891                handled = true;
16892                self.clear_row_highlights::<ActiveDebugLine>();
16893
16894                self.go_to_line::<ActiveDebugLine>(
16895                    multibuffer_anchor,
16896                    Some(cx.theme().colors().editor_debugger_active_line_background),
16897                    window,
16898                    cx,
16899                );
16900
16901                cx.notify();
16902            }
16903
16904            handled.then_some(())
16905        })
16906        .is_some()
16907    }
16908
16909    pub fn copy_file_name_without_extension(
16910        &mut self,
16911        _: &CopyFileNameWithoutExtension,
16912        _: &mut Window,
16913        cx: &mut Context<Self>,
16914    ) {
16915        if let Some(file) = self.target_file(cx) {
16916            if let Some(file_stem) = file.path().file_stem() {
16917                if let Some(name) = file_stem.to_str() {
16918                    cx.write_to_clipboard(ClipboardItem::new_string(name.to_string()));
16919                }
16920            }
16921        }
16922    }
16923
16924    pub fn copy_file_name(&mut self, _: &CopyFileName, _: &mut Window, cx: &mut Context<Self>) {
16925        if let Some(file) = self.target_file(cx) {
16926            if let Some(file_name) = file.path().file_name() {
16927                if let Some(name) = file_name.to_str() {
16928                    cx.write_to_clipboard(ClipboardItem::new_string(name.to_string()));
16929                }
16930            }
16931        }
16932    }
16933
16934    pub fn toggle_git_blame(
16935        &mut self,
16936        _: &::git::Blame,
16937        window: &mut Window,
16938        cx: &mut Context<Self>,
16939    ) {
16940        self.show_git_blame_gutter = !self.show_git_blame_gutter;
16941
16942        if self.show_git_blame_gutter && !self.has_blame_entries(cx) {
16943            self.start_git_blame(true, window, cx);
16944        }
16945
16946        cx.notify();
16947    }
16948
16949    pub fn toggle_git_blame_inline(
16950        &mut self,
16951        _: &ToggleGitBlameInline,
16952        window: &mut Window,
16953        cx: &mut Context<Self>,
16954    ) {
16955        self.toggle_git_blame_inline_internal(true, window, cx);
16956        cx.notify();
16957    }
16958
16959    pub fn open_git_blame_commit(
16960        &mut self,
16961        _: &OpenGitBlameCommit,
16962        window: &mut Window,
16963        cx: &mut Context<Self>,
16964    ) {
16965        self.open_git_blame_commit_internal(window, cx);
16966    }
16967
16968    fn open_git_blame_commit_internal(
16969        &mut self,
16970        window: &mut Window,
16971        cx: &mut Context<Self>,
16972    ) -> Option<()> {
16973        let blame = self.blame.as_ref()?;
16974        let snapshot = self.snapshot(window, cx);
16975        let cursor = self.selections.newest::<Point>(cx).head();
16976        let (buffer, point, _) = snapshot.buffer_snapshot.point_to_buffer_point(cursor)?;
16977        let blame_entry = blame
16978            .update(cx, |blame, cx| {
16979                blame
16980                    .blame_for_rows(
16981                        &[RowInfo {
16982                            buffer_id: Some(buffer.remote_id()),
16983                            buffer_row: Some(point.row),
16984                            ..Default::default()
16985                        }],
16986                        cx,
16987                    )
16988                    .next()
16989            })
16990            .flatten()?;
16991        let renderer = cx.global::<GlobalBlameRenderer>().0.clone();
16992        let repo = blame.read(cx).repository(cx)?;
16993        let workspace = self.workspace()?.downgrade();
16994        renderer.open_blame_commit(blame_entry, repo, workspace, window, cx);
16995        None
16996    }
16997
16998    pub fn git_blame_inline_enabled(&self) -> bool {
16999        self.git_blame_inline_enabled
17000    }
17001
17002    pub fn toggle_selection_menu(
17003        &mut self,
17004        _: &ToggleSelectionMenu,
17005        _: &mut Window,
17006        cx: &mut Context<Self>,
17007    ) {
17008        self.show_selection_menu = self
17009            .show_selection_menu
17010            .map(|show_selections_menu| !show_selections_menu)
17011            .or_else(|| Some(!EditorSettings::get_global(cx).toolbar.selections_menu));
17012
17013        cx.notify();
17014    }
17015
17016    pub fn selection_menu_enabled(&self, cx: &App) -> bool {
17017        self.show_selection_menu
17018            .unwrap_or_else(|| EditorSettings::get_global(cx).toolbar.selections_menu)
17019    }
17020
17021    fn start_git_blame(
17022        &mut self,
17023        user_triggered: bool,
17024        window: &mut Window,
17025        cx: &mut Context<Self>,
17026    ) {
17027        if let Some(project) = self.project.as_ref() {
17028            let Some(buffer) = self.buffer().read(cx).as_singleton() else {
17029                return;
17030            };
17031
17032            if buffer.read(cx).file().is_none() {
17033                return;
17034            }
17035
17036            let focused = self.focus_handle(cx).contains_focused(window, cx);
17037
17038            let project = project.clone();
17039            let blame = cx.new(|cx| GitBlame::new(buffer, project, user_triggered, focused, cx));
17040            self.blame_subscription =
17041                Some(cx.observe_in(&blame, window, |_, _, _, cx| cx.notify()));
17042            self.blame = Some(blame);
17043        }
17044    }
17045
17046    fn toggle_git_blame_inline_internal(
17047        &mut self,
17048        user_triggered: bool,
17049        window: &mut Window,
17050        cx: &mut Context<Self>,
17051    ) {
17052        if self.git_blame_inline_enabled {
17053            self.git_blame_inline_enabled = false;
17054            self.show_git_blame_inline = false;
17055            self.show_git_blame_inline_delay_task.take();
17056        } else {
17057            self.git_blame_inline_enabled = true;
17058            self.start_git_blame_inline(user_triggered, window, cx);
17059        }
17060
17061        cx.notify();
17062    }
17063
17064    fn start_git_blame_inline(
17065        &mut self,
17066        user_triggered: bool,
17067        window: &mut Window,
17068        cx: &mut Context<Self>,
17069    ) {
17070        self.start_git_blame(user_triggered, window, cx);
17071
17072        if ProjectSettings::get_global(cx)
17073            .git
17074            .inline_blame_delay()
17075            .is_some()
17076        {
17077            self.start_inline_blame_timer(window, cx);
17078        } else {
17079            self.show_git_blame_inline = true
17080        }
17081    }
17082
17083    pub fn blame(&self) -> Option<&Entity<GitBlame>> {
17084        self.blame.as_ref()
17085    }
17086
17087    pub fn show_git_blame_gutter(&self) -> bool {
17088        self.show_git_blame_gutter
17089    }
17090
17091    pub fn render_git_blame_gutter(&self, cx: &App) -> bool {
17092        !self.mode().is_minimap() && self.show_git_blame_gutter && self.has_blame_entries(cx)
17093    }
17094
17095    pub fn render_git_blame_inline(&self, window: &Window, cx: &App) -> bool {
17096        self.show_git_blame_inline
17097            && (self.focus_handle.is_focused(window) || self.inline_blame_popover.is_some())
17098            && !self.newest_selection_head_on_empty_line(cx)
17099            && self.has_blame_entries(cx)
17100    }
17101
17102    fn has_blame_entries(&self, cx: &App) -> bool {
17103        self.blame()
17104            .map_or(false, |blame| blame.read(cx).has_generated_entries())
17105    }
17106
17107    fn newest_selection_head_on_empty_line(&self, cx: &App) -> bool {
17108        let cursor_anchor = self.selections.newest_anchor().head();
17109
17110        let snapshot = self.buffer.read(cx).snapshot(cx);
17111        let buffer_row = MultiBufferRow(cursor_anchor.to_point(&snapshot).row);
17112
17113        snapshot.line_len(buffer_row) == 0
17114    }
17115
17116    fn get_permalink_to_line(&self, cx: &mut Context<Self>) -> Task<Result<url::Url>> {
17117        let buffer_and_selection = maybe!({
17118            let selection = self.selections.newest::<Point>(cx);
17119            let selection_range = selection.range();
17120
17121            let multi_buffer = self.buffer().read(cx);
17122            let multi_buffer_snapshot = multi_buffer.snapshot(cx);
17123            let buffer_ranges = multi_buffer_snapshot.range_to_buffer_ranges(selection_range);
17124
17125            let (buffer, range, _) = if selection.reversed {
17126                buffer_ranges.first()
17127            } else {
17128                buffer_ranges.last()
17129            }?;
17130
17131            let selection = text::ToPoint::to_point(&range.start, &buffer).row
17132                ..text::ToPoint::to_point(&range.end, &buffer).row;
17133            Some((
17134                multi_buffer.buffer(buffer.remote_id()).unwrap().clone(),
17135                selection,
17136            ))
17137        });
17138
17139        let Some((buffer, selection)) = buffer_and_selection else {
17140            return Task::ready(Err(anyhow!("failed to determine buffer and selection")));
17141        };
17142
17143        let Some(project) = self.project.as_ref() else {
17144            return Task::ready(Err(anyhow!("editor does not have project")));
17145        };
17146
17147        project.update(cx, |project, cx| {
17148            project.get_permalink_to_line(&buffer, selection, cx)
17149        })
17150    }
17151
17152    pub fn copy_permalink_to_line(
17153        &mut self,
17154        _: &CopyPermalinkToLine,
17155        window: &mut Window,
17156        cx: &mut Context<Self>,
17157    ) {
17158        let permalink_task = self.get_permalink_to_line(cx);
17159        let workspace = self.workspace();
17160
17161        cx.spawn_in(window, async move |_, cx| match permalink_task.await {
17162            Ok(permalink) => {
17163                cx.update(|_, cx| {
17164                    cx.write_to_clipboard(ClipboardItem::new_string(permalink.to_string()));
17165                })
17166                .ok();
17167            }
17168            Err(err) => {
17169                let message = format!("Failed to copy permalink: {err}");
17170
17171                Err::<(), anyhow::Error>(err).log_err();
17172
17173                if let Some(workspace) = workspace {
17174                    workspace
17175                        .update_in(cx, |workspace, _, cx| {
17176                            struct CopyPermalinkToLine;
17177
17178                            workspace.show_toast(
17179                                Toast::new(
17180                                    NotificationId::unique::<CopyPermalinkToLine>(),
17181                                    message,
17182                                ),
17183                                cx,
17184                            )
17185                        })
17186                        .ok();
17187                }
17188            }
17189        })
17190        .detach();
17191    }
17192
17193    pub fn copy_file_location(
17194        &mut self,
17195        _: &CopyFileLocation,
17196        _: &mut Window,
17197        cx: &mut Context<Self>,
17198    ) {
17199        let selection = self.selections.newest::<Point>(cx).start.row + 1;
17200        if let Some(file) = self.target_file(cx) {
17201            if let Some(path) = file.path().to_str() {
17202                cx.write_to_clipboard(ClipboardItem::new_string(format!("{path}:{selection}")));
17203            }
17204        }
17205    }
17206
17207    pub fn open_permalink_to_line(
17208        &mut self,
17209        _: &OpenPermalinkToLine,
17210        window: &mut Window,
17211        cx: &mut Context<Self>,
17212    ) {
17213        let permalink_task = self.get_permalink_to_line(cx);
17214        let workspace = self.workspace();
17215
17216        cx.spawn_in(window, async move |_, cx| match permalink_task.await {
17217            Ok(permalink) => {
17218                cx.update(|_, cx| {
17219                    cx.open_url(permalink.as_ref());
17220                })
17221                .ok();
17222            }
17223            Err(err) => {
17224                let message = format!("Failed to open permalink: {err}");
17225
17226                Err::<(), anyhow::Error>(err).log_err();
17227
17228                if let Some(workspace) = workspace {
17229                    workspace
17230                        .update(cx, |workspace, cx| {
17231                            struct OpenPermalinkToLine;
17232
17233                            workspace.show_toast(
17234                                Toast::new(
17235                                    NotificationId::unique::<OpenPermalinkToLine>(),
17236                                    message,
17237                                ),
17238                                cx,
17239                            )
17240                        })
17241                        .ok();
17242                }
17243            }
17244        })
17245        .detach();
17246    }
17247
17248    pub fn insert_uuid_v4(
17249        &mut self,
17250        _: &InsertUuidV4,
17251        window: &mut Window,
17252        cx: &mut Context<Self>,
17253    ) {
17254        self.insert_uuid(UuidVersion::V4, window, cx);
17255    }
17256
17257    pub fn insert_uuid_v7(
17258        &mut self,
17259        _: &InsertUuidV7,
17260        window: &mut Window,
17261        cx: &mut Context<Self>,
17262    ) {
17263        self.insert_uuid(UuidVersion::V7, window, cx);
17264    }
17265
17266    fn insert_uuid(&mut self, version: UuidVersion, window: &mut Window, cx: &mut Context<Self>) {
17267        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
17268        self.transact(window, cx, |this, window, cx| {
17269            let edits = this
17270                .selections
17271                .all::<Point>(cx)
17272                .into_iter()
17273                .map(|selection| {
17274                    let uuid = match version {
17275                        UuidVersion::V4 => uuid::Uuid::new_v4(),
17276                        UuidVersion::V7 => uuid::Uuid::now_v7(),
17277                    };
17278
17279                    (selection.range(), uuid.to_string())
17280                });
17281            this.edit(edits, cx);
17282            this.refresh_inline_completion(true, false, window, cx);
17283        });
17284    }
17285
17286    pub fn open_selections_in_multibuffer(
17287        &mut self,
17288        _: &OpenSelectionsInMultibuffer,
17289        window: &mut Window,
17290        cx: &mut Context<Self>,
17291    ) {
17292        let multibuffer = self.buffer.read(cx);
17293
17294        let Some(buffer) = multibuffer.as_singleton() else {
17295            return;
17296        };
17297
17298        let Some(workspace) = self.workspace() else {
17299            return;
17300        };
17301
17302        let locations = self
17303            .selections
17304            .disjoint_anchors()
17305            .iter()
17306            .map(|range| Location {
17307                buffer: buffer.clone(),
17308                range: range.start.text_anchor..range.end.text_anchor,
17309            })
17310            .collect::<Vec<_>>();
17311
17312        let title = multibuffer.title(cx).to_string();
17313
17314        cx.spawn_in(window, async move |_, cx| {
17315            workspace.update_in(cx, |workspace, window, cx| {
17316                Self::open_locations_in_multibuffer(
17317                    workspace,
17318                    locations,
17319                    format!("Selections for '{title}'"),
17320                    false,
17321                    MultibufferSelectionMode::All,
17322                    window,
17323                    cx,
17324                );
17325            })
17326        })
17327        .detach();
17328    }
17329
17330    /// Adds a row highlight for the given range. If a row has multiple highlights, the
17331    /// last highlight added will be used.
17332    ///
17333    /// If the range ends at the beginning of a line, then that line will not be highlighted.
17334    pub fn highlight_rows<T: 'static>(
17335        &mut self,
17336        range: Range<Anchor>,
17337        color: Hsla,
17338        options: RowHighlightOptions,
17339        cx: &mut Context<Self>,
17340    ) {
17341        let snapshot = self.buffer().read(cx).snapshot(cx);
17342        let row_highlights = self.highlighted_rows.entry(TypeId::of::<T>()).or_default();
17343        let ix = row_highlights.binary_search_by(|highlight| {
17344            Ordering::Equal
17345                .then_with(|| highlight.range.start.cmp(&range.start, &snapshot))
17346                .then_with(|| highlight.range.end.cmp(&range.end, &snapshot))
17347        });
17348
17349        if let Err(mut ix) = ix {
17350            let index = post_inc(&mut self.highlight_order);
17351
17352            // If this range intersects with the preceding highlight, then merge it with
17353            // the preceding highlight. Otherwise insert a new highlight.
17354            let mut merged = false;
17355            if ix > 0 {
17356                let prev_highlight = &mut row_highlights[ix - 1];
17357                if prev_highlight
17358                    .range
17359                    .end
17360                    .cmp(&range.start, &snapshot)
17361                    .is_ge()
17362                {
17363                    ix -= 1;
17364                    if prev_highlight.range.end.cmp(&range.end, &snapshot).is_lt() {
17365                        prev_highlight.range.end = range.end;
17366                    }
17367                    merged = true;
17368                    prev_highlight.index = index;
17369                    prev_highlight.color = color;
17370                    prev_highlight.options = options;
17371                }
17372            }
17373
17374            if !merged {
17375                row_highlights.insert(
17376                    ix,
17377                    RowHighlight {
17378                        range: range.clone(),
17379                        index,
17380                        color,
17381                        options,
17382                        type_id: TypeId::of::<T>(),
17383                    },
17384                );
17385            }
17386
17387            // If any of the following highlights intersect with this one, merge them.
17388            while let Some(next_highlight) = row_highlights.get(ix + 1) {
17389                let highlight = &row_highlights[ix];
17390                if next_highlight
17391                    .range
17392                    .start
17393                    .cmp(&highlight.range.end, &snapshot)
17394                    .is_le()
17395                {
17396                    if next_highlight
17397                        .range
17398                        .end
17399                        .cmp(&highlight.range.end, &snapshot)
17400                        .is_gt()
17401                    {
17402                        row_highlights[ix].range.end = next_highlight.range.end;
17403                    }
17404                    row_highlights.remove(ix + 1);
17405                } else {
17406                    break;
17407                }
17408            }
17409        }
17410    }
17411
17412    /// Remove any highlighted row ranges of the given type that intersect the
17413    /// given ranges.
17414    pub fn remove_highlighted_rows<T: 'static>(
17415        &mut self,
17416        ranges_to_remove: Vec<Range<Anchor>>,
17417        cx: &mut Context<Self>,
17418    ) {
17419        let snapshot = self.buffer().read(cx).snapshot(cx);
17420        let row_highlights = self.highlighted_rows.entry(TypeId::of::<T>()).or_default();
17421        let mut ranges_to_remove = ranges_to_remove.iter().peekable();
17422        row_highlights.retain(|highlight| {
17423            while let Some(range_to_remove) = ranges_to_remove.peek() {
17424                match range_to_remove.end.cmp(&highlight.range.start, &snapshot) {
17425                    Ordering::Less | Ordering::Equal => {
17426                        ranges_to_remove.next();
17427                    }
17428                    Ordering::Greater => {
17429                        match range_to_remove.start.cmp(&highlight.range.end, &snapshot) {
17430                            Ordering::Less | Ordering::Equal => {
17431                                return false;
17432                            }
17433                            Ordering::Greater => break,
17434                        }
17435                    }
17436                }
17437            }
17438
17439            true
17440        })
17441    }
17442
17443    /// Clear all anchor ranges for a certain highlight context type, so no corresponding rows will be highlighted.
17444    pub fn clear_row_highlights<T: 'static>(&mut self) {
17445        self.highlighted_rows.remove(&TypeId::of::<T>());
17446    }
17447
17448    /// For a highlight given context type, gets all anchor ranges that will be used for row highlighting.
17449    pub fn highlighted_rows<T: 'static>(&self) -> impl '_ + Iterator<Item = (Range<Anchor>, Hsla)> {
17450        self.highlighted_rows
17451            .get(&TypeId::of::<T>())
17452            .map_or(&[] as &[_], |vec| vec.as_slice())
17453            .iter()
17454            .map(|highlight| (highlight.range.clone(), highlight.color))
17455    }
17456
17457    /// Merges all anchor ranges for all context types ever set, picking the last highlight added in case of a row conflict.
17458    /// Returns a map of display rows that are highlighted and their corresponding highlight color.
17459    /// Allows to ignore certain kinds of highlights.
17460    pub fn highlighted_display_rows(
17461        &self,
17462        window: &mut Window,
17463        cx: &mut App,
17464    ) -> BTreeMap<DisplayRow, LineHighlight> {
17465        let snapshot = self.snapshot(window, cx);
17466        let mut used_highlight_orders = HashMap::default();
17467        self.highlighted_rows
17468            .iter()
17469            .flat_map(|(_, highlighted_rows)| highlighted_rows.iter())
17470            .fold(
17471                BTreeMap::<DisplayRow, LineHighlight>::new(),
17472                |mut unique_rows, highlight| {
17473                    let start = highlight.range.start.to_display_point(&snapshot);
17474                    let end = highlight.range.end.to_display_point(&snapshot);
17475                    let start_row = start.row().0;
17476                    let end_row = if highlight.range.end.text_anchor != text::Anchor::MAX
17477                        && end.column() == 0
17478                    {
17479                        end.row().0.saturating_sub(1)
17480                    } else {
17481                        end.row().0
17482                    };
17483                    for row in start_row..=end_row {
17484                        let used_index =
17485                            used_highlight_orders.entry(row).or_insert(highlight.index);
17486                        if highlight.index >= *used_index {
17487                            *used_index = highlight.index;
17488                            unique_rows.insert(
17489                                DisplayRow(row),
17490                                LineHighlight {
17491                                    include_gutter: highlight.options.include_gutter,
17492                                    border: None,
17493                                    background: highlight.color.into(),
17494                                    type_id: Some(highlight.type_id),
17495                                },
17496                            );
17497                        }
17498                    }
17499                    unique_rows
17500                },
17501            )
17502    }
17503
17504    pub fn highlighted_display_row_for_autoscroll(
17505        &self,
17506        snapshot: &DisplaySnapshot,
17507    ) -> Option<DisplayRow> {
17508        self.highlighted_rows
17509            .values()
17510            .flat_map(|highlighted_rows| highlighted_rows.iter())
17511            .filter_map(|highlight| {
17512                if highlight.options.autoscroll {
17513                    Some(highlight.range.start.to_display_point(snapshot).row())
17514                } else {
17515                    None
17516                }
17517            })
17518            .min()
17519    }
17520
17521    pub fn set_search_within_ranges(&mut self, ranges: &[Range<Anchor>], cx: &mut Context<Self>) {
17522        self.highlight_background::<SearchWithinRange>(
17523            ranges,
17524            |colors| colors.editor_document_highlight_read_background,
17525            cx,
17526        )
17527    }
17528
17529    pub fn set_breadcrumb_header(&mut self, new_header: String) {
17530        self.breadcrumb_header = Some(new_header);
17531    }
17532
17533    pub fn clear_search_within_ranges(&mut self, cx: &mut Context<Self>) {
17534        self.clear_background_highlights::<SearchWithinRange>(cx);
17535    }
17536
17537    pub fn highlight_background<T: 'static>(
17538        &mut self,
17539        ranges: &[Range<Anchor>],
17540        color_fetcher: fn(&ThemeColors) -> Hsla,
17541        cx: &mut Context<Self>,
17542    ) {
17543        self.background_highlights
17544            .insert(TypeId::of::<T>(), (color_fetcher, Arc::from(ranges)));
17545        self.scrollbar_marker_state.dirty = true;
17546        cx.notify();
17547    }
17548
17549    pub fn clear_background_highlights<T: 'static>(
17550        &mut self,
17551        cx: &mut Context<Self>,
17552    ) -> Option<BackgroundHighlight> {
17553        let text_highlights = self.background_highlights.remove(&TypeId::of::<T>())?;
17554        if !text_highlights.1.is_empty() {
17555            self.scrollbar_marker_state.dirty = true;
17556            cx.notify();
17557        }
17558        Some(text_highlights)
17559    }
17560
17561    pub fn highlight_gutter<T: 'static>(
17562        &mut self,
17563        ranges: &[Range<Anchor>],
17564        color_fetcher: fn(&App) -> Hsla,
17565        cx: &mut Context<Self>,
17566    ) {
17567        self.gutter_highlights
17568            .insert(TypeId::of::<T>(), (color_fetcher, Arc::from(ranges)));
17569        cx.notify();
17570    }
17571
17572    pub fn clear_gutter_highlights<T: 'static>(
17573        &mut self,
17574        cx: &mut Context<Self>,
17575    ) -> Option<GutterHighlight> {
17576        cx.notify();
17577        self.gutter_highlights.remove(&TypeId::of::<T>())
17578    }
17579
17580    #[cfg(feature = "test-support")]
17581    pub fn all_text_background_highlights(
17582        &self,
17583        window: &mut Window,
17584        cx: &mut Context<Self>,
17585    ) -> Vec<(Range<DisplayPoint>, Hsla)> {
17586        let snapshot = self.snapshot(window, cx);
17587        let buffer = &snapshot.buffer_snapshot;
17588        let start = buffer.anchor_before(0);
17589        let end = buffer.anchor_after(buffer.len());
17590        let theme = cx.theme().colors();
17591        self.background_highlights_in_range(start..end, &snapshot, theme)
17592    }
17593
17594    #[cfg(feature = "test-support")]
17595    pub fn search_background_highlights(&mut self, cx: &mut Context<Self>) -> Vec<Range<Point>> {
17596        let snapshot = self.buffer().read(cx).snapshot(cx);
17597
17598        let highlights = self
17599            .background_highlights
17600            .get(&TypeId::of::<items::BufferSearchHighlights>());
17601
17602        if let Some((_color, ranges)) = highlights {
17603            ranges
17604                .iter()
17605                .map(|range| range.start.to_point(&snapshot)..range.end.to_point(&snapshot))
17606                .collect_vec()
17607        } else {
17608            vec![]
17609        }
17610    }
17611
17612    fn document_highlights_for_position<'a>(
17613        &'a self,
17614        position: Anchor,
17615        buffer: &'a MultiBufferSnapshot,
17616    ) -> impl 'a + Iterator<Item = &'a Range<Anchor>> {
17617        let read_highlights = self
17618            .background_highlights
17619            .get(&TypeId::of::<DocumentHighlightRead>())
17620            .map(|h| &h.1);
17621        let write_highlights = self
17622            .background_highlights
17623            .get(&TypeId::of::<DocumentHighlightWrite>())
17624            .map(|h| &h.1);
17625        let left_position = position.bias_left(buffer);
17626        let right_position = position.bias_right(buffer);
17627        read_highlights
17628            .into_iter()
17629            .chain(write_highlights)
17630            .flat_map(move |ranges| {
17631                let start_ix = match ranges.binary_search_by(|probe| {
17632                    let cmp = probe.end.cmp(&left_position, buffer);
17633                    if cmp.is_ge() {
17634                        Ordering::Greater
17635                    } else {
17636                        Ordering::Less
17637                    }
17638                }) {
17639                    Ok(i) | Err(i) => i,
17640                };
17641
17642                ranges[start_ix..]
17643                    .iter()
17644                    .take_while(move |range| range.start.cmp(&right_position, buffer).is_le())
17645            })
17646    }
17647
17648    pub fn has_background_highlights<T: 'static>(&self) -> bool {
17649        self.background_highlights
17650            .get(&TypeId::of::<T>())
17651            .map_or(false, |(_, highlights)| !highlights.is_empty())
17652    }
17653
17654    pub fn background_highlights_in_range(
17655        &self,
17656        search_range: Range<Anchor>,
17657        display_snapshot: &DisplaySnapshot,
17658        theme: &ThemeColors,
17659    ) -> Vec<(Range<DisplayPoint>, Hsla)> {
17660        let mut results = Vec::new();
17661        for (color_fetcher, ranges) in self.background_highlights.values() {
17662            let color = color_fetcher(theme);
17663            let start_ix = match ranges.binary_search_by(|probe| {
17664                let cmp = probe
17665                    .end
17666                    .cmp(&search_range.start, &display_snapshot.buffer_snapshot);
17667                if cmp.is_gt() {
17668                    Ordering::Greater
17669                } else {
17670                    Ordering::Less
17671                }
17672            }) {
17673                Ok(i) | Err(i) => i,
17674            };
17675            for range in &ranges[start_ix..] {
17676                if range
17677                    .start
17678                    .cmp(&search_range.end, &display_snapshot.buffer_snapshot)
17679                    .is_ge()
17680                {
17681                    break;
17682                }
17683
17684                let start = range.start.to_display_point(display_snapshot);
17685                let end = range.end.to_display_point(display_snapshot);
17686                results.push((start..end, color))
17687            }
17688        }
17689        results
17690    }
17691
17692    pub fn background_highlight_row_ranges<T: 'static>(
17693        &self,
17694        search_range: Range<Anchor>,
17695        display_snapshot: &DisplaySnapshot,
17696        count: usize,
17697    ) -> Vec<RangeInclusive<DisplayPoint>> {
17698        let mut results = Vec::new();
17699        let Some((_, ranges)) = self.background_highlights.get(&TypeId::of::<T>()) else {
17700            return vec![];
17701        };
17702
17703        let start_ix = match ranges.binary_search_by(|probe| {
17704            let cmp = probe
17705                .end
17706                .cmp(&search_range.start, &display_snapshot.buffer_snapshot);
17707            if cmp.is_gt() {
17708                Ordering::Greater
17709            } else {
17710                Ordering::Less
17711            }
17712        }) {
17713            Ok(i) | Err(i) => i,
17714        };
17715        let mut push_region = |start: Option<Point>, end: Option<Point>| {
17716            if let (Some(start_display), Some(end_display)) = (start, end) {
17717                results.push(
17718                    start_display.to_display_point(display_snapshot)
17719                        ..=end_display.to_display_point(display_snapshot),
17720                );
17721            }
17722        };
17723        let mut start_row: Option<Point> = None;
17724        let mut end_row: Option<Point> = None;
17725        if ranges.len() > count {
17726            return Vec::new();
17727        }
17728        for range in &ranges[start_ix..] {
17729            if range
17730                .start
17731                .cmp(&search_range.end, &display_snapshot.buffer_snapshot)
17732                .is_ge()
17733            {
17734                break;
17735            }
17736            let end = range.end.to_point(&display_snapshot.buffer_snapshot);
17737            if let Some(current_row) = &end_row {
17738                if end.row == current_row.row {
17739                    continue;
17740                }
17741            }
17742            let start = range.start.to_point(&display_snapshot.buffer_snapshot);
17743            if start_row.is_none() {
17744                assert_eq!(end_row, None);
17745                start_row = Some(start);
17746                end_row = Some(end);
17747                continue;
17748            }
17749            if let Some(current_end) = end_row.as_mut() {
17750                if start.row > current_end.row + 1 {
17751                    push_region(start_row, end_row);
17752                    start_row = Some(start);
17753                    end_row = Some(end);
17754                } else {
17755                    // Merge two hunks.
17756                    *current_end = end;
17757                }
17758            } else {
17759                unreachable!();
17760            }
17761        }
17762        // We might still have a hunk that was not rendered (if there was a search hit on the last line)
17763        push_region(start_row, end_row);
17764        results
17765    }
17766
17767    pub fn gutter_highlights_in_range(
17768        &self,
17769        search_range: Range<Anchor>,
17770        display_snapshot: &DisplaySnapshot,
17771        cx: &App,
17772    ) -> Vec<(Range<DisplayPoint>, Hsla)> {
17773        let mut results = Vec::new();
17774        for (color_fetcher, ranges) in self.gutter_highlights.values() {
17775            let color = color_fetcher(cx);
17776            let start_ix = match ranges.binary_search_by(|probe| {
17777                let cmp = probe
17778                    .end
17779                    .cmp(&search_range.start, &display_snapshot.buffer_snapshot);
17780                if cmp.is_gt() {
17781                    Ordering::Greater
17782                } else {
17783                    Ordering::Less
17784                }
17785            }) {
17786                Ok(i) | Err(i) => i,
17787            };
17788            for range in &ranges[start_ix..] {
17789                if range
17790                    .start
17791                    .cmp(&search_range.end, &display_snapshot.buffer_snapshot)
17792                    .is_ge()
17793                {
17794                    break;
17795                }
17796
17797                let start = range.start.to_display_point(display_snapshot);
17798                let end = range.end.to_display_point(display_snapshot);
17799                results.push((start..end, color))
17800            }
17801        }
17802        results
17803    }
17804
17805    /// Get the text ranges corresponding to the redaction query
17806    pub fn redacted_ranges(
17807        &self,
17808        search_range: Range<Anchor>,
17809        display_snapshot: &DisplaySnapshot,
17810        cx: &App,
17811    ) -> Vec<Range<DisplayPoint>> {
17812        display_snapshot
17813            .buffer_snapshot
17814            .redacted_ranges(search_range, |file| {
17815                if let Some(file) = file {
17816                    file.is_private()
17817                        && EditorSettings::get(
17818                            Some(SettingsLocation {
17819                                worktree_id: file.worktree_id(cx),
17820                                path: file.path().as_ref(),
17821                            }),
17822                            cx,
17823                        )
17824                        .redact_private_values
17825                } else {
17826                    false
17827                }
17828            })
17829            .map(|range| {
17830                range.start.to_display_point(display_snapshot)
17831                    ..range.end.to_display_point(display_snapshot)
17832            })
17833            .collect()
17834    }
17835
17836    pub fn highlight_text<T: 'static>(
17837        &mut self,
17838        ranges: Vec<Range<Anchor>>,
17839        style: HighlightStyle,
17840        cx: &mut Context<Self>,
17841    ) {
17842        self.display_map.update(cx, |map, _| {
17843            map.highlight_text(TypeId::of::<T>(), ranges, style)
17844        });
17845        cx.notify();
17846    }
17847
17848    pub(crate) fn highlight_inlays<T: 'static>(
17849        &mut self,
17850        highlights: Vec<InlayHighlight>,
17851        style: HighlightStyle,
17852        cx: &mut Context<Self>,
17853    ) {
17854        self.display_map.update(cx, |map, _| {
17855            map.highlight_inlays(TypeId::of::<T>(), highlights, style)
17856        });
17857        cx.notify();
17858    }
17859
17860    pub fn text_highlights<'a, T: 'static>(
17861        &'a self,
17862        cx: &'a App,
17863    ) -> Option<(HighlightStyle, &'a [Range<Anchor>])> {
17864        self.display_map.read(cx).text_highlights(TypeId::of::<T>())
17865    }
17866
17867    pub fn clear_highlights<T: 'static>(&mut self, cx: &mut Context<Self>) {
17868        let cleared = self
17869            .display_map
17870            .update(cx, |map, _| map.clear_highlights(TypeId::of::<T>()));
17871        if cleared {
17872            cx.notify();
17873        }
17874    }
17875
17876    pub fn show_local_cursors(&self, window: &mut Window, cx: &mut App) -> bool {
17877        (self.read_only(cx) || self.blink_manager.read(cx).visible())
17878            && self.focus_handle.is_focused(window)
17879    }
17880
17881    pub fn set_show_cursor_when_unfocused(&mut self, is_enabled: bool, cx: &mut Context<Self>) {
17882        self.show_cursor_when_unfocused = is_enabled;
17883        cx.notify();
17884    }
17885
17886    fn on_buffer_changed(&mut self, _: Entity<MultiBuffer>, cx: &mut Context<Self>) {
17887        cx.notify();
17888    }
17889
17890    fn on_debug_session_event(
17891        &mut self,
17892        _session: Entity<Session>,
17893        event: &SessionEvent,
17894        cx: &mut Context<Self>,
17895    ) {
17896        match event {
17897            SessionEvent::InvalidateInlineValue => {
17898                self.refresh_inline_values(cx);
17899            }
17900            _ => {}
17901        }
17902    }
17903
17904    pub fn refresh_inline_values(&mut self, cx: &mut Context<Self>) {
17905        let Some(project) = self.project.clone() else {
17906            return;
17907        };
17908
17909        if !self.inline_value_cache.enabled {
17910            let inlays = std::mem::take(&mut self.inline_value_cache.inlays);
17911            self.splice_inlays(&inlays, Vec::new(), cx);
17912            return;
17913        }
17914
17915        let current_execution_position = self
17916            .highlighted_rows
17917            .get(&TypeId::of::<ActiveDebugLine>())
17918            .and_then(|lines| lines.last().map(|line| line.range.start));
17919
17920        self.inline_value_cache.refresh_task = cx.spawn(async move |editor, cx| {
17921            let snapshot = editor
17922                .update(cx, |editor, cx| editor.buffer().read(cx).snapshot(cx))
17923                .ok()?;
17924
17925            let inline_values = editor
17926                .update(cx, |editor, cx| {
17927                    let Some(current_execution_position) = current_execution_position else {
17928                        return Some(Task::ready(Ok(Vec::new())));
17929                    };
17930
17931                    let buffer = editor.buffer.read_with(cx, |buffer, cx| {
17932                        let snapshot = buffer.snapshot(cx);
17933
17934                        let excerpt = snapshot.excerpt_containing(
17935                            current_execution_position..current_execution_position,
17936                        )?;
17937
17938                        editor.buffer.read(cx).buffer(excerpt.buffer_id())
17939                    })?;
17940
17941                    let range =
17942                        buffer.read(cx).anchor_before(0)..current_execution_position.text_anchor;
17943
17944                    project.inline_values(buffer, range, cx)
17945                })
17946                .ok()
17947                .flatten()?
17948                .await
17949                .context("refreshing debugger inlays")
17950                .log_err()?;
17951
17952            let (excerpt_id, buffer_id) = snapshot
17953                .excerpts()
17954                .next()
17955                .map(|excerpt| (excerpt.0, excerpt.1.remote_id()))?;
17956            editor
17957                .update(cx, |editor, cx| {
17958                    let new_inlays = inline_values
17959                        .into_iter()
17960                        .map(|debugger_value| {
17961                            Inlay::debugger_hint(
17962                                post_inc(&mut editor.next_inlay_id),
17963                                Anchor::in_buffer(excerpt_id, buffer_id, debugger_value.position),
17964                                debugger_value.text(),
17965                            )
17966                        })
17967                        .collect::<Vec<_>>();
17968                    let mut inlay_ids = new_inlays.iter().map(|inlay| inlay.id).collect();
17969                    std::mem::swap(&mut editor.inline_value_cache.inlays, &mut inlay_ids);
17970
17971                    editor.splice_inlays(&inlay_ids, new_inlays, cx);
17972                })
17973                .ok()?;
17974            Some(())
17975        });
17976    }
17977
17978    fn on_buffer_event(
17979        &mut self,
17980        multibuffer: &Entity<MultiBuffer>,
17981        event: &multi_buffer::Event,
17982        window: &mut Window,
17983        cx: &mut Context<Self>,
17984    ) {
17985        match event {
17986            multi_buffer::Event::Edited {
17987                singleton_buffer_edited,
17988                edited_buffer: buffer_edited,
17989            } => {
17990                self.scrollbar_marker_state.dirty = true;
17991                self.active_indent_guides_state.dirty = true;
17992                self.refresh_active_diagnostics(cx);
17993                self.refresh_code_actions(window, cx);
17994                self.refresh_selected_text_highlights(true, window, cx);
17995                refresh_matching_bracket_highlights(self, window, cx);
17996                if self.has_active_inline_completion() {
17997                    self.update_visible_inline_completion(window, cx);
17998                }
17999                if let Some(buffer) = buffer_edited {
18000                    let buffer_id = buffer.read(cx).remote_id();
18001                    if !self.registered_buffers.contains_key(&buffer_id) {
18002                        if let Some(project) = self.project.as_ref() {
18003                            project.update(cx, |project, cx| {
18004                                self.registered_buffers.insert(
18005                                    buffer_id,
18006                                    project.register_buffer_with_language_servers(&buffer, cx),
18007                                );
18008                            })
18009                        }
18010                    }
18011                }
18012                cx.emit(EditorEvent::BufferEdited);
18013                cx.emit(SearchEvent::MatchesInvalidated);
18014                if *singleton_buffer_edited {
18015                    if let Some(project) = &self.project {
18016                        #[allow(clippy::mutable_key_type)]
18017                        let languages_affected = multibuffer.update(cx, |multibuffer, cx| {
18018                            multibuffer
18019                                .all_buffers()
18020                                .into_iter()
18021                                .filter_map(|buffer| {
18022                                    buffer.update(cx, |buffer, cx| {
18023                                        let language = buffer.language()?;
18024                                        let should_discard = project.update(cx, |project, cx| {
18025                                            project.is_local()
18026                                                && !project.has_language_servers_for(buffer, cx)
18027                                        });
18028                                        should_discard.not().then_some(language.clone())
18029                                    })
18030                                })
18031                                .collect::<HashSet<_>>()
18032                        });
18033                        if !languages_affected.is_empty() {
18034                            self.refresh_inlay_hints(
18035                                InlayHintRefreshReason::BufferEdited(languages_affected),
18036                                cx,
18037                            );
18038                        }
18039                    }
18040                }
18041
18042                let Some(project) = &self.project else { return };
18043                let (telemetry, is_via_ssh) = {
18044                    let project = project.read(cx);
18045                    let telemetry = project.client().telemetry().clone();
18046                    let is_via_ssh = project.is_via_ssh();
18047                    (telemetry, is_via_ssh)
18048                };
18049                refresh_linked_ranges(self, window, cx);
18050                telemetry.log_edit_event("editor", is_via_ssh);
18051            }
18052            multi_buffer::Event::ExcerptsAdded {
18053                buffer,
18054                predecessor,
18055                excerpts,
18056            } => {
18057                self.tasks_update_task = Some(self.refresh_runnables(window, cx));
18058                let buffer_id = buffer.read(cx).remote_id();
18059                if self.buffer.read(cx).diff_for(buffer_id).is_none() {
18060                    if let Some(project) = &self.project {
18061                        update_uncommitted_diff_for_buffer(
18062                            cx.entity(),
18063                            project,
18064                            [buffer.clone()],
18065                            self.buffer.clone(),
18066                            cx,
18067                        )
18068                        .detach();
18069                    }
18070                }
18071                cx.emit(EditorEvent::ExcerptsAdded {
18072                    buffer: buffer.clone(),
18073                    predecessor: *predecessor,
18074                    excerpts: excerpts.clone(),
18075                });
18076                self.refresh_inlay_hints(InlayHintRefreshReason::NewLinesShown, cx);
18077            }
18078            multi_buffer::Event::ExcerptsRemoved {
18079                ids,
18080                removed_buffer_ids,
18081            } => {
18082                self.refresh_inlay_hints(InlayHintRefreshReason::ExcerptsRemoved(ids.clone()), cx);
18083                let buffer = self.buffer.read(cx);
18084                self.registered_buffers
18085                    .retain(|buffer_id, _| buffer.buffer(*buffer_id).is_some());
18086                jsx_tag_auto_close::refresh_enabled_in_any_buffer(self, multibuffer, cx);
18087                cx.emit(EditorEvent::ExcerptsRemoved {
18088                    ids: ids.clone(),
18089                    removed_buffer_ids: removed_buffer_ids.clone(),
18090                })
18091            }
18092            multi_buffer::Event::ExcerptsEdited {
18093                excerpt_ids,
18094                buffer_ids,
18095            } => {
18096                self.display_map.update(cx, |map, cx| {
18097                    map.unfold_buffers(buffer_ids.iter().copied(), cx)
18098                });
18099                cx.emit(EditorEvent::ExcerptsEdited {
18100                    ids: excerpt_ids.clone(),
18101                })
18102            }
18103            multi_buffer::Event::ExcerptsExpanded { ids } => {
18104                self.refresh_inlay_hints(InlayHintRefreshReason::NewLinesShown, cx);
18105                cx.emit(EditorEvent::ExcerptsExpanded { ids: ids.clone() })
18106            }
18107            multi_buffer::Event::Reparsed(buffer_id) => {
18108                self.tasks_update_task = Some(self.refresh_runnables(window, cx));
18109                jsx_tag_auto_close::refresh_enabled_in_any_buffer(self, multibuffer, cx);
18110
18111                cx.emit(EditorEvent::Reparsed(*buffer_id));
18112            }
18113            multi_buffer::Event::DiffHunksToggled => {
18114                self.tasks_update_task = Some(self.refresh_runnables(window, cx));
18115            }
18116            multi_buffer::Event::LanguageChanged(buffer_id) => {
18117                linked_editing_ranges::refresh_linked_ranges(self, window, cx);
18118                jsx_tag_auto_close::refresh_enabled_in_any_buffer(self, multibuffer, cx);
18119                cx.emit(EditorEvent::Reparsed(*buffer_id));
18120                cx.notify();
18121            }
18122            multi_buffer::Event::DirtyChanged => cx.emit(EditorEvent::DirtyChanged),
18123            multi_buffer::Event::Saved => cx.emit(EditorEvent::Saved),
18124            multi_buffer::Event::FileHandleChanged
18125            | multi_buffer::Event::Reloaded
18126            | multi_buffer::Event::BufferDiffChanged => cx.emit(EditorEvent::TitleChanged),
18127            multi_buffer::Event::Closed => cx.emit(EditorEvent::Closed),
18128            multi_buffer::Event::DiagnosticsUpdated => {
18129                self.refresh_active_diagnostics(cx);
18130                self.refresh_inline_diagnostics(true, window, cx);
18131                self.scrollbar_marker_state.dirty = true;
18132                cx.notify();
18133            }
18134            _ => {}
18135        };
18136    }
18137
18138    pub fn start_temporary_diff_override(&mut self) {
18139        self.load_diff_task.take();
18140        self.temporary_diff_override = true;
18141    }
18142
18143    pub fn end_temporary_diff_override(&mut self, cx: &mut Context<Self>) {
18144        self.temporary_diff_override = false;
18145        self.set_render_diff_hunk_controls(Arc::new(render_diff_hunk_controls), cx);
18146        self.buffer.update(cx, |buffer, cx| {
18147            buffer.set_all_diff_hunks_collapsed(cx);
18148        });
18149
18150        if let Some(project) = self.project.clone() {
18151            self.load_diff_task = Some(
18152                update_uncommitted_diff_for_buffer(
18153                    cx.entity(),
18154                    &project,
18155                    self.buffer.read(cx).all_buffers(),
18156                    self.buffer.clone(),
18157                    cx,
18158                )
18159                .shared(),
18160            );
18161        }
18162    }
18163
18164    fn on_display_map_changed(
18165        &mut self,
18166        _: Entity<DisplayMap>,
18167        _: &mut Window,
18168        cx: &mut Context<Self>,
18169    ) {
18170        cx.notify();
18171    }
18172
18173    fn settings_changed(&mut self, window: &mut Window, cx: &mut Context<Self>) {
18174        let new_severity = if self.diagnostics_enabled() {
18175            EditorSettings::get_global(cx)
18176                .diagnostics_max_severity
18177                .unwrap_or(DiagnosticSeverity::Hint)
18178        } else {
18179            DiagnosticSeverity::Off
18180        };
18181        self.set_max_diagnostics_severity(new_severity, cx);
18182        self.tasks_update_task = Some(self.refresh_runnables(window, cx));
18183        self.update_edit_prediction_settings(cx);
18184        self.refresh_inline_completion(true, false, window, cx);
18185        self.refresh_inlay_hints(
18186            InlayHintRefreshReason::SettingsChange(inlay_hint_settings(
18187                self.selections.newest_anchor().head(),
18188                &self.buffer.read(cx).snapshot(cx),
18189                cx,
18190            )),
18191            cx,
18192        );
18193
18194        let old_cursor_shape = self.cursor_shape;
18195
18196        {
18197            let editor_settings = EditorSettings::get_global(cx);
18198            self.scroll_manager.vertical_scroll_margin = editor_settings.vertical_scroll_margin;
18199            self.show_breadcrumbs = editor_settings.toolbar.breadcrumbs;
18200            self.cursor_shape = editor_settings.cursor_shape.unwrap_or_default();
18201            self.hide_mouse_mode = editor_settings.hide_mouse.unwrap_or_default();
18202        }
18203
18204        if old_cursor_shape != self.cursor_shape {
18205            cx.emit(EditorEvent::CursorShapeChanged);
18206        }
18207
18208        let project_settings = ProjectSettings::get_global(cx);
18209        self.serialize_dirty_buffers =
18210            !self.mode.is_minimap() && project_settings.session.restore_unsaved_buffers;
18211
18212        if self.mode.is_full() {
18213            let show_inline_diagnostics = project_settings.diagnostics.inline.enabled;
18214            let inline_blame_enabled = project_settings.git.inline_blame_enabled();
18215            if self.show_inline_diagnostics != show_inline_diagnostics {
18216                self.show_inline_diagnostics = show_inline_diagnostics;
18217                self.refresh_inline_diagnostics(false, window, cx);
18218            }
18219
18220            if self.git_blame_inline_enabled != inline_blame_enabled {
18221                self.toggle_git_blame_inline_internal(false, window, cx);
18222            }
18223
18224            let minimap_settings = EditorSettings::get_global(cx).minimap;
18225            if self.minimap_visibility.visible() != minimap_settings.minimap_enabled() {
18226                self.set_minimap_visibility(
18227                    self.minimap_visibility.toggle_visibility(),
18228                    window,
18229                    cx,
18230                );
18231            } else if let Some(minimap_entity) = self.minimap.as_ref() {
18232                minimap_entity.update(cx, |minimap_editor, cx| {
18233                    minimap_editor.update_minimap_configuration(minimap_settings, cx)
18234                })
18235            }
18236        }
18237
18238        cx.notify();
18239    }
18240
18241    pub fn set_searchable(&mut self, searchable: bool) {
18242        self.searchable = searchable;
18243    }
18244
18245    pub fn searchable(&self) -> bool {
18246        self.searchable
18247    }
18248
18249    fn open_proposed_changes_editor(
18250        &mut self,
18251        _: &OpenProposedChangesEditor,
18252        window: &mut Window,
18253        cx: &mut Context<Self>,
18254    ) {
18255        let Some(workspace) = self.workspace() else {
18256            cx.propagate();
18257            return;
18258        };
18259
18260        let selections = self.selections.all::<usize>(cx);
18261        let multi_buffer = self.buffer.read(cx);
18262        let multi_buffer_snapshot = multi_buffer.snapshot(cx);
18263        let mut new_selections_by_buffer = HashMap::default();
18264        for selection in selections {
18265            for (buffer, range, _) in
18266                multi_buffer_snapshot.range_to_buffer_ranges(selection.start..selection.end)
18267            {
18268                let mut range = range.to_point(buffer);
18269                range.start.column = 0;
18270                range.end.column = buffer.line_len(range.end.row);
18271                new_selections_by_buffer
18272                    .entry(multi_buffer.buffer(buffer.remote_id()).unwrap())
18273                    .or_insert(Vec::new())
18274                    .push(range)
18275            }
18276        }
18277
18278        let proposed_changes_buffers = new_selections_by_buffer
18279            .into_iter()
18280            .map(|(buffer, ranges)| ProposedChangeLocation { buffer, ranges })
18281            .collect::<Vec<_>>();
18282        let proposed_changes_editor = cx.new(|cx| {
18283            ProposedChangesEditor::new(
18284                "Proposed changes",
18285                proposed_changes_buffers,
18286                self.project.clone(),
18287                window,
18288                cx,
18289            )
18290        });
18291
18292        window.defer(cx, move |window, cx| {
18293            workspace.update(cx, |workspace, cx| {
18294                workspace.active_pane().update(cx, |pane, cx| {
18295                    pane.add_item(
18296                        Box::new(proposed_changes_editor),
18297                        true,
18298                        true,
18299                        None,
18300                        window,
18301                        cx,
18302                    );
18303                });
18304            });
18305        });
18306    }
18307
18308    pub fn open_excerpts_in_split(
18309        &mut self,
18310        _: &OpenExcerptsSplit,
18311        window: &mut Window,
18312        cx: &mut Context<Self>,
18313    ) {
18314        self.open_excerpts_common(None, true, window, cx)
18315    }
18316
18317    pub fn open_excerpts(&mut self, _: &OpenExcerpts, window: &mut Window, cx: &mut Context<Self>) {
18318        self.open_excerpts_common(None, false, window, cx)
18319    }
18320
18321    fn open_excerpts_common(
18322        &mut self,
18323        jump_data: Option<JumpData>,
18324        split: bool,
18325        window: &mut Window,
18326        cx: &mut Context<Self>,
18327    ) {
18328        let Some(workspace) = self.workspace() else {
18329            cx.propagate();
18330            return;
18331        };
18332
18333        if self.buffer.read(cx).is_singleton() {
18334            cx.propagate();
18335            return;
18336        }
18337
18338        let mut new_selections_by_buffer = HashMap::default();
18339        match &jump_data {
18340            Some(JumpData::MultiBufferPoint {
18341                excerpt_id,
18342                position,
18343                anchor,
18344                line_offset_from_top,
18345            }) => {
18346                let multi_buffer_snapshot = self.buffer.read(cx).snapshot(cx);
18347                if let Some(buffer) = multi_buffer_snapshot
18348                    .buffer_id_for_excerpt(*excerpt_id)
18349                    .and_then(|buffer_id| self.buffer.read(cx).buffer(buffer_id))
18350                {
18351                    let buffer_snapshot = buffer.read(cx).snapshot();
18352                    let jump_to_point = if buffer_snapshot.can_resolve(anchor) {
18353                        language::ToPoint::to_point(anchor, &buffer_snapshot)
18354                    } else {
18355                        buffer_snapshot.clip_point(*position, Bias::Left)
18356                    };
18357                    let jump_to_offset = buffer_snapshot.point_to_offset(jump_to_point);
18358                    new_selections_by_buffer.insert(
18359                        buffer,
18360                        (
18361                            vec![jump_to_offset..jump_to_offset],
18362                            Some(*line_offset_from_top),
18363                        ),
18364                    );
18365                }
18366            }
18367            Some(JumpData::MultiBufferRow {
18368                row,
18369                line_offset_from_top,
18370            }) => {
18371                let point = MultiBufferPoint::new(row.0, 0);
18372                if let Some((buffer, buffer_point, _)) =
18373                    self.buffer.read(cx).point_to_buffer_point(point, cx)
18374                {
18375                    let buffer_offset = buffer.read(cx).point_to_offset(buffer_point);
18376                    new_selections_by_buffer
18377                        .entry(buffer)
18378                        .or_insert((Vec::new(), Some(*line_offset_from_top)))
18379                        .0
18380                        .push(buffer_offset..buffer_offset)
18381                }
18382            }
18383            None => {
18384                let selections = self.selections.all::<usize>(cx);
18385                let multi_buffer = self.buffer.read(cx);
18386                for selection in selections {
18387                    for (snapshot, range, _, anchor) in multi_buffer
18388                        .snapshot(cx)
18389                        .range_to_buffer_ranges_with_deleted_hunks(selection.range())
18390                    {
18391                        if let Some(anchor) = anchor {
18392                            // selection is in a deleted hunk
18393                            let Some(buffer_id) = anchor.buffer_id else {
18394                                continue;
18395                            };
18396                            let Some(buffer_handle) = multi_buffer.buffer(buffer_id) else {
18397                                continue;
18398                            };
18399                            let offset = text::ToOffset::to_offset(
18400                                &anchor.text_anchor,
18401                                &buffer_handle.read(cx).snapshot(),
18402                            );
18403                            let range = offset..offset;
18404                            new_selections_by_buffer
18405                                .entry(buffer_handle)
18406                                .or_insert((Vec::new(), None))
18407                                .0
18408                                .push(range)
18409                        } else {
18410                            let Some(buffer_handle) = multi_buffer.buffer(snapshot.remote_id())
18411                            else {
18412                                continue;
18413                            };
18414                            new_selections_by_buffer
18415                                .entry(buffer_handle)
18416                                .or_insert((Vec::new(), None))
18417                                .0
18418                                .push(range)
18419                        }
18420                    }
18421                }
18422            }
18423        }
18424
18425        new_selections_by_buffer
18426            .retain(|buffer, _| Self::can_open_excerpts_in_file(buffer.read(cx).file()));
18427
18428        if new_selections_by_buffer.is_empty() {
18429            return;
18430        }
18431
18432        // We defer the pane interaction because we ourselves are a workspace item
18433        // and activating a new item causes the pane to call a method on us reentrantly,
18434        // which panics if we're on the stack.
18435        window.defer(cx, move |window, cx| {
18436            workspace.update(cx, |workspace, cx| {
18437                let pane = if split {
18438                    workspace.adjacent_pane(window, cx)
18439                } else {
18440                    workspace.active_pane().clone()
18441                };
18442
18443                for (buffer, (ranges, scroll_offset)) in new_selections_by_buffer {
18444                    let editor = buffer
18445                        .read(cx)
18446                        .file()
18447                        .is_none()
18448                        .then(|| {
18449                            // Handle file-less buffers separately: those are not really the project items, so won't have a project path or entity id,
18450                            // so `workspace.open_project_item` will never find them, always opening a new editor.
18451                            // Instead, we try to activate the existing editor in the pane first.
18452                            let (editor, pane_item_index) =
18453                                pane.read(cx).items().enumerate().find_map(|(i, item)| {
18454                                    let editor = item.downcast::<Editor>()?;
18455                                    let singleton_buffer =
18456                                        editor.read(cx).buffer().read(cx).as_singleton()?;
18457                                    if singleton_buffer == buffer {
18458                                        Some((editor, i))
18459                                    } else {
18460                                        None
18461                                    }
18462                                })?;
18463                            pane.update(cx, |pane, cx| {
18464                                pane.activate_item(pane_item_index, true, true, window, cx)
18465                            });
18466                            Some(editor)
18467                        })
18468                        .flatten()
18469                        .unwrap_or_else(|| {
18470                            workspace.open_project_item::<Self>(
18471                                pane.clone(),
18472                                buffer,
18473                                true,
18474                                true,
18475                                window,
18476                                cx,
18477                            )
18478                        });
18479
18480                    editor.update(cx, |editor, cx| {
18481                        let autoscroll = match scroll_offset {
18482                            Some(scroll_offset) => Autoscroll::top_relative(scroll_offset as usize),
18483                            None => Autoscroll::newest(),
18484                        };
18485                        let nav_history = editor.nav_history.take();
18486                        editor.change_selections(Some(autoscroll), window, cx, |s| {
18487                            s.select_ranges(ranges);
18488                        });
18489                        editor.nav_history = nav_history;
18490                    });
18491                }
18492            })
18493        });
18494    }
18495
18496    // For now, don't allow opening excerpts in buffers that aren't backed by
18497    // regular project files.
18498    fn can_open_excerpts_in_file(file: Option<&Arc<dyn language::File>>) -> bool {
18499        file.map_or(true, |file| project::File::from_dyn(Some(file)).is_some())
18500    }
18501
18502    fn marked_text_ranges(&self, cx: &App) -> Option<Vec<Range<OffsetUtf16>>> {
18503        let snapshot = self.buffer.read(cx).read(cx);
18504        let (_, ranges) = self.text_highlights::<InputComposition>(cx)?;
18505        Some(
18506            ranges
18507                .iter()
18508                .map(move |range| {
18509                    range.start.to_offset_utf16(&snapshot)..range.end.to_offset_utf16(&snapshot)
18510                })
18511                .collect(),
18512        )
18513    }
18514
18515    fn selection_replacement_ranges(
18516        &self,
18517        range: Range<OffsetUtf16>,
18518        cx: &mut App,
18519    ) -> Vec<Range<OffsetUtf16>> {
18520        let selections = self.selections.all::<OffsetUtf16>(cx);
18521        let newest_selection = selections
18522            .iter()
18523            .max_by_key(|selection| selection.id)
18524            .unwrap();
18525        let start_delta = range.start.0 as isize - newest_selection.start.0 as isize;
18526        let end_delta = range.end.0 as isize - newest_selection.end.0 as isize;
18527        let snapshot = self.buffer.read(cx).read(cx);
18528        selections
18529            .into_iter()
18530            .map(|mut selection| {
18531                selection.start.0 =
18532                    (selection.start.0 as isize).saturating_add(start_delta) as usize;
18533                selection.end.0 = (selection.end.0 as isize).saturating_add(end_delta) as usize;
18534                snapshot.clip_offset_utf16(selection.start, Bias::Left)
18535                    ..snapshot.clip_offset_utf16(selection.end, Bias::Right)
18536            })
18537            .collect()
18538    }
18539
18540    fn report_editor_event(
18541        &self,
18542        event_type: &'static str,
18543        file_extension: Option<String>,
18544        cx: &App,
18545    ) {
18546        if cfg!(any(test, feature = "test-support")) {
18547            return;
18548        }
18549
18550        let Some(project) = &self.project else { return };
18551
18552        // If None, we are in a file without an extension
18553        let file = self
18554            .buffer
18555            .read(cx)
18556            .as_singleton()
18557            .and_then(|b| b.read(cx).file());
18558        let file_extension = file_extension.or(file
18559            .as_ref()
18560            .and_then(|file| Path::new(file.file_name(cx)).extension())
18561            .and_then(|e| e.to_str())
18562            .map(|a| a.to_string()));
18563
18564        let vim_mode = vim_enabled(cx);
18565
18566        let edit_predictions_provider = all_language_settings(file, cx).edit_predictions.provider;
18567        let copilot_enabled = edit_predictions_provider
18568            == language::language_settings::EditPredictionProvider::Copilot;
18569        let copilot_enabled_for_language = self
18570            .buffer
18571            .read(cx)
18572            .language_settings(cx)
18573            .show_edit_predictions;
18574
18575        let project = project.read(cx);
18576        telemetry::event!(
18577            event_type,
18578            file_extension,
18579            vim_mode,
18580            copilot_enabled,
18581            copilot_enabled_for_language,
18582            edit_predictions_provider,
18583            is_via_ssh = project.is_via_ssh(),
18584        );
18585    }
18586
18587    /// Copy the highlighted chunks to the clipboard as JSON. The format is an array of lines,
18588    /// with each line being an array of {text, highlight} objects.
18589    fn copy_highlight_json(
18590        &mut self,
18591        _: &CopyHighlightJson,
18592        window: &mut Window,
18593        cx: &mut Context<Self>,
18594    ) {
18595        #[derive(Serialize)]
18596        struct Chunk<'a> {
18597            text: String,
18598            highlight: Option<&'a str>,
18599        }
18600
18601        let snapshot = self.buffer.read(cx).snapshot(cx);
18602        let range = self
18603            .selected_text_range(false, window, cx)
18604            .and_then(|selection| {
18605                if selection.range.is_empty() {
18606                    None
18607                } else {
18608                    Some(selection.range)
18609                }
18610            })
18611            .unwrap_or_else(|| 0..snapshot.len());
18612
18613        let chunks = snapshot.chunks(range, true);
18614        let mut lines = Vec::new();
18615        let mut line: VecDeque<Chunk> = VecDeque::new();
18616
18617        let Some(style) = self.style.as_ref() else {
18618            return;
18619        };
18620
18621        for chunk in chunks {
18622            let highlight = chunk
18623                .syntax_highlight_id
18624                .and_then(|id| id.name(&style.syntax));
18625            let mut chunk_lines = chunk.text.split('\n').peekable();
18626            while let Some(text) = chunk_lines.next() {
18627                let mut merged_with_last_token = false;
18628                if let Some(last_token) = line.back_mut() {
18629                    if last_token.highlight == highlight {
18630                        last_token.text.push_str(text);
18631                        merged_with_last_token = true;
18632                    }
18633                }
18634
18635                if !merged_with_last_token {
18636                    line.push_back(Chunk {
18637                        text: text.into(),
18638                        highlight,
18639                    });
18640                }
18641
18642                if chunk_lines.peek().is_some() {
18643                    if line.len() > 1 && line.front().unwrap().text.is_empty() {
18644                        line.pop_front();
18645                    }
18646                    if line.len() > 1 && line.back().unwrap().text.is_empty() {
18647                        line.pop_back();
18648                    }
18649
18650                    lines.push(mem::take(&mut line));
18651                }
18652            }
18653        }
18654
18655        let Some(lines) = serde_json::to_string_pretty(&lines).log_err() else {
18656            return;
18657        };
18658        cx.write_to_clipboard(ClipboardItem::new_string(lines));
18659    }
18660
18661    pub fn open_context_menu(
18662        &mut self,
18663        _: &OpenContextMenu,
18664        window: &mut Window,
18665        cx: &mut Context<Self>,
18666    ) {
18667        self.request_autoscroll(Autoscroll::newest(), cx);
18668        let position = self.selections.newest_display(cx).start;
18669        mouse_context_menu::deploy_context_menu(self, None, position, window, cx);
18670    }
18671
18672    pub fn inlay_hint_cache(&self) -> &InlayHintCache {
18673        &self.inlay_hint_cache
18674    }
18675
18676    pub fn replay_insert_event(
18677        &mut self,
18678        text: &str,
18679        relative_utf16_range: Option<Range<isize>>,
18680        window: &mut Window,
18681        cx: &mut Context<Self>,
18682    ) {
18683        if !self.input_enabled {
18684            cx.emit(EditorEvent::InputIgnored { text: text.into() });
18685            return;
18686        }
18687        if let Some(relative_utf16_range) = relative_utf16_range {
18688            let selections = self.selections.all::<OffsetUtf16>(cx);
18689            self.change_selections(None, window, cx, |s| {
18690                let new_ranges = selections.into_iter().map(|range| {
18691                    let start = OffsetUtf16(
18692                        range
18693                            .head()
18694                            .0
18695                            .saturating_add_signed(relative_utf16_range.start),
18696                    );
18697                    let end = OffsetUtf16(
18698                        range
18699                            .head()
18700                            .0
18701                            .saturating_add_signed(relative_utf16_range.end),
18702                    );
18703                    start..end
18704                });
18705                s.select_ranges(new_ranges);
18706            });
18707        }
18708
18709        self.handle_input(text, window, cx);
18710    }
18711
18712    pub fn supports_inlay_hints(&self, cx: &mut App) -> bool {
18713        let Some(provider) = self.semantics_provider.as_ref() else {
18714            return false;
18715        };
18716
18717        let mut supports = false;
18718        self.buffer().update(cx, |this, cx| {
18719            this.for_each_buffer(|buffer| {
18720                supports |= provider.supports_inlay_hints(buffer, cx);
18721            });
18722        });
18723
18724        supports
18725    }
18726
18727    pub fn is_focused(&self, window: &Window) -> bool {
18728        self.focus_handle.is_focused(window)
18729    }
18730
18731    fn handle_focus(&mut self, window: &mut Window, cx: &mut Context<Self>) {
18732        cx.emit(EditorEvent::Focused);
18733
18734        if let Some(descendant) = self
18735            .last_focused_descendant
18736            .take()
18737            .and_then(|descendant| descendant.upgrade())
18738        {
18739            window.focus(&descendant);
18740        } else {
18741            if let Some(blame) = self.blame.as_ref() {
18742                blame.update(cx, GitBlame::focus)
18743            }
18744
18745            self.blink_manager.update(cx, BlinkManager::enable);
18746            self.show_cursor_names(window, cx);
18747            self.buffer.update(cx, |buffer, cx| {
18748                buffer.finalize_last_transaction(cx);
18749                if self.leader_id.is_none() {
18750                    buffer.set_active_selections(
18751                        &self.selections.disjoint_anchors(),
18752                        self.selections.line_mode,
18753                        self.cursor_shape,
18754                        cx,
18755                    );
18756                }
18757            });
18758        }
18759    }
18760
18761    fn handle_focus_in(&mut self, _: &mut Window, cx: &mut Context<Self>) {
18762        cx.emit(EditorEvent::FocusedIn)
18763    }
18764
18765    fn handle_focus_out(
18766        &mut self,
18767        event: FocusOutEvent,
18768        _window: &mut Window,
18769        cx: &mut Context<Self>,
18770    ) {
18771        if event.blurred != self.focus_handle {
18772            self.last_focused_descendant = Some(event.blurred);
18773        }
18774        self.refresh_inlay_hints(InlayHintRefreshReason::ModifiersChanged(false), cx);
18775    }
18776
18777    pub fn handle_blur(&mut self, window: &mut Window, cx: &mut Context<Self>) {
18778        self.blink_manager.update(cx, BlinkManager::disable);
18779        self.buffer
18780            .update(cx, |buffer, cx| buffer.remove_active_selections(cx));
18781
18782        if let Some(blame) = self.blame.as_ref() {
18783            blame.update(cx, GitBlame::blur)
18784        }
18785        if !self.hover_state.focused(window, cx) {
18786            hide_hover(self, cx);
18787        }
18788        if !self
18789            .context_menu
18790            .borrow()
18791            .as_ref()
18792            .is_some_and(|context_menu| context_menu.focused(window, cx))
18793        {
18794            self.hide_context_menu(window, cx);
18795        }
18796        self.discard_inline_completion(false, cx);
18797        cx.emit(EditorEvent::Blurred);
18798        cx.notify();
18799    }
18800
18801    pub fn register_action<A: Action>(
18802        &mut self,
18803        listener: impl Fn(&A, &mut Window, &mut App) + 'static,
18804    ) -> Subscription {
18805        let id = self.next_editor_action_id.post_inc();
18806        let listener = Arc::new(listener);
18807        self.editor_actions.borrow_mut().insert(
18808            id,
18809            Box::new(move |window, _| {
18810                let listener = listener.clone();
18811                window.on_action(TypeId::of::<A>(), move |action, phase, window, cx| {
18812                    let action = action.downcast_ref().unwrap();
18813                    if phase == DispatchPhase::Bubble {
18814                        listener(action, window, cx)
18815                    }
18816                })
18817            }),
18818        );
18819
18820        let editor_actions = self.editor_actions.clone();
18821        Subscription::new(move || {
18822            editor_actions.borrow_mut().remove(&id);
18823        })
18824    }
18825
18826    pub fn file_header_size(&self) -> u32 {
18827        FILE_HEADER_HEIGHT
18828    }
18829
18830    pub fn restore(
18831        &mut self,
18832        revert_changes: HashMap<BufferId, Vec<(Range<text::Anchor>, Rope)>>,
18833        window: &mut Window,
18834        cx: &mut Context<Self>,
18835    ) {
18836        let workspace = self.workspace();
18837        let project = self.project.as_ref();
18838        let save_tasks = self.buffer().update(cx, |multi_buffer, cx| {
18839            let mut tasks = Vec::new();
18840            for (buffer_id, changes) in revert_changes {
18841                if let Some(buffer) = multi_buffer.buffer(buffer_id) {
18842                    buffer.update(cx, |buffer, cx| {
18843                        buffer.edit(
18844                            changes
18845                                .into_iter()
18846                                .map(|(range, text)| (range, text.to_string())),
18847                            None,
18848                            cx,
18849                        );
18850                    });
18851
18852                    if let Some(project) =
18853                        project.filter(|_| multi_buffer.all_diff_hunks_expanded())
18854                    {
18855                        project.update(cx, |project, cx| {
18856                            tasks.push((buffer.clone(), project.save_buffer(buffer, cx)));
18857                        })
18858                    }
18859                }
18860            }
18861            tasks
18862        });
18863        cx.spawn_in(window, async move |_, cx| {
18864            for (buffer, task) in save_tasks {
18865                let result = task.await;
18866                if result.is_err() {
18867                    let Some(path) = buffer
18868                        .read_with(cx, |buffer, cx| buffer.project_path(cx))
18869                        .ok()
18870                    else {
18871                        continue;
18872                    };
18873                    if let Some((workspace, path)) = workspace.as_ref().zip(path) {
18874                        let Some(task) = cx
18875                            .update_window_entity(&workspace, |workspace, window, cx| {
18876                                workspace
18877                                    .open_path_preview(path, None, false, false, false, window, cx)
18878                            })
18879                            .ok()
18880                        else {
18881                            continue;
18882                        };
18883                        task.await.log_err();
18884                    }
18885                }
18886            }
18887        })
18888        .detach();
18889        self.change_selections(None, window, cx, |selections| selections.refresh());
18890    }
18891
18892    pub fn to_pixel_point(
18893        &self,
18894        source: multi_buffer::Anchor,
18895        editor_snapshot: &EditorSnapshot,
18896        window: &mut Window,
18897    ) -> Option<gpui::Point<Pixels>> {
18898        let source_point = source.to_display_point(editor_snapshot);
18899        self.display_to_pixel_point(source_point, editor_snapshot, window)
18900    }
18901
18902    pub fn display_to_pixel_point(
18903        &self,
18904        source: DisplayPoint,
18905        editor_snapshot: &EditorSnapshot,
18906        window: &mut Window,
18907    ) -> Option<gpui::Point<Pixels>> {
18908        let line_height = self.style()?.text.line_height_in_pixels(window.rem_size());
18909        let text_layout_details = self.text_layout_details(window);
18910        let scroll_top = text_layout_details
18911            .scroll_anchor
18912            .scroll_position(editor_snapshot)
18913            .y;
18914
18915        if source.row().as_f32() < scroll_top.floor() {
18916            return None;
18917        }
18918        let source_x = editor_snapshot.x_for_display_point(source, &text_layout_details);
18919        let source_y = line_height * (source.row().as_f32() - scroll_top);
18920        Some(gpui::Point::new(source_x, source_y))
18921    }
18922
18923    pub fn has_visible_completions_menu(&self) -> bool {
18924        !self.edit_prediction_preview_is_active()
18925            && self.context_menu.borrow().as_ref().map_or(false, |menu| {
18926                menu.visible() && matches!(menu, CodeContextMenu::Completions(_))
18927            })
18928    }
18929
18930    pub fn register_addon<T: Addon>(&mut self, instance: T) {
18931        if self.mode.is_minimap() {
18932            return;
18933        }
18934        self.addons
18935            .insert(std::any::TypeId::of::<T>(), Box::new(instance));
18936    }
18937
18938    pub fn unregister_addon<T: Addon>(&mut self) {
18939        self.addons.remove(&std::any::TypeId::of::<T>());
18940    }
18941
18942    pub fn addon<T: Addon>(&self) -> Option<&T> {
18943        let type_id = std::any::TypeId::of::<T>();
18944        self.addons
18945            .get(&type_id)
18946            .and_then(|item| item.to_any().downcast_ref::<T>())
18947    }
18948
18949    pub fn addon_mut<T: Addon>(&mut self) -> Option<&mut T> {
18950        let type_id = std::any::TypeId::of::<T>();
18951        self.addons
18952            .get_mut(&type_id)
18953            .and_then(|item| item.to_any_mut()?.downcast_mut::<T>())
18954    }
18955
18956    fn character_size(&self, window: &mut Window) -> gpui::Size<Pixels> {
18957        let text_layout_details = self.text_layout_details(window);
18958        let style = &text_layout_details.editor_style;
18959        let font_id = window.text_system().resolve_font(&style.text.font());
18960        let font_size = style.text.font_size.to_pixels(window.rem_size());
18961        let line_height = style.text.line_height_in_pixels(window.rem_size());
18962        let em_width = window.text_system().em_width(font_id, font_size).unwrap();
18963
18964        gpui::Size::new(em_width, line_height)
18965    }
18966
18967    pub fn wait_for_diff_to_load(&self) -> Option<Shared<Task<()>>> {
18968        self.load_diff_task.clone()
18969    }
18970
18971    fn read_metadata_from_db(
18972        &mut self,
18973        item_id: u64,
18974        workspace_id: WorkspaceId,
18975        window: &mut Window,
18976        cx: &mut Context<Editor>,
18977    ) {
18978        if self.is_singleton(cx)
18979            && !self.mode.is_minimap()
18980            && WorkspaceSettings::get(None, cx).restore_on_startup != RestoreOnStartupBehavior::None
18981        {
18982            let buffer_snapshot = OnceCell::new();
18983
18984            if let Some(folds) = DB.get_editor_folds(item_id, workspace_id).log_err() {
18985                if !folds.is_empty() {
18986                    let snapshot =
18987                        buffer_snapshot.get_or_init(|| self.buffer.read(cx).snapshot(cx));
18988                    self.fold_ranges(
18989                        folds
18990                            .into_iter()
18991                            .map(|(start, end)| {
18992                                snapshot.clip_offset(start, Bias::Left)
18993                                    ..snapshot.clip_offset(end, Bias::Right)
18994                            })
18995                            .collect(),
18996                        false,
18997                        window,
18998                        cx,
18999                    );
19000                }
19001            }
19002
19003            if let Some(selections) = DB.get_editor_selections(item_id, workspace_id).log_err() {
19004                if !selections.is_empty() {
19005                    let snapshot =
19006                        buffer_snapshot.get_or_init(|| self.buffer.read(cx).snapshot(cx));
19007                    self.change_selections(None, window, cx, |s| {
19008                        s.select_ranges(selections.into_iter().map(|(start, end)| {
19009                            snapshot.clip_offset(start, Bias::Left)
19010                                ..snapshot.clip_offset(end, Bias::Right)
19011                        }));
19012                    });
19013                }
19014            };
19015        }
19016
19017        self.read_scroll_position_from_db(item_id, workspace_id, window, cx);
19018    }
19019}
19020
19021fn vim_enabled(cx: &App) -> bool {
19022    cx.global::<SettingsStore>()
19023        .raw_user_settings()
19024        .get("vim_mode")
19025        == Some(&serde_json::Value::Bool(true))
19026}
19027
19028// Consider user intent and default settings
19029fn choose_completion_range(
19030    completion: &Completion,
19031    intent: CompletionIntent,
19032    buffer: &Entity<Buffer>,
19033    cx: &mut Context<Editor>,
19034) -> Range<usize> {
19035    fn should_replace(
19036        completion: &Completion,
19037        insert_range: &Range<text::Anchor>,
19038        intent: CompletionIntent,
19039        completion_mode_setting: LspInsertMode,
19040        buffer: &Buffer,
19041    ) -> bool {
19042        // specific actions take precedence over settings
19043        match intent {
19044            CompletionIntent::CompleteWithInsert => return false,
19045            CompletionIntent::CompleteWithReplace => return true,
19046            CompletionIntent::Complete | CompletionIntent::Compose => {}
19047        }
19048
19049        match completion_mode_setting {
19050            LspInsertMode::Insert => false,
19051            LspInsertMode::Replace => true,
19052            LspInsertMode::ReplaceSubsequence => {
19053                let mut text_to_replace = buffer.chars_for_range(
19054                    buffer.anchor_before(completion.replace_range.start)
19055                        ..buffer.anchor_after(completion.replace_range.end),
19056                );
19057                let mut completion_text = completion.new_text.chars();
19058
19059                // is `text_to_replace` a subsequence of `completion_text`
19060                text_to_replace
19061                    .all(|needle_ch| completion_text.any(|haystack_ch| haystack_ch == needle_ch))
19062            }
19063            LspInsertMode::ReplaceSuffix => {
19064                let range_after_cursor = insert_range.end..completion.replace_range.end;
19065
19066                let text_after_cursor = buffer
19067                    .text_for_range(
19068                        buffer.anchor_before(range_after_cursor.start)
19069                            ..buffer.anchor_after(range_after_cursor.end),
19070                    )
19071                    .collect::<String>();
19072                completion.new_text.ends_with(&text_after_cursor)
19073            }
19074        }
19075    }
19076
19077    let buffer = buffer.read(cx);
19078
19079    if let CompletionSource::Lsp {
19080        insert_range: Some(insert_range),
19081        ..
19082    } = &completion.source
19083    {
19084        let completion_mode_setting =
19085            language_settings(buffer.language().map(|l| l.name()), buffer.file(), cx)
19086                .completions
19087                .lsp_insert_mode;
19088
19089        if !should_replace(
19090            completion,
19091            &insert_range,
19092            intent,
19093            completion_mode_setting,
19094            buffer,
19095        ) {
19096            return insert_range.to_offset(buffer);
19097        }
19098    }
19099
19100    completion.replace_range.to_offset(buffer)
19101}
19102
19103fn insert_extra_newline_brackets(
19104    buffer: &MultiBufferSnapshot,
19105    range: Range<usize>,
19106    language: &language::LanguageScope,
19107) -> bool {
19108    let leading_whitespace_len = buffer
19109        .reversed_chars_at(range.start)
19110        .take_while(|c| c.is_whitespace() && *c != '\n')
19111        .map(|c| c.len_utf8())
19112        .sum::<usize>();
19113    let trailing_whitespace_len = buffer
19114        .chars_at(range.end)
19115        .take_while(|c| c.is_whitespace() && *c != '\n')
19116        .map(|c| c.len_utf8())
19117        .sum::<usize>();
19118    let range = range.start - leading_whitespace_len..range.end + trailing_whitespace_len;
19119
19120    language.brackets().any(|(pair, enabled)| {
19121        let pair_start = pair.start.trim_end();
19122        let pair_end = pair.end.trim_start();
19123
19124        enabled
19125            && pair.newline
19126            && buffer.contains_str_at(range.end, pair_end)
19127            && buffer.contains_str_at(range.start.saturating_sub(pair_start.len()), pair_start)
19128    })
19129}
19130
19131fn insert_extra_newline_tree_sitter(buffer: &MultiBufferSnapshot, range: Range<usize>) -> bool {
19132    let (buffer, range) = match buffer.range_to_buffer_ranges(range).as_slice() {
19133        [(buffer, range, _)] => (*buffer, range.clone()),
19134        _ => return false,
19135    };
19136    let pair = {
19137        let mut result: Option<BracketMatch> = None;
19138
19139        for pair in buffer
19140            .all_bracket_ranges(range.clone())
19141            .filter(move |pair| {
19142                pair.open_range.start <= range.start && pair.close_range.end >= range.end
19143            })
19144        {
19145            let len = pair.close_range.end - pair.open_range.start;
19146
19147            if let Some(existing) = &result {
19148                let existing_len = existing.close_range.end - existing.open_range.start;
19149                if len > existing_len {
19150                    continue;
19151                }
19152            }
19153
19154            result = Some(pair);
19155        }
19156
19157        result
19158    };
19159    let Some(pair) = pair else {
19160        return false;
19161    };
19162    pair.newline_only
19163        && buffer
19164            .chars_for_range(pair.open_range.end..range.start)
19165            .chain(buffer.chars_for_range(range.end..pair.close_range.start))
19166            .all(|c| c.is_whitespace() && c != '\n')
19167}
19168
19169fn update_uncommitted_diff_for_buffer(
19170    editor: Entity<Editor>,
19171    project: &Entity<Project>,
19172    buffers: impl IntoIterator<Item = Entity<Buffer>>,
19173    buffer: Entity<MultiBuffer>,
19174    cx: &mut App,
19175) -> Task<()> {
19176    let mut tasks = Vec::new();
19177    project.update(cx, |project, cx| {
19178        for buffer in buffers {
19179            if project::File::from_dyn(buffer.read(cx).file()).is_some() {
19180                tasks.push(project.open_uncommitted_diff(buffer.clone(), cx))
19181            }
19182        }
19183    });
19184    cx.spawn(async move |cx| {
19185        let diffs = future::join_all(tasks).await;
19186        if editor
19187            .read_with(cx, |editor, _cx| editor.temporary_diff_override)
19188            .unwrap_or(false)
19189        {
19190            return;
19191        }
19192
19193        buffer
19194            .update(cx, |buffer, cx| {
19195                for diff in diffs.into_iter().flatten() {
19196                    buffer.add_diff(diff, cx);
19197                }
19198            })
19199            .ok();
19200    })
19201}
19202
19203fn char_len_with_expanded_tabs(offset: usize, text: &str, tab_size: NonZeroU32) -> usize {
19204    let tab_size = tab_size.get() as usize;
19205    let mut width = offset;
19206
19207    for ch in text.chars() {
19208        width += if ch == '\t' {
19209            tab_size - (width % tab_size)
19210        } else {
19211            1
19212        };
19213    }
19214
19215    width - offset
19216}
19217
19218#[cfg(test)]
19219mod tests {
19220    use super::*;
19221
19222    #[test]
19223    fn test_string_size_with_expanded_tabs() {
19224        let nz = |val| NonZeroU32::new(val).unwrap();
19225        assert_eq!(char_len_with_expanded_tabs(0, "", nz(4)), 0);
19226        assert_eq!(char_len_with_expanded_tabs(0, "hello", nz(4)), 5);
19227        assert_eq!(char_len_with_expanded_tabs(0, "\thello", nz(4)), 9);
19228        assert_eq!(char_len_with_expanded_tabs(0, "abc\tab", nz(4)), 6);
19229        assert_eq!(char_len_with_expanded_tabs(0, "hello\t", nz(4)), 8);
19230        assert_eq!(char_len_with_expanded_tabs(0, "\t\t", nz(8)), 16);
19231        assert_eq!(char_len_with_expanded_tabs(0, "x\t", nz(8)), 8);
19232        assert_eq!(char_len_with_expanded_tabs(7, "x\t", nz(8)), 9);
19233    }
19234}
19235
19236/// Tokenizes a string into runs of text that should stick together, or that is whitespace.
19237struct WordBreakingTokenizer<'a> {
19238    input: &'a str,
19239}
19240
19241impl<'a> WordBreakingTokenizer<'a> {
19242    fn new(input: &'a str) -> Self {
19243        Self { input }
19244    }
19245}
19246
19247fn is_char_ideographic(ch: char) -> bool {
19248    use unicode_script::Script::*;
19249    use unicode_script::UnicodeScript;
19250    matches!(ch.script(), Han | Tangut | Yi)
19251}
19252
19253fn is_grapheme_ideographic(text: &str) -> bool {
19254    text.chars().any(is_char_ideographic)
19255}
19256
19257fn is_grapheme_whitespace(text: &str) -> bool {
19258    text.chars().any(|x| x.is_whitespace())
19259}
19260
19261fn should_stay_with_preceding_ideograph(text: &str) -> bool {
19262    text.chars().next().map_or(false, |ch| {
19263        matches!(ch, '。' | '、' | ',' | '?' | '!' | ':' | ';' | '…')
19264    })
19265}
19266
19267#[derive(PartialEq, Eq, Debug, Clone, Copy)]
19268enum WordBreakToken<'a> {
19269    Word { token: &'a str, grapheme_len: usize },
19270    InlineWhitespace { token: &'a str, grapheme_len: usize },
19271    Newline,
19272}
19273
19274impl<'a> Iterator for WordBreakingTokenizer<'a> {
19275    /// Yields a span, the count of graphemes in the token, and whether it was
19276    /// whitespace. Note that it also breaks at word boundaries.
19277    type Item = WordBreakToken<'a>;
19278
19279    fn next(&mut self) -> Option<Self::Item> {
19280        use unicode_segmentation::UnicodeSegmentation;
19281        if self.input.is_empty() {
19282            return None;
19283        }
19284
19285        let mut iter = self.input.graphemes(true).peekable();
19286        let mut offset = 0;
19287        let mut grapheme_len = 0;
19288        if let Some(first_grapheme) = iter.next() {
19289            let is_newline = first_grapheme == "\n";
19290            let is_whitespace = is_grapheme_whitespace(first_grapheme);
19291            offset += first_grapheme.len();
19292            grapheme_len += 1;
19293            if is_grapheme_ideographic(first_grapheme) && !is_whitespace {
19294                if let Some(grapheme) = iter.peek().copied() {
19295                    if should_stay_with_preceding_ideograph(grapheme) {
19296                        offset += grapheme.len();
19297                        grapheme_len += 1;
19298                    }
19299                }
19300            } else {
19301                let mut words = self.input[offset..].split_word_bound_indices().peekable();
19302                let mut next_word_bound = words.peek().copied();
19303                if next_word_bound.map_or(false, |(i, _)| i == 0) {
19304                    next_word_bound = words.next();
19305                }
19306                while let Some(grapheme) = iter.peek().copied() {
19307                    if next_word_bound.map_or(false, |(i, _)| i == offset) {
19308                        break;
19309                    };
19310                    if is_grapheme_whitespace(grapheme) != is_whitespace
19311                        || (grapheme == "\n") != is_newline
19312                    {
19313                        break;
19314                    };
19315                    offset += grapheme.len();
19316                    grapheme_len += 1;
19317                    iter.next();
19318                }
19319            }
19320            let token = &self.input[..offset];
19321            self.input = &self.input[offset..];
19322            if token == "\n" {
19323                Some(WordBreakToken::Newline)
19324            } else if is_whitespace {
19325                Some(WordBreakToken::InlineWhitespace {
19326                    token,
19327                    grapheme_len,
19328                })
19329            } else {
19330                Some(WordBreakToken::Word {
19331                    token,
19332                    grapheme_len,
19333                })
19334            }
19335        } else {
19336            None
19337        }
19338    }
19339}
19340
19341#[test]
19342fn test_word_breaking_tokenizer() {
19343    let tests: &[(&str, &[WordBreakToken<'static>])] = &[
19344        ("", &[]),
19345        ("  ", &[whitespace("  ", 2)]),
19346        ("Ʒ", &[word("Ʒ", 1)]),
19347        ("Ǽ", &[word("Ǽ", 1)]),
19348        ("", &[word("", 1)]),
19349        ("⋑⋑", &[word("⋑⋑", 2)]),
19350        (
19351            "原理,进而",
19352            &[word("", 1), word("理,", 2), word("", 1), word("", 1)],
19353        ),
19354        (
19355            "hello world",
19356            &[word("hello", 5), whitespace(" ", 1), word("world", 5)],
19357        ),
19358        (
19359            "hello, world",
19360            &[word("hello,", 6), whitespace(" ", 1), word("world", 5)],
19361        ),
19362        (
19363            "  hello world",
19364            &[
19365                whitespace("  ", 2),
19366                word("hello", 5),
19367                whitespace(" ", 1),
19368                word("world", 5),
19369            ],
19370        ),
19371        (
19372            "这是什么 \n 钢笔",
19373            &[
19374                word("", 1),
19375                word("", 1),
19376                word("", 1),
19377                word("", 1),
19378                whitespace(" ", 1),
19379                newline(),
19380                whitespace(" ", 1),
19381                word("", 1),
19382                word("", 1),
19383            ],
19384        ),
19385        (" mutton", &[whitespace("", 1), word("mutton", 6)]),
19386    ];
19387
19388    fn word(token: &'static str, grapheme_len: usize) -> WordBreakToken<'static> {
19389        WordBreakToken::Word {
19390            token,
19391            grapheme_len,
19392        }
19393    }
19394
19395    fn whitespace(token: &'static str, grapheme_len: usize) -> WordBreakToken<'static> {
19396        WordBreakToken::InlineWhitespace {
19397            token,
19398            grapheme_len,
19399        }
19400    }
19401
19402    fn newline() -> WordBreakToken<'static> {
19403        WordBreakToken::Newline
19404    }
19405
19406    for (input, result) in tests {
19407        assert_eq!(
19408            WordBreakingTokenizer::new(input)
19409                .collect::<Vec<_>>()
19410                .as_slice(),
19411            *result,
19412        );
19413    }
19414}
19415
19416fn wrap_with_prefix(
19417    line_prefix: String,
19418    unwrapped_text: String,
19419    wrap_column: usize,
19420    tab_size: NonZeroU32,
19421    preserve_existing_whitespace: bool,
19422) -> String {
19423    let line_prefix_len = char_len_with_expanded_tabs(0, &line_prefix, tab_size);
19424    let mut wrapped_text = String::new();
19425    let mut current_line = line_prefix.clone();
19426
19427    let tokenizer = WordBreakingTokenizer::new(&unwrapped_text);
19428    let mut current_line_len = line_prefix_len;
19429    let mut in_whitespace = false;
19430    for token in tokenizer {
19431        let have_preceding_whitespace = in_whitespace;
19432        match token {
19433            WordBreakToken::Word {
19434                token,
19435                grapheme_len,
19436            } => {
19437                in_whitespace = false;
19438                if current_line_len + grapheme_len > wrap_column
19439                    && current_line_len != line_prefix_len
19440                {
19441                    wrapped_text.push_str(current_line.trim_end());
19442                    wrapped_text.push('\n');
19443                    current_line.truncate(line_prefix.len());
19444                    current_line_len = line_prefix_len;
19445                }
19446                current_line.push_str(token);
19447                current_line_len += grapheme_len;
19448            }
19449            WordBreakToken::InlineWhitespace {
19450                mut token,
19451                mut grapheme_len,
19452            } => {
19453                in_whitespace = true;
19454                if have_preceding_whitespace && !preserve_existing_whitespace {
19455                    continue;
19456                }
19457                if !preserve_existing_whitespace {
19458                    token = " ";
19459                    grapheme_len = 1;
19460                }
19461                if current_line_len + grapheme_len > wrap_column {
19462                    wrapped_text.push_str(current_line.trim_end());
19463                    wrapped_text.push('\n');
19464                    current_line.truncate(line_prefix.len());
19465                    current_line_len = line_prefix_len;
19466                } else if current_line_len != line_prefix_len || preserve_existing_whitespace {
19467                    current_line.push_str(token);
19468                    current_line_len += grapheme_len;
19469                }
19470            }
19471            WordBreakToken::Newline => {
19472                in_whitespace = true;
19473                if preserve_existing_whitespace {
19474                    wrapped_text.push_str(current_line.trim_end());
19475                    wrapped_text.push('\n');
19476                    current_line.truncate(line_prefix.len());
19477                    current_line_len = line_prefix_len;
19478                } else if have_preceding_whitespace {
19479                    continue;
19480                } else if current_line_len + 1 > wrap_column && current_line_len != line_prefix_len
19481                {
19482                    wrapped_text.push_str(current_line.trim_end());
19483                    wrapped_text.push('\n');
19484                    current_line.truncate(line_prefix.len());
19485                    current_line_len = line_prefix_len;
19486                } else if current_line_len != line_prefix_len {
19487                    current_line.push(' ');
19488                    current_line_len += 1;
19489                }
19490            }
19491        }
19492    }
19493
19494    if !current_line.is_empty() {
19495        wrapped_text.push_str(&current_line);
19496    }
19497    wrapped_text
19498}
19499
19500#[test]
19501fn test_wrap_with_prefix() {
19502    assert_eq!(
19503        wrap_with_prefix(
19504            "# ".to_string(),
19505            "abcdefg".to_string(),
19506            4,
19507            NonZeroU32::new(4).unwrap(),
19508            false,
19509        ),
19510        "# abcdefg"
19511    );
19512    assert_eq!(
19513        wrap_with_prefix(
19514            "".to_string(),
19515            "\thello world".to_string(),
19516            8,
19517            NonZeroU32::new(4).unwrap(),
19518            false,
19519        ),
19520        "hello\nworld"
19521    );
19522    assert_eq!(
19523        wrap_with_prefix(
19524            "// ".to_string(),
19525            "xx \nyy zz aa bb cc".to_string(),
19526            12,
19527            NonZeroU32::new(4).unwrap(),
19528            false,
19529        ),
19530        "// xx yy zz\n// aa bb cc"
19531    );
19532    assert_eq!(
19533        wrap_with_prefix(
19534            String::new(),
19535            "这是什么 \n 钢笔".to_string(),
19536            3,
19537            NonZeroU32::new(4).unwrap(),
19538            false,
19539        ),
19540        "这是什\n么 钢\n"
19541    );
19542}
19543
19544pub trait CollaborationHub {
19545    fn collaborators<'a>(&self, cx: &'a App) -> &'a HashMap<PeerId, Collaborator>;
19546    fn user_participant_indices<'a>(&self, cx: &'a App) -> &'a HashMap<u64, ParticipantIndex>;
19547    fn user_names(&self, cx: &App) -> HashMap<u64, SharedString>;
19548}
19549
19550impl CollaborationHub for Entity<Project> {
19551    fn collaborators<'a>(&self, cx: &'a App) -> &'a HashMap<PeerId, Collaborator> {
19552        self.read(cx).collaborators()
19553    }
19554
19555    fn user_participant_indices<'a>(&self, cx: &'a App) -> &'a HashMap<u64, ParticipantIndex> {
19556        self.read(cx).user_store().read(cx).participant_indices()
19557    }
19558
19559    fn user_names(&self, cx: &App) -> HashMap<u64, SharedString> {
19560        let this = self.read(cx);
19561        let user_ids = this.collaborators().values().map(|c| c.user_id);
19562        this.user_store().read_with(cx, |user_store, cx| {
19563            user_store.participant_names(user_ids, cx)
19564        })
19565    }
19566}
19567
19568pub trait SemanticsProvider {
19569    fn hover(
19570        &self,
19571        buffer: &Entity<Buffer>,
19572        position: text::Anchor,
19573        cx: &mut App,
19574    ) -> Option<Task<Vec<project::Hover>>>;
19575
19576    fn inline_values(
19577        &self,
19578        buffer_handle: Entity<Buffer>,
19579        range: Range<text::Anchor>,
19580        cx: &mut App,
19581    ) -> Option<Task<anyhow::Result<Vec<InlayHint>>>>;
19582
19583    fn inlay_hints(
19584        &self,
19585        buffer_handle: Entity<Buffer>,
19586        range: Range<text::Anchor>,
19587        cx: &mut App,
19588    ) -> Option<Task<anyhow::Result<Vec<InlayHint>>>>;
19589
19590    fn resolve_inlay_hint(
19591        &self,
19592        hint: InlayHint,
19593        buffer_handle: Entity<Buffer>,
19594        server_id: LanguageServerId,
19595        cx: &mut App,
19596    ) -> Option<Task<anyhow::Result<InlayHint>>>;
19597
19598    fn supports_inlay_hints(&self, buffer: &Entity<Buffer>, cx: &mut App) -> bool;
19599
19600    fn document_highlights(
19601        &self,
19602        buffer: &Entity<Buffer>,
19603        position: text::Anchor,
19604        cx: &mut App,
19605    ) -> Option<Task<Result<Vec<DocumentHighlight>>>>;
19606
19607    fn definitions(
19608        &self,
19609        buffer: &Entity<Buffer>,
19610        position: text::Anchor,
19611        kind: GotoDefinitionKind,
19612        cx: &mut App,
19613    ) -> Option<Task<Result<Vec<LocationLink>>>>;
19614
19615    fn range_for_rename(
19616        &self,
19617        buffer: &Entity<Buffer>,
19618        position: text::Anchor,
19619        cx: &mut App,
19620    ) -> Option<Task<Result<Option<Range<text::Anchor>>>>>;
19621
19622    fn perform_rename(
19623        &self,
19624        buffer: &Entity<Buffer>,
19625        position: text::Anchor,
19626        new_name: String,
19627        cx: &mut App,
19628    ) -> Option<Task<Result<ProjectTransaction>>>;
19629}
19630
19631pub trait CompletionProvider {
19632    fn completions(
19633        &self,
19634        excerpt_id: ExcerptId,
19635        buffer: &Entity<Buffer>,
19636        buffer_position: text::Anchor,
19637        trigger: CompletionContext,
19638        window: &mut Window,
19639        cx: &mut Context<Editor>,
19640    ) -> Task<Result<Option<Vec<Completion>>>>;
19641
19642    fn resolve_completions(
19643        &self,
19644        buffer: Entity<Buffer>,
19645        completion_indices: Vec<usize>,
19646        completions: Rc<RefCell<Box<[Completion]>>>,
19647        cx: &mut Context<Editor>,
19648    ) -> Task<Result<bool>>;
19649
19650    fn apply_additional_edits_for_completion(
19651        &self,
19652        _buffer: Entity<Buffer>,
19653        _completions: Rc<RefCell<Box<[Completion]>>>,
19654        _completion_index: usize,
19655        _push_to_history: bool,
19656        _cx: &mut Context<Editor>,
19657    ) -> Task<Result<Option<language::Transaction>>> {
19658        Task::ready(Ok(None))
19659    }
19660
19661    fn is_completion_trigger(
19662        &self,
19663        buffer: &Entity<Buffer>,
19664        position: language::Anchor,
19665        text: &str,
19666        trigger_in_words: bool,
19667        cx: &mut Context<Editor>,
19668    ) -> bool;
19669
19670    fn sort_completions(&self) -> bool {
19671        true
19672    }
19673
19674    fn filter_completions(&self) -> bool {
19675        true
19676    }
19677}
19678
19679pub trait CodeActionProvider {
19680    fn id(&self) -> Arc<str>;
19681
19682    fn code_actions(
19683        &self,
19684        buffer: &Entity<Buffer>,
19685        range: Range<text::Anchor>,
19686        window: &mut Window,
19687        cx: &mut App,
19688    ) -> Task<Result<Vec<CodeAction>>>;
19689
19690    fn apply_code_action(
19691        &self,
19692        buffer_handle: Entity<Buffer>,
19693        action: CodeAction,
19694        excerpt_id: ExcerptId,
19695        push_to_history: bool,
19696        window: &mut Window,
19697        cx: &mut App,
19698    ) -> Task<Result<ProjectTransaction>>;
19699}
19700
19701impl CodeActionProvider for Entity<Project> {
19702    fn id(&self) -> Arc<str> {
19703        "project".into()
19704    }
19705
19706    fn code_actions(
19707        &self,
19708        buffer: &Entity<Buffer>,
19709        range: Range<text::Anchor>,
19710        _window: &mut Window,
19711        cx: &mut App,
19712    ) -> Task<Result<Vec<CodeAction>>> {
19713        self.update(cx, |project, cx| {
19714            let code_lens = project.code_lens(buffer, range.clone(), cx);
19715            let code_actions = project.code_actions(buffer, range, None, cx);
19716            cx.background_spawn(async move {
19717                let (code_lens, code_actions) = join(code_lens, code_actions).await;
19718                Ok(code_lens
19719                    .context("code lens fetch")?
19720                    .into_iter()
19721                    .chain(code_actions.context("code action fetch")?)
19722                    .collect())
19723            })
19724        })
19725    }
19726
19727    fn apply_code_action(
19728        &self,
19729        buffer_handle: Entity<Buffer>,
19730        action: CodeAction,
19731        _excerpt_id: ExcerptId,
19732        push_to_history: bool,
19733        _window: &mut Window,
19734        cx: &mut App,
19735    ) -> Task<Result<ProjectTransaction>> {
19736        self.update(cx, |project, cx| {
19737            project.apply_code_action(buffer_handle, action, push_to_history, cx)
19738        })
19739    }
19740}
19741
19742fn snippet_completions(
19743    project: &Project,
19744    buffer: &Entity<Buffer>,
19745    buffer_position: text::Anchor,
19746    cx: &mut App,
19747) -> Task<Result<Vec<Completion>>> {
19748    let languages = buffer.read(cx).languages_at(buffer_position);
19749    let snippet_store = project.snippets().read(cx);
19750
19751    let scopes: Vec<_> = languages
19752        .iter()
19753        .filter_map(|language| {
19754            let language_name = language.lsp_id();
19755            let snippets = snippet_store.snippets_for(Some(language_name), cx);
19756
19757            if snippets.is_empty() {
19758                None
19759            } else {
19760                Some((language.default_scope(), snippets))
19761            }
19762        })
19763        .collect();
19764
19765    if scopes.is_empty() {
19766        return Task::ready(Ok(vec![]));
19767    }
19768
19769    let snapshot = buffer.read(cx).text_snapshot();
19770    let chars: String = snapshot
19771        .reversed_chars_for_range(text::Anchor::MIN..buffer_position)
19772        .collect();
19773    let executor = cx.background_executor().clone();
19774
19775    cx.background_spawn(async move {
19776        let mut all_results: Vec<Completion> = Vec::new();
19777        for (scope, snippets) in scopes.into_iter() {
19778            let classifier = CharClassifier::new(Some(scope)).for_completion(true);
19779            let mut last_word = chars
19780                .chars()
19781                .take_while(|c| classifier.is_word(*c))
19782                .collect::<String>();
19783            last_word = last_word.chars().rev().collect();
19784
19785            if last_word.is_empty() {
19786                return Ok(vec![]);
19787            }
19788
19789            let as_offset = text::ToOffset::to_offset(&buffer_position, &snapshot);
19790            let to_lsp = |point: &text::Anchor| {
19791                let end = text::ToPointUtf16::to_point_utf16(point, &snapshot);
19792                point_to_lsp(end)
19793            };
19794            let lsp_end = to_lsp(&buffer_position);
19795
19796            let candidates = snippets
19797                .iter()
19798                .enumerate()
19799                .flat_map(|(ix, snippet)| {
19800                    snippet
19801                        .prefix
19802                        .iter()
19803                        .map(move |prefix| StringMatchCandidate::new(ix, &prefix))
19804                })
19805                .collect::<Vec<StringMatchCandidate>>();
19806
19807            let mut matches = fuzzy::match_strings(
19808                &candidates,
19809                &last_word,
19810                last_word.chars().any(|c| c.is_uppercase()),
19811                100,
19812                &Default::default(),
19813                executor.clone(),
19814            )
19815            .await;
19816
19817            // Remove all candidates where the query's start does not match the start of any word in the candidate
19818            if let Some(query_start) = last_word.chars().next() {
19819                matches.retain(|string_match| {
19820                    split_words(&string_match.string).any(|word| {
19821                        // Check that the first codepoint of the word as lowercase matches the first
19822                        // codepoint of the query as lowercase
19823                        word.chars()
19824                            .flat_map(|codepoint| codepoint.to_lowercase())
19825                            .zip(query_start.to_lowercase())
19826                            .all(|(word_cp, query_cp)| word_cp == query_cp)
19827                    })
19828                });
19829            }
19830
19831            let matched_strings = matches
19832                .into_iter()
19833                .map(|m| m.string)
19834                .collect::<HashSet<_>>();
19835
19836            let mut result: Vec<Completion> = snippets
19837                .iter()
19838                .filter_map(|snippet| {
19839                    let matching_prefix = snippet
19840                        .prefix
19841                        .iter()
19842                        .find(|prefix| matched_strings.contains(*prefix))?;
19843                    let start = as_offset - last_word.len();
19844                    let start = snapshot.anchor_before(start);
19845                    let range = start..buffer_position;
19846                    let lsp_start = to_lsp(&start);
19847                    let lsp_range = lsp::Range {
19848                        start: lsp_start,
19849                        end: lsp_end,
19850                    };
19851                    Some(Completion {
19852                        replace_range: range,
19853                        new_text: snippet.body.clone(),
19854                        source: CompletionSource::Lsp {
19855                            insert_range: None,
19856                            server_id: LanguageServerId(usize::MAX),
19857                            resolved: true,
19858                            lsp_completion: Box::new(lsp::CompletionItem {
19859                                label: snippet.prefix.first().unwrap().clone(),
19860                                kind: Some(CompletionItemKind::SNIPPET),
19861                                label_details: snippet.description.as_ref().map(|description| {
19862                                    lsp::CompletionItemLabelDetails {
19863                                        detail: Some(description.clone()),
19864                                        description: None,
19865                                    }
19866                                }),
19867                                insert_text_format: Some(InsertTextFormat::SNIPPET),
19868                                text_edit: Some(lsp::CompletionTextEdit::InsertAndReplace(
19869                                    lsp::InsertReplaceEdit {
19870                                        new_text: snippet.body.clone(),
19871                                        insert: lsp_range,
19872                                        replace: lsp_range,
19873                                    },
19874                                )),
19875                                filter_text: Some(snippet.body.clone()),
19876                                sort_text: Some(char::MAX.to_string()),
19877                                ..lsp::CompletionItem::default()
19878                            }),
19879                            lsp_defaults: None,
19880                        },
19881                        label: CodeLabel {
19882                            text: matching_prefix.clone(),
19883                            runs: Vec::new(),
19884                            filter_range: 0..matching_prefix.len(),
19885                        },
19886                        icon_path: None,
19887                        documentation: Some(
19888                            CompletionDocumentation::SingleLineAndMultiLinePlainText {
19889                                single_line: snippet.name.clone().into(),
19890                                plain_text: snippet
19891                                    .description
19892                                    .clone()
19893                                    .map(|description| description.into()),
19894                            },
19895                        ),
19896                        insert_text_mode: None,
19897                        confirm: None,
19898                    })
19899                })
19900                .collect();
19901
19902            all_results.append(&mut result);
19903        }
19904
19905        Ok(all_results)
19906    })
19907}
19908
19909impl CompletionProvider for Entity<Project> {
19910    fn completions(
19911        &self,
19912        _excerpt_id: ExcerptId,
19913        buffer: &Entity<Buffer>,
19914        buffer_position: text::Anchor,
19915        options: CompletionContext,
19916        _window: &mut Window,
19917        cx: &mut Context<Editor>,
19918    ) -> Task<Result<Option<Vec<Completion>>>> {
19919        self.update(cx, |project, cx| {
19920            let snippets = snippet_completions(project, buffer, buffer_position, cx);
19921            let project_completions = project.completions(buffer, buffer_position, options, cx);
19922            cx.background_spawn(async move {
19923                let snippets_completions = snippets.await?;
19924                match project_completions.await? {
19925                    Some(mut completions) => {
19926                        completions.extend(snippets_completions);
19927                        Ok(Some(completions))
19928                    }
19929                    None => {
19930                        if snippets_completions.is_empty() {
19931                            Ok(None)
19932                        } else {
19933                            Ok(Some(snippets_completions))
19934                        }
19935                    }
19936                }
19937            })
19938        })
19939    }
19940
19941    fn resolve_completions(
19942        &self,
19943        buffer: Entity<Buffer>,
19944        completion_indices: Vec<usize>,
19945        completions: Rc<RefCell<Box<[Completion]>>>,
19946        cx: &mut Context<Editor>,
19947    ) -> Task<Result<bool>> {
19948        self.update(cx, |project, cx| {
19949            project.lsp_store().update(cx, |lsp_store, cx| {
19950                lsp_store.resolve_completions(buffer, completion_indices, completions, cx)
19951            })
19952        })
19953    }
19954
19955    fn apply_additional_edits_for_completion(
19956        &self,
19957        buffer: Entity<Buffer>,
19958        completions: Rc<RefCell<Box<[Completion]>>>,
19959        completion_index: usize,
19960        push_to_history: bool,
19961        cx: &mut Context<Editor>,
19962    ) -> Task<Result<Option<language::Transaction>>> {
19963        self.update(cx, |project, cx| {
19964            project.lsp_store().update(cx, |lsp_store, cx| {
19965                lsp_store.apply_additional_edits_for_completion(
19966                    buffer,
19967                    completions,
19968                    completion_index,
19969                    push_to_history,
19970                    cx,
19971                )
19972            })
19973        })
19974    }
19975
19976    fn is_completion_trigger(
19977        &self,
19978        buffer: &Entity<Buffer>,
19979        position: language::Anchor,
19980        text: &str,
19981        trigger_in_words: bool,
19982        cx: &mut Context<Editor>,
19983    ) -> bool {
19984        let mut chars = text.chars();
19985        let char = if let Some(char) = chars.next() {
19986            char
19987        } else {
19988            return false;
19989        };
19990        if chars.next().is_some() {
19991            return false;
19992        }
19993
19994        let buffer = buffer.read(cx);
19995        let snapshot = buffer.snapshot();
19996        if !snapshot.settings_at(position, cx).show_completions_on_input {
19997            return false;
19998        }
19999        let classifier = snapshot.char_classifier_at(position).for_completion(true);
20000        if trigger_in_words && classifier.is_word(char) {
20001            return true;
20002        }
20003
20004        buffer.completion_triggers().contains(text)
20005    }
20006}
20007
20008impl SemanticsProvider for Entity<Project> {
20009    fn hover(
20010        &self,
20011        buffer: &Entity<Buffer>,
20012        position: text::Anchor,
20013        cx: &mut App,
20014    ) -> Option<Task<Vec<project::Hover>>> {
20015        Some(self.update(cx, |project, cx| project.hover(buffer, position, cx)))
20016    }
20017
20018    fn document_highlights(
20019        &self,
20020        buffer: &Entity<Buffer>,
20021        position: text::Anchor,
20022        cx: &mut App,
20023    ) -> Option<Task<Result<Vec<DocumentHighlight>>>> {
20024        Some(self.update(cx, |project, cx| {
20025            project.document_highlights(buffer, position, cx)
20026        }))
20027    }
20028
20029    fn definitions(
20030        &self,
20031        buffer: &Entity<Buffer>,
20032        position: text::Anchor,
20033        kind: GotoDefinitionKind,
20034        cx: &mut App,
20035    ) -> Option<Task<Result<Vec<LocationLink>>>> {
20036        Some(self.update(cx, |project, cx| match kind {
20037            GotoDefinitionKind::Symbol => project.definition(&buffer, position, cx),
20038            GotoDefinitionKind::Declaration => project.declaration(&buffer, position, cx),
20039            GotoDefinitionKind::Type => project.type_definition(&buffer, position, cx),
20040            GotoDefinitionKind::Implementation => project.implementation(&buffer, position, cx),
20041        }))
20042    }
20043
20044    fn supports_inlay_hints(&self, buffer: &Entity<Buffer>, cx: &mut App) -> bool {
20045        // TODO: make this work for remote projects
20046        self.update(cx, |project, cx| {
20047            if project
20048                .active_debug_session(cx)
20049                .is_some_and(|(session, _)| session.read(cx).any_stopped_thread())
20050            {
20051                return true;
20052            }
20053
20054            buffer.update(cx, |buffer, cx| {
20055                project.any_language_server_supports_inlay_hints(buffer, cx)
20056            })
20057        })
20058    }
20059
20060    fn inline_values(
20061        &self,
20062        buffer_handle: Entity<Buffer>,
20063        range: Range<text::Anchor>,
20064        cx: &mut App,
20065    ) -> Option<Task<anyhow::Result<Vec<InlayHint>>>> {
20066        self.update(cx, |project, cx| {
20067            let (session, active_stack_frame) = project.active_debug_session(cx)?;
20068
20069            Some(project.inline_values(session, active_stack_frame, buffer_handle, range, cx))
20070        })
20071    }
20072
20073    fn inlay_hints(
20074        &self,
20075        buffer_handle: Entity<Buffer>,
20076        range: Range<text::Anchor>,
20077        cx: &mut App,
20078    ) -> Option<Task<anyhow::Result<Vec<InlayHint>>>> {
20079        Some(self.update(cx, |project, cx| {
20080            project.inlay_hints(buffer_handle, range, cx)
20081        }))
20082    }
20083
20084    fn resolve_inlay_hint(
20085        &self,
20086        hint: InlayHint,
20087        buffer_handle: Entity<Buffer>,
20088        server_id: LanguageServerId,
20089        cx: &mut App,
20090    ) -> Option<Task<anyhow::Result<InlayHint>>> {
20091        Some(self.update(cx, |project, cx| {
20092            project.resolve_inlay_hint(hint, buffer_handle, server_id, cx)
20093        }))
20094    }
20095
20096    fn range_for_rename(
20097        &self,
20098        buffer: &Entity<Buffer>,
20099        position: text::Anchor,
20100        cx: &mut App,
20101    ) -> Option<Task<Result<Option<Range<text::Anchor>>>>> {
20102        Some(self.update(cx, |project, cx| {
20103            let buffer = buffer.clone();
20104            let task = project.prepare_rename(buffer.clone(), position, cx);
20105            cx.spawn(async move |_, cx| {
20106                Ok(match task.await? {
20107                    PrepareRenameResponse::Success(range) => Some(range),
20108                    PrepareRenameResponse::InvalidPosition => None,
20109                    PrepareRenameResponse::OnlyUnpreparedRenameSupported => {
20110                        // Fallback on using TreeSitter info to determine identifier range
20111                        buffer.update(cx, |buffer, _| {
20112                            let snapshot = buffer.snapshot();
20113                            let (range, kind) = snapshot.surrounding_word(position);
20114                            if kind != Some(CharKind::Word) {
20115                                return None;
20116                            }
20117                            Some(
20118                                snapshot.anchor_before(range.start)
20119                                    ..snapshot.anchor_after(range.end),
20120                            )
20121                        })?
20122                    }
20123                })
20124            })
20125        }))
20126    }
20127
20128    fn perform_rename(
20129        &self,
20130        buffer: &Entity<Buffer>,
20131        position: text::Anchor,
20132        new_name: String,
20133        cx: &mut App,
20134    ) -> Option<Task<Result<ProjectTransaction>>> {
20135        Some(self.update(cx, |project, cx| {
20136            project.perform_rename(buffer.clone(), position, new_name, cx)
20137        }))
20138    }
20139}
20140
20141fn inlay_hint_settings(
20142    location: Anchor,
20143    snapshot: &MultiBufferSnapshot,
20144    cx: &mut Context<Editor>,
20145) -> InlayHintSettings {
20146    let file = snapshot.file_at(location);
20147    let language = snapshot.language_at(location).map(|l| l.name());
20148    language_settings(language, file, cx).inlay_hints
20149}
20150
20151fn consume_contiguous_rows(
20152    contiguous_row_selections: &mut Vec<Selection<Point>>,
20153    selection: &Selection<Point>,
20154    display_map: &DisplaySnapshot,
20155    selections: &mut Peekable<std::slice::Iter<Selection<Point>>>,
20156) -> (MultiBufferRow, MultiBufferRow) {
20157    contiguous_row_selections.push(selection.clone());
20158    let start_row = MultiBufferRow(selection.start.row);
20159    let mut end_row = ending_row(selection, display_map);
20160
20161    while let Some(next_selection) = selections.peek() {
20162        if next_selection.start.row <= end_row.0 {
20163            end_row = ending_row(next_selection, display_map);
20164            contiguous_row_selections.push(selections.next().unwrap().clone());
20165        } else {
20166            break;
20167        }
20168    }
20169    (start_row, end_row)
20170}
20171
20172fn ending_row(next_selection: &Selection<Point>, display_map: &DisplaySnapshot) -> MultiBufferRow {
20173    if next_selection.end.column > 0 || next_selection.is_empty() {
20174        MultiBufferRow(display_map.next_line_boundary(next_selection.end).0.row + 1)
20175    } else {
20176        MultiBufferRow(next_selection.end.row)
20177    }
20178}
20179
20180impl EditorSnapshot {
20181    pub fn remote_selections_in_range<'a>(
20182        &'a self,
20183        range: &'a Range<Anchor>,
20184        collaboration_hub: &dyn CollaborationHub,
20185        cx: &'a App,
20186    ) -> impl 'a + Iterator<Item = RemoteSelection> {
20187        let participant_names = collaboration_hub.user_names(cx);
20188        let participant_indices = collaboration_hub.user_participant_indices(cx);
20189        let collaborators_by_peer_id = collaboration_hub.collaborators(cx);
20190        let collaborators_by_replica_id = collaborators_by_peer_id
20191            .iter()
20192            .map(|(_, collaborator)| (collaborator.replica_id, collaborator))
20193            .collect::<HashMap<_, _>>();
20194        self.buffer_snapshot
20195            .selections_in_range(range, false)
20196            .filter_map(move |(replica_id, line_mode, cursor_shape, selection)| {
20197                if replica_id == AGENT_REPLICA_ID {
20198                    Some(RemoteSelection {
20199                        replica_id,
20200                        selection,
20201                        cursor_shape,
20202                        line_mode,
20203                        collaborator_id: CollaboratorId::Agent,
20204                        user_name: Some("Agent".into()),
20205                        color: cx.theme().players().agent(),
20206                    })
20207                } else {
20208                    let collaborator = collaborators_by_replica_id.get(&replica_id)?;
20209                    let participant_index = participant_indices.get(&collaborator.user_id).copied();
20210                    let user_name = participant_names.get(&collaborator.user_id).cloned();
20211                    Some(RemoteSelection {
20212                        replica_id,
20213                        selection,
20214                        cursor_shape,
20215                        line_mode,
20216                        collaborator_id: CollaboratorId::PeerId(collaborator.peer_id),
20217                        user_name,
20218                        color: if let Some(index) = participant_index {
20219                            cx.theme().players().color_for_participant(index.0)
20220                        } else {
20221                            cx.theme().players().absent()
20222                        },
20223                    })
20224                }
20225            })
20226    }
20227
20228    pub fn hunks_for_ranges(
20229        &self,
20230        ranges: impl IntoIterator<Item = Range<Point>>,
20231    ) -> Vec<MultiBufferDiffHunk> {
20232        let mut hunks = Vec::new();
20233        let mut processed_buffer_rows: HashMap<BufferId, HashSet<Range<text::Anchor>>> =
20234            HashMap::default();
20235        for query_range in ranges {
20236            let query_rows =
20237                MultiBufferRow(query_range.start.row)..MultiBufferRow(query_range.end.row + 1);
20238            for hunk in self.buffer_snapshot.diff_hunks_in_range(
20239                Point::new(query_rows.start.0, 0)..Point::new(query_rows.end.0, 0),
20240            ) {
20241                // Include deleted hunks that are adjacent to the query range, because
20242                // otherwise they would be missed.
20243                let mut intersects_range = hunk.row_range.overlaps(&query_rows);
20244                if hunk.status().is_deleted() {
20245                    intersects_range |= hunk.row_range.start == query_rows.end;
20246                    intersects_range |= hunk.row_range.end == query_rows.start;
20247                }
20248                if intersects_range {
20249                    if !processed_buffer_rows
20250                        .entry(hunk.buffer_id)
20251                        .or_default()
20252                        .insert(hunk.buffer_range.start..hunk.buffer_range.end)
20253                    {
20254                        continue;
20255                    }
20256                    hunks.push(hunk);
20257                }
20258            }
20259        }
20260
20261        hunks
20262    }
20263
20264    fn display_diff_hunks_for_rows<'a>(
20265        &'a self,
20266        display_rows: Range<DisplayRow>,
20267        folded_buffers: &'a HashSet<BufferId>,
20268    ) -> impl 'a + Iterator<Item = DisplayDiffHunk> {
20269        let buffer_start = DisplayPoint::new(display_rows.start, 0).to_point(self);
20270        let buffer_end = DisplayPoint::new(display_rows.end, 0).to_point(self);
20271
20272        self.buffer_snapshot
20273            .diff_hunks_in_range(buffer_start..buffer_end)
20274            .filter_map(|hunk| {
20275                if folded_buffers.contains(&hunk.buffer_id) {
20276                    return None;
20277                }
20278
20279                let hunk_start_point = Point::new(hunk.row_range.start.0, 0);
20280                let hunk_end_point = Point::new(hunk.row_range.end.0, 0);
20281
20282                let hunk_display_start = self.point_to_display_point(hunk_start_point, Bias::Left);
20283                let hunk_display_end = self.point_to_display_point(hunk_end_point, Bias::Right);
20284
20285                let display_hunk = if hunk_display_start.column() != 0 {
20286                    DisplayDiffHunk::Folded {
20287                        display_row: hunk_display_start.row(),
20288                    }
20289                } else {
20290                    let mut end_row = hunk_display_end.row();
20291                    if hunk_display_end.column() > 0 {
20292                        end_row.0 += 1;
20293                    }
20294                    let is_created_file = hunk.is_created_file();
20295                    DisplayDiffHunk::Unfolded {
20296                        status: hunk.status(),
20297                        diff_base_byte_range: hunk.diff_base_byte_range,
20298                        display_row_range: hunk_display_start.row()..end_row,
20299                        multi_buffer_range: Anchor::range_in_buffer(
20300                            hunk.excerpt_id,
20301                            hunk.buffer_id,
20302                            hunk.buffer_range,
20303                        ),
20304                        is_created_file,
20305                    }
20306                };
20307
20308                Some(display_hunk)
20309            })
20310    }
20311
20312    pub fn language_at<T: ToOffset>(&self, position: T) -> Option<&Arc<Language>> {
20313        self.display_snapshot.buffer_snapshot.language_at(position)
20314    }
20315
20316    pub fn is_focused(&self) -> bool {
20317        self.is_focused
20318    }
20319
20320    pub fn placeholder_text(&self) -> Option<&Arc<str>> {
20321        self.placeholder_text.as_ref()
20322    }
20323
20324    pub fn scroll_position(&self) -> gpui::Point<f32> {
20325        self.scroll_anchor.scroll_position(&self.display_snapshot)
20326    }
20327
20328    fn gutter_dimensions(
20329        &self,
20330        font_id: FontId,
20331        font_size: Pixels,
20332        max_line_number_width: Pixels,
20333        cx: &App,
20334    ) -> Option<GutterDimensions> {
20335        if !self.show_gutter {
20336            return None;
20337        }
20338
20339        let em_width = cx.text_system().em_width(font_id, font_size).log_err()?;
20340        let em_advance = cx.text_system().em_advance(font_id, font_size).log_err()?;
20341
20342        let show_git_gutter = self.show_git_diff_gutter.unwrap_or_else(|| {
20343            matches!(
20344                ProjectSettings::get_global(cx).git.git_gutter,
20345                Some(GitGutterSetting::TrackedFiles)
20346            )
20347        });
20348        let gutter_settings = EditorSettings::get_global(cx).gutter;
20349        let show_line_numbers = self
20350            .show_line_numbers
20351            .unwrap_or(gutter_settings.line_numbers);
20352        let line_gutter_width = if show_line_numbers {
20353            // Avoid flicker-like gutter resizes when the line number gains another digit and only resize the gutter on files with N*10^5 lines.
20354            let min_width_for_number_on_gutter = em_advance * MIN_LINE_NUMBER_DIGITS as f32;
20355            max_line_number_width.max(min_width_for_number_on_gutter)
20356        } else {
20357            0.0.into()
20358        };
20359
20360        let show_runnables = self.show_runnables.unwrap_or(gutter_settings.runnables);
20361        let show_breakpoints = self.show_breakpoints.unwrap_or(gutter_settings.breakpoints);
20362
20363        let git_blame_entries_width =
20364            self.git_blame_gutter_max_author_length
20365                .map(|max_author_length| {
20366                    let renderer = cx.global::<GlobalBlameRenderer>().0.clone();
20367                    const MAX_RELATIVE_TIMESTAMP: &str = "60 minutes ago";
20368
20369                    /// The number of characters to dedicate to gaps and margins.
20370                    const SPACING_WIDTH: usize = 4;
20371
20372                    let max_char_count = max_author_length.min(renderer.max_author_length())
20373                        + ::git::SHORT_SHA_LENGTH
20374                        + MAX_RELATIVE_TIMESTAMP.len()
20375                        + SPACING_WIDTH;
20376
20377                    em_advance * max_char_count
20378                });
20379
20380        let is_singleton = self.buffer_snapshot.is_singleton();
20381
20382        let mut left_padding = git_blame_entries_width.unwrap_or(Pixels::ZERO);
20383        left_padding += if !is_singleton {
20384            em_width * 4.0
20385        } else if show_runnables || show_breakpoints {
20386            em_width * 3.0
20387        } else if show_git_gutter && show_line_numbers {
20388            em_width * 2.0
20389        } else if show_git_gutter || show_line_numbers {
20390            em_width
20391        } else {
20392            px(0.)
20393        };
20394
20395        let shows_folds = is_singleton && gutter_settings.folds;
20396
20397        let right_padding = if shows_folds && show_line_numbers {
20398            em_width * 4.0
20399        } else if shows_folds || (!is_singleton && show_line_numbers) {
20400            em_width * 3.0
20401        } else if show_line_numbers {
20402            em_width
20403        } else {
20404            px(0.)
20405        };
20406
20407        Some(GutterDimensions {
20408            left_padding,
20409            right_padding,
20410            width: line_gutter_width + left_padding + right_padding,
20411            margin: GutterDimensions::default_gutter_margin(font_id, font_size, cx),
20412            git_blame_entries_width,
20413        })
20414    }
20415
20416    pub fn render_crease_toggle(
20417        &self,
20418        buffer_row: MultiBufferRow,
20419        row_contains_cursor: bool,
20420        editor: Entity<Editor>,
20421        window: &mut Window,
20422        cx: &mut App,
20423    ) -> Option<AnyElement> {
20424        let folded = self.is_line_folded(buffer_row);
20425        let mut is_foldable = false;
20426
20427        if let Some(crease) = self
20428            .crease_snapshot
20429            .query_row(buffer_row, &self.buffer_snapshot)
20430        {
20431            is_foldable = true;
20432            match crease {
20433                Crease::Inline { render_toggle, .. } | Crease::Block { render_toggle, .. } => {
20434                    if let Some(render_toggle) = render_toggle {
20435                        let toggle_callback =
20436                            Arc::new(move |folded, window: &mut Window, cx: &mut App| {
20437                                if folded {
20438                                    editor.update(cx, |editor, cx| {
20439                                        editor.fold_at(buffer_row, window, cx)
20440                                    });
20441                                } else {
20442                                    editor.update(cx, |editor, cx| {
20443                                        editor.unfold_at(buffer_row, window, cx)
20444                                    });
20445                                }
20446                            });
20447                        return Some((render_toggle)(
20448                            buffer_row,
20449                            folded,
20450                            toggle_callback,
20451                            window,
20452                            cx,
20453                        ));
20454                    }
20455                }
20456            }
20457        }
20458
20459        is_foldable |= self.starts_indent(buffer_row);
20460
20461        if folded || (is_foldable && (row_contains_cursor || self.gutter_hovered)) {
20462            Some(
20463                Disclosure::new(("gutter_crease", buffer_row.0), !folded)
20464                    .toggle_state(folded)
20465                    .on_click(window.listener_for(&editor, move |this, _e, window, cx| {
20466                        if folded {
20467                            this.unfold_at(buffer_row, window, cx);
20468                        } else {
20469                            this.fold_at(buffer_row, window, cx);
20470                        }
20471                    }))
20472                    .into_any_element(),
20473            )
20474        } else {
20475            None
20476        }
20477    }
20478
20479    pub fn render_crease_trailer(
20480        &self,
20481        buffer_row: MultiBufferRow,
20482        window: &mut Window,
20483        cx: &mut App,
20484    ) -> Option<AnyElement> {
20485        let folded = self.is_line_folded(buffer_row);
20486        if let Crease::Inline { render_trailer, .. } = self
20487            .crease_snapshot
20488            .query_row(buffer_row, &self.buffer_snapshot)?
20489        {
20490            let render_trailer = render_trailer.as_ref()?;
20491            Some(render_trailer(buffer_row, folded, window, cx))
20492        } else {
20493            None
20494        }
20495    }
20496}
20497
20498impl Deref for EditorSnapshot {
20499    type Target = DisplaySnapshot;
20500
20501    fn deref(&self) -> &Self::Target {
20502        &self.display_snapshot
20503    }
20504}
20505
20506#[derive(Clone, Debug, PartialEq, Eq)]
20507pub enum EditorEvent {
20508    InputIgnored {
20509        text: Arc<str>,
20510    },
20511    InputHandled {
20512        utf16_range_to_replace: Option<Range<isize>>,
20513        text: Arc<str>,
20514    },
20515    ExcerptsAdded {
20516        buffer: Entity<Buffer>,
20517        predecessor: ExcerptId,
20518        excerpts: Vec<(ExcerptId, ExcerptRange<language::Anchor>)>,
20519    },
20520    ExcerptsRemoved {
20521        ids: Vec<ExcerptId>,
20522        removed_buffer_ids: Vec<BufferId>,
20523    },
20524    BufferFoldToggled {
20525        ids: Vec<ExcerptId>,
20526        folded: bool,
20527    },
20528    ExcerptsEdited {
20529        ids: Vec<ExcerptId>,
20530    },
20531    ExcerptsExpanded {
20532        ids: Vec<ExcerptId>,
20533    },
20534    BufferEdited,
20535    Edited {
20536        transaction_id: clock::Lamport,
20537    },
20538    Reparsed(BufferId),
20539    Focused,
20540    FocusedIn,
20541    Blurred,
20542    DirtyChanged,
20543    Saved,
20544    TitleChanged,
20545    DiffBaseChanged,
20546    SelectionsChanged {
20547        local: bool,
20548    },
20549    ScrollPositionChanged {
20550        local: bool,
20551        autoscroll: bool,
20552    },
20553    Closed,
20554    TransactionUndone {
20555        transaction_id: clock::Lamport,
20556    },
20557    TransactionBegun {
20558        transaction_id: clock::Lamport,
20559    },
20560    Reloaded,
20561    CursorShapeChanged,
20562    PushedToNavHistory {
20563        anchor: Anchor,
20564        is_deactivate: bool,
20565    },
20566}
20567
20568impl EventEmitter<EditorEvent> for Editor {}
20569
20570impl Focusable for Editor {
20571    fn focus_handle(&self, _cx: &App) -> FocusHandle {
20572        self.focus_handle.clone()
20573    }
20574}
20575
20576impl Render for Editor {
20577    fn render(&mut self, _: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
20578        let settings = ThemeSettings::get_global(cx);
20579
20580        let mut text_style = match self.mode {
20581            EditorMode::SingleLine { .. } | EditorMode::AutoHeight { .. } => TextStyle {
20582                color: cx.theme().colors().editor_foreground,
20583                font_family: settings.ui_font.family.clone(),
20584                font_features: settings.ui_font.features.clone(),
20585                font_fallbacks: settings.ui_font.fallbacks.clone(),
20586                font_size: rems(0.875).into(),
20587                font_weight: settings.ui_font.weight,
20588                line_height: relative(settings.buffer_line_height.value()),
20589                ..Default::default()
20590            },
20591            EditorMode::Full { .. } | EditorMode::Minimap { .. } => TextStyle {
20592                color: cx.theme().colors().editor_foreground,
20593                font_family: settings.buffer_font.family.clone(),
20594                font_features: settings.buffer_font.features.clone(),
20595                font_fallbacks: settings.buffer_font.fallbacks.clone(),
20596                font_size: settings.buffer_font_size(cx).into(),
20597                font_weight: settings.buffer_font.weight,
20598                line_height: relative(settings.buffer_line_height.value()),
20599                ..Default::default()
20600            },
20601        };
20602        if let Some(text_style_refinement) = &self.text_style_refinement {
20603            text_style.refine(text_style_refinement)
20604        }
20605
20606        let background = match self.mode {
20607            EditorMode::SingleLine { .. } => cx.theme().system().transparent,
20608            EditorMode::AutoHeight { max_lines: _ } => cx.theme().system().transparent,
20609            EditorMode::Full { .. } => cx.theme().colors().editor_background,
20610            EditorMode::Minimap { .. } => cx.theme().colors().editor_background.opacity(0.7),
20611        };
20612
20613        EditorElement::new(
20614            &cx.entity(),
20615            EditorStyle {
20616                background,
20617                local_player: cx.theme().players().local(),
20618                text: text_style,
20619                scrollbar_width: EditorElement::SCROLLBAR_WIDTH,
20620                syntax: cx.theme().syntax().clone(),
20621                status: cx.theme().status().clone(),
20622                inlay_hints_style: make_inlay_hints_style(cx),
20623                inline_completion_styles: make_suggestion_styles(cx),
20624                unnecessary_code_fade: ThemeSettings::get_global(cx).unnecessary_code_fade,
20625                show_underlines: !self.mode.is_minimap(),
20626            },
20627        )
20628    }
20629}
20630
20631impl EntityInputHandler for Editor {
20632    fn text_for_range(
20633        &mut self,
20634        range_utf16: Range<usize>,
20635        adjusted_range: &mut Option<Range<usize>>,
20636        _: &mut Window,
20637        cx: &mut Context<Self>,
20638    ) -> Option<String> {
20639        let snapshot = self.buffer.read(cx).read(cx);
20640        let start = snapshot.clip_offset_utf16(OffsetUtf16(range_utf16.start), Bias::Left);
20641        let end = snapshot.clip_offset_utf16(OffsetUtf16(range_utf16.end), Bias::Right);
20642        if (start.0..end.0) != range_utf16 {
20643            adjusted_range.replace(start.0..end.0);
20644        }
20645        Some(snapshot.text_for_range(start..end).collect())
20646    }
20647
20648    fn selected_text_range(
20649        &mut self,
20650        ignore_disabled_input: bool,
20651        _: &mut Window,
20652        cx: &mut Context<Self>,
20653    ) -> Option<UTF16Selection> {
20654        // Prevent the IME menu from appearing when holding down an alphabetic key
20655        // while input is disabled.
20656        if !ignore_disabled_input && !self.input_enabled {
20657            return None;
20658        }
20659
20660        let selection = self.selections.newest::<OffsetUtf16>(cx);
20661        let range = selection.range();
20662
20663        Some(UTF16Selection {
20664            range: range.start.0..range.end.0,
20665            reversed: selection.reversed,
20666        })
20667    }
20668
20669    fn marked_text_range(&self, _: &mut Window, cx: &mut Context<Self>) -> Option<Range<usize>> {
20670        let snapshot = self.buffer.read(cx).read(cx);
20671        let range = self.text_highlights::<InputComposition>(cx)?.1.first()?;
20672        Some(range.start.to_offset_utf16(&snapshot).0..range.end.to_offset_utf16(&snapshot).0)
20673    }
20674
20675    fn unmark_text(&mut self, _: &mut Window, cx: &mut Context<Self>) {
20676        self.clear_highlights::<InputComposition>(cx);
20677        self.ime_transaction.take();
20678    }
20679
20680    fn replace_text_in_range(
20681        &mut self,
20682        range_utf16: Option<Range<usize>>,
20683        text: &str,
20684        window: &mut Window,
20685        cx: &mut Context<Self>,
20686    ) {
20687        if !self.input_enabled {
20688            cx.emit(EditorEvent::InputIgnored { text: text.into() });
20689            return;
20690        }
20691
20692        self.transact(window, cx, |this, window, cx| {
20693            let new_selected_ranges = if let Some(range_utf16) = range_utf16 {
20694                let range_utf16 = OffsetUtf16(range_utf16.start)..OffsetUtf16(range_utf16.end);
20695                Some(this.selection_replacement_ranges(range_utf16, cx))
20696            } else {
20697                this.marked_text_ranges(cx)
20698            };
20699
20700            let range_to_replace = new_selected_ranges.as_ref().and_then(|ranges_to_replace| {
20701                let newest_selection_id = this.selections.newest_anchor().id;
20702                this.selections
20703                    .all::<OffsetUtf16>(cx)
20704                    .iter()
20705                    .zip(ranges_to_replace.iter())
20706                    .find_map(|(selection, range)| {
20707                        if selection.id == newest_selection_id {
20708                            Some(
20709                                (range.start.0 as isize - selection.head().0 as isize)
20710                                    ..(range.end.0 as isize - selection.head().0 as isize),
20711                            )
20712                        } else {
20713                            None
20714                        }
20715                    })
20716            });
20717
20718            cx.emit(EditorEvent::InputHandled {
20719                utf16_range_to_replace: range_to_replace,
20720                text: text.into(),
20721            });
20722
20723            if let Some(new_selected_ranges) = new_selected_ranges {
20724                this.change_selections(None, window, cx, |selections| {
20725                    selections.select_ranges(new_selected_ranges)
20726                });
20727                this.backspace(&Default::default(), window, cx);
20728            }
20729
20730            this.handle_input(text, window, cx);
20731        });
20732
20733        if let Some(transaction) = self.ime_transaction {
20734            self.buffer.update(cx, |buffer, cx| {
20735                buffer.group_until_transaction(transaction, cx);
20736            });
20737        }
20738
20739        self.unmark_text(window, cx);
20740    }
20741
20742    fn replace_and_mark_text_in_range(
20743        &mut self,
20744        range_utf16: Option<Range<usize>>,
20745        text: &str,
20746        new_selected_range_utf16: Option<Range<usize>>,
20747        window: &mut Window,
20748        cx: &mut Context<Self>,
20749    ) {
20750        if !self.input_enabled {
20751            return;
20752        }
20753
20754        let transaction = self.transact(window, cx, |this, window, cx| {
20755            let ranges_to_replace = if let Some(mut marked_ranges) = this.marked_text_ranges(cx) {
20756                let snapshot = this.buffer.read(cx).read(cx);
20757                if let Some(relative_range_utf16) = range_utf16.as_ref() {
20758                    for marked_range in &mut marked_ranges {
20759                        marked_range.end.0 = marked_range.start.0 + relative_range_utf16.end;
20760                        marked_range.start.0 += relative_range_utf16.start;
20761                        marked_range.start =
20762                            snapshot.clip_offset_utf16(marked_range.start, Bias::Left);
20763                        marked_range.end =
20764                            snapshot.clip_offset_utf16(marked_range.end, Bias::Right);
20765                    }
20766                }
20767                Some(marked_ranges)
20768            } else if let Some(range_utf16) = range_utf16 {
20769                let range_utf16 = OffsetUtf16(range_utf16.start)..OffsetUtf16(range_utf16.end);
20770                Some(this.selection_replacement_ranges(range_utf16, cx))
20771            } else {
20772                None
20773            };
20774
20775            let range_to_replace = ranges_to_replace.as_ref().and_then(|ranges_to_replace| {
20776                let newest_selection_id = this.selections.newest_anchor().id;
20777                this.selections
20778                    .all::<OffsetUtf16>(cx)
20779                    .iter()
20780                    .zip(ranges_to_replace.iter())
20781                    .find_map(|(selection, range)| {
20782                        if selection.id == newest_selection_id {
20783                            Some(
20784                                (range.start.0 as isize - selection.head().0 as isize)
20785                                    ..(range.end.0 as isize - selection.head().0 as isize),
20786                            )
20787                        } else {
20788                            None
20789                        }
20790                    })
20791            });
20792
20793            cx.emit(EditorEvent::InputHandled {
20794                utf16_range_to_replace: range_to_replace,
20795                text: text.into(),
20796            });
20797
20798            if let Some(ranges) = ranges_to_replace {
20799                this.change_selections(None, window, cx, |s| s.select_ranges(ranges));
20800            }
20801
20802            let marked_ranges = {
20803                let snapshot = this.buffer.read(cx).read(cx);
20804                this.selections
20805                    .disjoint_anchors()
20806                    .iter()
20807                    .map(|selection| {
20808                        selection.start.bias_left(&snapshot)..selection.end.bias_right(&snapshot)
20809                    })
20810                    .collect::<Vec<_>>()
20811            };
20812
20813            if text.is_empty() {
20814                this.unmark_text(window, cx);
20815            } else {
20816                this.highlight_text::<InputComposition>(
20817                    marked_ranges.clone(),
20818                    HighlightStyle {
20819                        underline: Some(UnderlineStyle {
20820                            thickness: px(1.),
20821                            color: None,
20822                            wavy: false,
20823                        }),
20824                        ..Default::default()
20825                    },
20826                    cx,
20827                );
20828            }
20829
20830            // Disable auto-closing when composing text (i.e. typing a `"` on a Brazilian keyboard)
20831            let use_autoclose = this.use_autoclose;
20832            let use_auto_surround = this.use_auto_surround;
20833            this.set_use_autoclose(false);
20834            this.set_use_auto_surround(false);
20835            this.handle_input(text, window, cx);
20836            this.set_use_autoclose(use_autoclose);
20837            this.set_use_auto_surround(use_auto_surround);
20838
20839            if let Some(new_selected_range) = new_selected_range_utf16 {
20840                let snapshot = this.buffer.read(cx).read(cx);
20841                let new_selected_ranges = marked_ranges
20842                    .into_iter()
20843                    .map(|marked_range| {
20844                        let insertion_start = marked_range.start.to_offset_utf16(&snapshot).0;
20845                        let new_start = OffsetUtf16(new_selected_range.start + insertion_start);
20846                        let new_end = OffsetUtf16(new_selected_range.end + insertion_start);
20847                        snapshot.clip_offset_utf16(new_start, Bias::Left)
20848                            ..snapshot.clip_offset_utf16(new_end, Bias::Right)
20849                    })
20850                    .collect::<Vec<_>>();
20851
20852                drop(snapshot);
20853                this.change_selections(None, window, cx, |selections| {
20854                    selections.select_ranges(new_selected_ranges)
20855                });
20856            }
20857        });
20858
20859        self.ime_transaction = self.ime_transaction.or(transaction);
20860        if let Some(transaction) = self.ime_transaction {
20861            self.buffer.update(cx, |buffer, cx| {
20862                buffer.group_until_transaction(transaction, cx);
20863            });
20864        }
20865
20866        if self.text_highlights::<InputComposition>(cx).is_none() {
20867            self.ime_transaction.take();
20868        }
20869    }
20870
20871    fn bounds_for_range(
20872        &mut self,
20873        range_utf16: Range<usize>,
20874        element_bounds: gpui::Bounds<Pixels>,
20875        window: &mut Window,
20876        cx: &mut Context<Self>,
20877    ) -> Option<gpui::Bounds<Pixels>> {
20878        let text_layout_details = self.text_layout_details(window);
20879        let gpui::Size {
20880            width: em_width,
20881            height: line_height,
20882        } = self.character_size(window);
20883
20884        let snapshot = self.snapshot(window, cx);
20885        let scroll_position = snapshot.scroll_position();
20886        let scroll_left = scroll_position.x * em_width;
20887
20888        let start = OffsetUtf16(range_utf16.start).to_display_point(&snapshot);
20889        let x = snapshot.x_for_display_point(start, &text_layout_details) - scroll_left
20890            + self.gutter_dimensions.width
20891            + self.gutter_dimensions.margin;
20892        let y = line_height * (start.row().as_f32() - scroll_position.y);
20893
20894        Some(Bounds {
20895            origin: element_bounds.origin + point(x, y),
20896            size: size(em_width, line_height),
20897        })
20898    }
20899
20900    fn character_index_for_point(
20901        &mut self,
20902        point: gpui::Point<Pixels>,
20903        _window: &mut Window,
20904        _cx: &mut Context<Self>,
20905    ) -> Option<usize> {
20906        let position_map = self.last_position_map.as_ref()?;
20907        if !position_map.text_hitbox.contains(&point) {
20908            return None;
20909        }
20910        let display_point = position_map.point_for_position(point).previous_valid;
20911        let anchor = position_map
20912            .snapshot
20913            .display_point_to_anchor(display_point, Bias::Left);
20914        let utf16_offset = anchor.to_offset_utf16(&position_map.snapshot.buffer_snapshot);
20915        Some(utf16_offset.0)
20916    }
20917}
20918
20919trait SelectionExt {
20920    fn display_range(&self, map: &DisplaySnapshot) -> Range<DisplayPoint>;
20921    fn spanned_rows(
20922        &self,
20923        include_end_if_at_line_start: bool,
20924        map: &DisplaySnapshot,
20925    ) -> Range<MultiBufferRow>;
20926}
20927
20928impl<T: ToPoint + ToOffset> SelectionExt for Selection<T> {
20929    fn display_range(&self, map: &DisplaySnapshot) -> Range<DisplayPoint> {
20930        let start = self
20931            .start
20932            .to_point(&map.buffer_snapshot)
20933            .to_display_point(map);
20934        let end = self
20935            .end
20936            .to_point(&map.buffer_snapshot)
20937            .to_display_point(map);
20938        if self.reversed {
20939            end..start
20940        } else {
20941            start..end
20942        }
20943    }
20944
20945    fn spanned_rows(
20946        &self,
20947        include_end_if_at_line_start: bool,
20948        map: &DisplaySnapshot,
20949    ) -> Range<MultiBufferRow> {
20950        let start = self.start.to_point(&map.buffer_snapshot);
20951        let mut end = self.end.to_point(&map.buffer_snapshot);
20952        if !include_end_if_at_line_start && start.row != end.row && end.column == 0 {
20953            end.row -= 1;
20954        }
20955
20956        let buffer_start = map.prev_line_boundary(start).0;
20957        let buffer_end = map.next_line_boundary(end).0;
20958        MultiBufferRow(buffer_start.row)..MultiBufferRow(buffer_end.row + 1)
20959    }
20960}
20961
20962impl<T: InvalidationRegion> InvalidationStack<T> {
20963    fn invalidate<S>(&mut self, selections: &[Selection<S>], buffer: &MultiBufferSnapshot)
20964    where
20965        S: Clone + ToOffset,
20966    {
20967        while let Some(region) = self.last() {
20968            let all_selections_inside_invalidation_ranges =
20969                if selections.len() == region.ranges().len() {
20970                    selections
20971                        .iter()
20972                        .zip(region.ranges().iter().map(|r| r.to_offset(buffer)))
20973                        .all(|(selection, invalidation_range)| {
20974                            let head = selection.head().to_offset(buffer);
20975                            invalidation_range.start <= head && invalidation_range.end >= head
20976                        })
20977                } else {
20978                    false
20979                };
20980
20981            if all_selections_inside_invalidation_ranges {
20982                break;
20983            } else {
20984                self.pop();
20985            }
20986        }
20987    }
20988}
20989
20990impl<T> Default for InvalidationStack<T> {
20991    fn default() -> Self {
20992        Self(Default::default())
20993    }
20994}
20995
20996impl<T> Deref for InvalidationStack<T> {
20997    type Target = Vec<T>;
20998
20999    fn deref(&self) -> &Self::Target {
21000        &self.0
21001    }
21002}
21003
21004impl<T> DerefMut for InvalidationStack<T> {
21005    fn deref_mut(&mut self) -> &mut Self::Target {
21006        &mut self.0
21007    }
21008}
21009
21010impl InvalidationRegion for SnippetState {
21011    fn ranges(&self) -> &[Range<Anchor>] {
21012        &self.ranges[self.active_index]
21013    }
21014}
21015
21016fn inline_completion_edit_text(
21017    current_snapshot: &BufferSnapshot,
21018    edits: &[(Range<Anchor>, String)],
21019    edit_preview: &EditPreview,
21020    include_deletions: bool,
21021    cx: &App,
21022) -> HighlightedText {
21023    let edits = edits
21024        .iter()
21025        .map(|(anchor, text)| {
21026            (
21027                anchor.start.text_anchor..anchor.end.text_anchor,
21028                text.clone(),
21029            )
21030        })
21031        .collect::<Vec<_>>();
21032
21033    edit_preview.highlight_edits(current_snapshot, &edits, include_deletions, cx)
21034}
21035
21036pub fn diagnostic_style(severity: lsp::DiagnosticSeverity, colors: &StatusColors) -> Hsla {
21037    match severity {
21038        lsp::DiagnosticSeverity::ERROR => colors.error,
21039        lsp::DiagnosticSeverity::WARNING => colors.warning,
21040        lsp::DiagnosticSeverity::INFORMATION => colors.info,
21041        lsp::DiagnosticSeverity::HINT => colors.info,
21042        _ => colors.ignored,
21043    }
21044}
21045
21046pub fn styled_runs_for_code_label<'a>(
21047    label: &'a CodeLabel,
21048    syntax_theme: &'a theme::SyntaxTheme,
21049) -> impl 'a + Iterator<Item = (Range<usize>, HighlightStyle)> {
21050    let fade_out = HighlightStyle {
21051        fade_out: Some(0.35),
21052        ..Default::default()
21053    };
21054
21055    let mut prev_end = label.filter_range.end;
21056    label
21057        .runs
21058        .iter()
21059        .enumerate()
21060        .flat_map(move |(ix, (range, highlight_id))| {
21061            let style = if let Some(style) = highlight_id.style(syntax_theme) {
21062                style
21063            } else {
21064                return Default::default();
21065            };
21066            let mut muted_style = style;
21067            muted_style.highlight(fade_out);
21068
21069            let mut runs = SmallVec::<[(Range<usize>, HighlightStyle); 3]>::new();
21070            if range.start >= label.filter_range.end {
21071                if range.start > prev_end {
21072                    runs.push((prev_end..range.start, fade_out));
21073                }
21074                runs.push((range.clone(), muted_style));
21075            } else if range.end <= label.filter_range.end {
21076                runs.push((range.clone(), style));
21077            } else {
21078                runs.push((range.start..label.filter_range.end, style));
21079                runs.push((label.filter_range.end..range.end, muted_style));
21080            }
21081            prev_end = cmp::max(prev_end, range.end);
21082
21083            if ix + 1 == label.runs.len() && label.text.len() > prev_end {
21084                runs.push((prev_end..label.text.len(), fade_out));
21085            }
21086
21087            runs
21088        })
21089}
21090
21091pub(crate) fn split_words(text: &str) -> impl std::iter::Iterator<Item = &str> + '_ {
21092    let mut prev_index = 0;
21093    let mut prev_codepoint: Option<char> = None;
21094    text.char_indices()
21095        .chain([(text.len(), '\0')])
21096        .filter_map(move |(index, codepoint)| {
21097            let prev_codepoint = prev_codepoint.replace(codepoint)?;
21098            let is_boundary = index == text.len()
21099                || !prev_codepoint.is_uppercase() && codepoint.is_uppercase()
21100                || !prev_codepoint.is_alphanumeric() && codepoint.is_alphanumeric();
21101            if is_boundary {
21102                let chunk = &text[prev_index..index];
21103                prev_index = index;
21104                Some(chunk)
21105            } else {
21106                None
21107            }
21108        })
21109}
21110
21111pub trait RangeToAnchorExt: Sized {
21112    fn to_anchors(self, snapshot: &MultiBufferSnapshot) -> Range<Anchor>;
21113
21114    fn to_display_points(self, snapshot: &EditorSnapshot) -> Range<DisplayPoint> {
21115        let anchor_range = self.to_anchors(&snapshot.buffer_snapshot);
21116        anchor_range.start.to_display_point(snapshot)..anchor_range.end.to_display_point(snapshot)
21117    }
21118}
21119
21120impl<T: ToOffset> RangeToAnchorExt for Range<T> {
21121    fn to_anchors(self, snapshot: &MultiBufferSnapshot) -> Range<Anchor> {
21122        let start_offset = self.start.to_offset(snapshot);
21123        let end_offset = self.end.to_offset(snapshot);
21124        if start_offset == end_offset {
21125            snapshot.anchor_before(start_offset)..snapshot.anchor_before(end_offset)
21126        } else {
21127            snapshot.anchor_after(self.start)..snapshot.anchor_before(self.end)
21128        }
21129    }
21130}
21131
21132pub trait RowExt {
21133    fn as_f32(&self) -> f32;
21134
21135    fn next_row(&self) -> Self;
21136
21137    fn previous_row(&self) -> Self;
21138
21139    fn minus(&self, other: Self) -> u32;
21140}
21141
21142impl RowExt for DisplayRow {
21143    fn as_f32(&self) -> f32 {
21144        self.0 as f32
21145    }
21146
21147    fn next_row(&self) -> Self {
21148        Self(self.0 + 1)
21149    }
21150
21151    fn previous_row(&self) -> Self {
21152        Self(self.0.saturating_sub(1))
21153    }
21154
21155    fn minus(&self, other: Self) -> u32 {
21156        self.0 - other.0
21157    }
21158}
21159
21160impl RowExt for MultiBufferRow {
21161    fn as_f32(&self) -> f32 {
21162        self.0 as f32
21163    }
21164
21165    fn next_row(&self) -> Self {
21166        Self(self.0 + 1)
21167    }
21168
21169    fn previous_row(&self) -> Self {
21170        Self(self.0.saturating_sub(1))
21171    }
21172
21173    fn minus(&self, other: Self) -> u32 {
21174        self.0 - other.0
21175    }
21176}
21177
21178trait RowRangeExt {
21179    type Row;
21180
21181    fn len(&self) -> usize;
21182
21183    fn iter_rows(&self) -> impl DoubleEndedIterator<Item = Self::Row>;
21184}
21185
21186impl RowRangeExt for Range<MultiBufferRow> {
21187    type Row = MultiBufferRow;
21188
21189    fn len(&self) -> usize {
21190        (self.end.0 - self.start.0) as usize
21191    }
21192
21193    fn iter_rows(&self) -> impl DoubleEndedIterator<Item = MultiBufferRow> {
21194        (self.start.0..self.end.0).map(MultiBufferRow)
21195    }
21196}
21197
21198impl RowRangeExt for Range<DisplayRow> {
21199    type Row = DisplayRow;
21200
21201    fn len(&self) -> usize {
21202        (self.end.0 - self.start.0) as usize
21203    }
21204
21205    fn iter_rows(&self) -> impl DoubleEndedIterator<Item = DisplayRow> {
21206        (self.start.0..self.end.0).map(DisplayRow)
21207    }
21208}
21209
21210/// If select range has more than one line, we
21211/// just point the cursor to range.start.
21212fn collapse_multiline_range(range: Range<Point>) -> Range<Point> {
21213    if range.start.row == range.end.row {
21214        range
21215    } else {
21216        range.start..range.start
21217    }
21218}
21219pub struct KillRing(ClipboardItem);
21220impl Global for KillRing {}
21221
21222const UPDATE_DEBOUNCE: Duration = Duration::from_millis(50);
21223
21224enum BreakpointPromptEditAction {
21225    Log,
21226    Condition,
21227    HitCondition,
21228}
21229
21230struct BreakpointPromptEditor {
21231    pub(crate) prompt: Entity<Editor>,
21232    editor: WeakEntity<Editor>,
21233    breakpoint_anchor: Anchor,
21234    breakpoint: Breakpoint,
21235    edit_action: BreakpointPromptEditAction,
21236    block_ids: HashSet<CustomBlockId>,
21237    editor_margins: Arc<Mutex<EditorMargins>>,
21238    _subscriptions: Vec<Subscription>,
21239}
21240
21241impl BreakpointPromptEditor {
21242    const MAX_LINES: u8 = 4;
21243
21244    fn new(
21245        editor: WeakEntity<Editor>,
21246        breakpoint_anchor: Anchor,
21247        breakpoint: Breakpoint,
21248        edit_action: BreakpointPromptEditAction,
21249        window: &mut Window,
21250        cx: &mut Context<Self>,
21251    ) -> Self {
21252        let base_text = match edit_action {
21253            BreakpointPromptEditAction::Log => breakpoint.message.as_ref(),
21254            BreakpointPromptEditAction::Condition => breakpoint.condition.as_ref(),
21255            BreakpointPromptEditAction::HitCondition => breakpoint.hit_condition.as_ref(),
21256        }
21257        .map(|msg| msg.to_string())
21258        .unwrap_or_default();
21259
21260        let buffer = cx.new(|cx| Buffer::local(base_text, cx));
21261        let buffer = cx.new(|cx| MultiBuffer::singleton(buffer, cx));
21262
21263        let prompt = cx.new(|cx| {
21264            let mut prompt = Editor::new(
21265                EditorMode::AutoHeight {
21266                    max_lines: Self::MAX_LINES as usize,
21267                },
21268                buffer,
21269                None,
21270                window,
21271                cx,
21272            );
21273            prompt.set_soft_wrap_mode(language::language_settings::SoftWrap::EditorWidth, cx);
21274            prompt.set_show_cursor_when_unfocused(false, cx);
21275            prompt.set_placeholder_text(
21276                match edit_action {
21277                    BreakpointPromptEditAction::Log => "Message to log when a breakpoint is hit. Expressions within {} are interpolated.",
21278                    BreakpointPromptEditAction::Condition => "Condition when a breakpoint is hit. Expressions within {} are interpolated.",
21279                    BreakpointPromptEditAction::HitCondition => "How many breakpoint hits to ignore",
21280                },
21281                cx,
21282            );
21283
21284            prompt
21285        });
21286
21287        Self {
21288            prompt,
21289            editor,
21290            breakpoint_anchor,
21291            breakpoint,
21292            edit_action,
21293            editor_margins: Arc::new(Mutex::new(EditorMargins::default())),
21294            block_ids: Default::default(),
21295            _subscriptions: vec![],
21296        }
21297    }
21298
21299    pub(crate) fn add_block_ids(&mut self, block_ids: Vec<CustomBlockId>) {
21300        self.block_ids.extend(block_ids)
21301    }
21302
21303    fn confirm(&mut self, _: &menu::Confirm, window: &mut Window, cx: &mut Context<Self>) {
21304        if let Some(editor) = self.editor.upgrade() {
21305            let message = self
21306                .prompt
21307                .read(cx)
21308                .buffer
21309                .read(cx)
21310                .as_singleton()
21311                .expect("A multi buffer in breakpoint prompt isn't possible")
21312                .read(cx)
21313                .as_rope()
21314                .to_string();
21315
21316            editor.update(cx, |editor, cx| {
21317                editor.edit_breakpoint_at_anchor(
21318                    self.breakpoint_anchor,
21319                    self.breakpoint.clone(),
21320                    match self.edit_action {
21321                        BreakpointPromptEditAction::Log => {
21322                            BreakpointEditAction::EditLogMessage(message.into())
21323                        }
21324                        BreakpointPromptEditAction::Condition => {
21325                            BreakpointEditAction::EditCondition(message.into())
21326                        }
21327                        BreakpointPromptEditAction::HitCondition => {
21328                            BreakpointEditAction::EditHitCondition(message.into())
21329                        }
21330                    },
21331                    cx,
21332                );
21333
21334                editor.remove_blocks(self.block_ids.clone(), None, cx);
21335                cx.focus_self(window);
21336            });
21337        }
21338    }
21339
21340    fn cancel(&mut self, _: &menu::Cancel, window: &mut Window, cx: &mut Context<Self>) {
21341        self.editor
21342            .update(cx, |editor, cx| {
21343                editor.remove_blocks(self.block_ids.clone(), None, cx);
21344                window.focus(&editor.focus_handle);
21345            })
21346            .log_err();
21347    }
21348
21349    fn render_prompt_editor(&self, cx: &mut Context<Self>) -> impl IntoElement {
21350        let settings = ThemeSettings::get_global(cx);
21351        let text_style = TextStyle {
21352            color: if self.prompt.read(cx).read_only(cx) {
21353                cx.theme().colors().text_disabled
21354            } else {
21355                cx.theme().colors().text
21356            },
21357            font_family: settings.buffer_font.family.clone(),
21358            font_fallbacks: settings.buffer_font.fallbacks.clone(),
21359            font_size: settings.buffer_font_size(cx).into(),
21360            font_weight: settings.buffer_font.weight,
21361            line_height: relative(settings.buffer_line_height.value()),
21362            ..Default::default()
21363        };
21364        EditorElement::new(
21365            &self.prompt,
21366            EditorStyle {
21367                background: cx.theme().colors().editor_background,
21368                local_player: cx.theme().players().local(),
21369                text: text_style,
21370                ..Default::default()
21371            },
21372        )
21373    }
21374}
21375
21376impl Render for BreakpointPromptEditor {
21377    fn render(&mut self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
21378        let editor_margins = *self.editor_margins.lock();
21379        let gutter_dimensions = editor_margins.gutter;
21380        h_flex()
21381            .key_context("Editor")
21382            .bg(cx.theme().colors().editor_background)
21383            .border_y_1()
21384            .border_color(cx.theme().status().info_border)
21385            .size_full()
21386            .py(window.line_height() / 2.5)
21387            .on_action(cx.listener(Self::confirm))
21388            .on_action(cx.listener(Self::cancel))
21389            .child(h_flex().w(gutter_dimensions.full_width() + (gutter_dimensions.margin / 2.0)))
21390            .child(div().flex_1().child(self.render_prompt_editor(cx)))
21391    }
21392}
21393
21394impl Focusable for BreakpointPromptEditor {
21395    fn focus_handle(&self, cx: &App) -> FocusHandle {
21396        self.prompt.focus_handle(cx)
21397    }
21398}
21399
21400fn all_edits_insertions_or_deletions(
21401    edits: &Vec<(Range<Anchor>, String)>,
21402    snapshot: &MultiBufferSnapshot,
21403) -> bool {
21404    let mut all_insertions = true;
21405    let mut all_deletions = true;
21406
21407    for (range, new_text) in edits.iter() {
21408        let range_is_empty = range.to_offset(&snapshot).is_empty();
21409        let text_is_empty = new_text.is_empty();
21410
21411        if range_is_empty != text_is_empty {
21412            if range_is_empty {
21413                all_deletions = false;
21414            } else {
21415                all_insertions = false;
21416            }
21417        } else {
21418            return false;
21419        }
21420
21421        if !all_insertions && !all_deletions {
21422            return false;
21423        }
21424    }
21425    all_insertions || all_deletions
21426}
21427
21428struct MissingEditPredictionKeybindingTooltip;
21429
21430impl Render for MissingEditPredictionKeybindingTooltip {
21431    fn render(&mut self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
21432        ui::tooltip_container(window, cx, |container, _, cx| {
21433            container
21434                .flex_shrink_0()
21435                .max_w_80()
21436                .min_h(rems_from_px(124.))
21437                .justify_between()
21438                .child(
21439                    v_flex()
21440                        .flex_1()
21441                        .text_ui_sm(cx)
21442                        .child(Label::new("Conflict with Accept Keybinding"))
21443                        .child("Your keymap currently overrides the default accept keybinding. To continue, assign one keybinding for the `editor::AcceptEditPrediction` action.")
21444                )
21445                .child(
21446                    h_flex()
21447                        .pb_1()
21448                        .gap_1()
21449                        .items_end()
21450                        .w_full()
21451                        .child(Button::new("open-keymap", "Assign Keybinding").size(ButtonSize::Compact).on_click(|_ev, window, cx| {
21452                            window.dispatch_action(zed_actions::OpenKeymap.boxed_clone(), cx)
21453                        }))
21454                        .child(Button::new("see-docs", "See Docs").size(ButtonSize::Compact).on_click(|_ev, _window, cx| {
21455                            cx.open_url("https://zed.dev/docs/completions#edit-predictions-missing-keybinding");
21456                        })),
21457                )
21458        })
21459    }
21460}
21461
21462#[derive(Debug, Clone, Copy, PartialEq)]
21463pub struct LineHighlight {
21464    pub background: Background,
21465    pub border: Option<gpui::Hsla>,
21466    pub include_gutter: bool,
21467    pub type_id: Option<TypeId>,
21468}
21469
21470fn render_diff_hunk_controls(
21471    row: u32,
21472    status: &DiffHunkStatus,
21473    hunk_range: Range<Anchor>,
21474    is_created_file: bool,
21475    line_height: Pixels,
21476    editor: &Entity<Editor>,
21477    _window: &mut Window,
21478    cx: &mut App,
21479) -> AnyElement {
21480    h_flex()
21481        .h(line_height)
21482        .mr_1()
21483        .gap_1()
21484        .px_0p5()
21485        .pb_1()
21486        .border_x_1()
21487        .border_b_1()
21488        .border_color(cx.theme().colors().border_variant)
21489        .rounded_b_lg()
21490        .bg(cx.theme().colors().editor_background)
21491        .gap_1()
21492        .occlude()
21493        .shadow_md()
21494        .child(if status.has_secondary_hunk() {
21495            Button::new(("stage", row as u64), "Stage")
21496                .alpha(if status.is_pending() { 0.66 } else { 1.0 })
21497                .tooltip({
21498                    let focus_handle = editor.focus_handle(cx);
21499                    move |window, cx| {
21500                        Tooltip::for_action_in(
21501                            "Stage Hunk",
21502                            &::git::ToggleStaged,
21503                            &focus_handle,
21504                            window,
21505                            cx,
21506                        )
21507                    }
21508                })
21509                .on_click({
21510                    let editor = editor.clone();
21511                    move |_event, _window, cx| {
21512                        editor.update(cx, |editor, cx| {
21513                            editor.stage_or_unstage_diff_hunks(
21514                                true,
21515                                vec![hunk_range.start..hunk_range.start],
21516                                cx,
21517                            );
21518                        });
21519                    }
21520                })
21521        } else {
21522            Button::new(("unstage", row as u64), "Unstage")
21523                .alpha(if status.is_pending() { 0.66 } else { 1.0 })
21524                .tooltip({
21525                    let focus_handle = editor.focus_handle(cx);
21526                    move |window, cx| {
21527                        Tooltip::for_action_in(
21528                            "Unstage Hunk",
21529                            &::git::ToggleStaged,
21530                            &focus_handle,
21531                            window,
21532                            cx,
21533                        )
21534                    }
21535                })
21536                .on_click({
21537                    let editor = editor.clone();
21538                    move |_event, _window, cx| {
21539                        editor.update(cx, |editor, cx| {
21540                            editor.stage_or_unstage_diff_hunks(
21541                                false,
21542                                vec![hunk_range.start..hunk_range.start],
21543                                cx,
21544                            );
21545                        });
21546                    }
21547                })
21548        })
21549        .child(
21550            Button::new(("restore", row as u64), "Restore")
21551                .tooltip({
21552                    let focus_handle = editor.focus_handle(cx);
21553                    move |window, cx| {
21554                        Tooltip::for_action_in(
21555                            "Restore Hunk",
21556                            &::git::Restore,
21557                            &focus_handle,
21558                            window,
21559                            cx,
21560                        )
21561                    }
21562                })
21563                .on_click({
21564                    let editor = editor.clone();
21565                    move |_event, window, cx| {
21566                        editor.update(cx, |editor, cx| {
21567                            let snapshot = editor.snapshot(window, cx);
21568                            let point = hunk_range.start.to_point(&snapshot.buffer_snapshot);
21569                            editor.restore_hunks_in_ranges(vec![point..point], window, cx);
21570                        });
21571                    }
21572                })
21573                .disabled(is_created_file),
21574        )
21575        .when(
21576            !editor.read(cx).buffer().read(cx).all_diff_hunks_expanded(),
21577            |el| {
21578                el.child(
21579                    IconButton::new(("next-hunk", row as u64), IconName::ArrowDown)
21580                        .shape(IconButtonShape::Square)
21581                        .icon_size(IconSize::Small)
21582                        // .disabled(!has_multiple_hunks)
21583                        .tooltip({
21584                            let focus_handle = editor.focus_handle(cx);
21585                            move |window, cx| {
21586                                Tooltip::for_action_in(
21587                                    "Next Hunk",
21588                                    &GoToHunk,
21589                                    &focus_handle,
21590                                    window,
21591                                    cx,
21592                                )
21593                            }
21594                        })
21595                        .on_click({
21596                            let editor = editor.clone();
21597                            move |_event, window, cx| {
21598                                editor.update(cx, |editor, cx| {
21599                                    let snapshot = editor.snapshot(window, cx);
21600                                    let position =
21601                                        hunk_range.end.to_point(&snapshot.buffer_snapshot);
21602                                    editor.go_to_hunk_before_or_after_position(
21603                                        &snapshot,
21604                                        position,
21605                                        Direction::Next,
21606                                        window,
21607                                        cx,
21608                                    );
21609                                    editor.expand_selected_diff_hunks(cx);
21610                                });
21611                            }
21612                        }),
21613                )
21614                .child(
21615                    IconButton::new(("prev-hunk", row as u64), IconName::ArrowUp)
21616                        .shape(IconButtonShape::Square)
21617                        .icon_size(IconSize::Small)
21618                        // .disabled(!has_multiple_hunks)
21619                        .tooltip({
21620                            let focus_handle = editor.focus_handle(cx);
21621                            move |window, cx| {
21622                                Tooltip::for_action_in(
21623                                    "Previous Hunk",
21624                                    &GoToPreviousHunk,
21625                                    &focus_handle,
21626                                    window,
21627                                    cx,
21628                                )
21629                            }
21630                        })
21631                        .on_click({
21632                            let editor = editor.clone();
21633                            move |_event, window, cx| {
21634                                editor.update(cx, |editor, cx| {
21635                                    let snapshot = editor.snapshot(window, cx);
21636                                    let point =
21637                                        hunk_range.start.to_point(&snapshot.buffer_snapshot);
21638                                    editor.go_to_hunk_before_or_after_position(
21639                                        &snapshot,
21640                                        point,
21641                                        Direction::Prev,
21642                                        window,
21643                                        cx,
21644                                    );
21645                                    editor.expand_selected_diff_hunks(cx);
21646                                });
21647                            }
21648                        }),
21649                )
21650            },
21651        )
21652        .into_any_element()
21653}