editor.rs

    1#![allow(rustdoc::private_intra_doc_links)]
    2//! This is the place where everything editor-related is stored (data-wise) and displayed (ui-wise).
    3//! The main point of interest in this crate is [`Editor`] type, which is used in every other Zed part as a user input element.
    4//! It comes in different flavors: single line, multiline and a fixed height one.
    5//!
    6//! Editor contains of multiple large submodules:
    7//! * [`element`] — the place where all rendering happens
    8//! * [`display_map`] - chunks up text in the editor into the logical blocks, establishes coordinates and mapping between each of them.
    9//!   Contains all metadata related to text transformations (folds, fake inlay text insertions, soft wraps, tab markup, etc.).
   10//! * [`inlay_hint_cache`] - is a storage of inlay hints out of LSP requests, responsible for querying LSP and updating `display_map`'s state accordingly.
   11//!
   12//! All other submodules and structs are mostly concerned with holding editor data about the way it displays current buffer region(s).
   13//!
   14//! If you're looking to improve Vim mode, you should check out Vim crate that wraps Editor and overrides its behavior.
   15pub mod actions;
   16mod blink_manager;
   17mod clangd_ext;
   18mod code_context_menus;
   19pub mod display_map;
   20mod editor_settings;
   21mod editor_settings_controls;
   22mod element;
   23mod git;
   24mod highlight_matching_bracket;
   25mod hover_links;
   26pub mod hover_popover;
   27mod indent_guides;
   28mod inlay_hint_cache;
   29pub mod items;
   30mod jsx_tag_auto_close;
   31mod linked_editing_ranges;
   32mod lsp_ext;
   33mod mouse_context_menu;
   34pub mod movement;
   35mod persistence;
   36mod proposed_changes_editor;
   37mod rust_analyzer_ext;
   38pub mod scroll;
   39mod selections_collection;
   40pub mod tasks;
   41
   42#[cfg(test)]
   43mod code_completion_tests;
   44#[cfg(test)]
   45mod editor_tests;
   46#[cfg(test)]
   47mod inline_completion_tests;
   48mod signature_help;
   49#[cfg(any(test, feature = "test-support"))]
   50pub mod test;
   51
   52pub(crate) use actions::*;
   53pub use actions::{AcceptEditPrediction, OpenExcerpts, OpenExcerptsSplit};
   54use aho_corasick::AhoCorasick;
   55use anyhow::{Context as _, Result, anyhow};
   56use blink_manager::BlinkManager;
   57use buffer_diff::DiffHunkStatus;
   58use client::{Collaborator, ParticipantIndex};
   59use clock::ReplicaId;
   60use collections::{BTreeMap, HashMap, HashSet, VecDeque};
   61use convert_case::{Case, Casing};
   62use display_map::*;
   63pub use display_map::{ChunkRenderer, ChunkRendererContext, DisplayPoint, FoldPlaceholder};
   64use editor_settings::GoToDefinitionFallback;
   65pub use editor_settings::{
   66    CurrentLineHighlight, EditorSettings, HideMouseMode, ScrollBeyondLastLine, SearchSettings,
   67    ShowScrollbar,
   68};
   69pub use editor_settings_controls::*;
   70use element::{AcceptEditPredictionBinding, LineWithInvisibles, PositionMap, layout_line};
   71pub use element::{
   72    CursorLayout, EditorElement, HighlightedRange, HighlightedRangeLine, PointForPosition,
   73};
   74use feature_flags::{Debugger, FeatureFlagAppExt};
   75use futures::{
   76    FutureExt,
   77    future::{self, Shared, join},
   78};
   79use fuzzy::StringMatchCandidate;
   80
   81use ::git::Restore;
   82use code_context_menus::{
   83    AvailableCodeAction, CodeActionContents, CodeActionsItem, CodeActionsMenu, CodeContextMenu,
   84    CompletionsMenu, ContextMenuOrigin,
   85};
   86use git::blame::{GitBlame, GlobalBlameRenderer};
   87use gpui::{
   88    Action, Animation, AnimationExt, AnyElement, AnyWeakEntity, App, AppContext,
   89    AsyncWindowContext, AvailableSpace, Background, Bounds, ClickEvent, ClipboardEntry,
   90    ClipboardItem, Context, DispatchPhase, Edges, Entity, EntityInputHandler, EventEmitter,
   91    FocusHandle, FocusOutEvent, Focusable, FontId, FontWeight, Global, HighlightStyle, Hsla,
   92    KeyContext, Modifiers, MouseButton, MouseDownEvent, PaintQuad, ParentElement, Pixels, Render,
   93    SharedString, Size, Stateful, Styled, Subscription, Task, TextStyle, TextStyleRefinement,
   94    UTF16Selection, UnderlineStyle, UniformListScrollHandle, WeakEntity, WeakFocusHandle, Window,
   95    div, impl_actions, point, prelude::*, pulsating_between, px, relative, size,
   96};
   97use highlight_matching_bracket::refresh_matching_bracket_highlights;
   98use hover_links::{HoverLink, HoveredLinkState, InlayHighlight, find_file};
   99pub use hover_popover::hover_markdown_style;
  100use hover_popover::{HoverState, hide_hover};
  101use indent_guides::ActiveIndentGuidesState;
  102use inlay_hint_cache::{InlayHintCache, InlaySplice, InvalidationStrategy};
  103pub use inline_completion::Direction;
  104use inline_completion::{EditPredictionProvider, InlineCompletionProviderHandle};
  105pub use items::MAX_TAB_TITLE_LEN;
  106use itertools::Itertools;
  107use language::{
  108    AutoindentMode, BracketMatch, BracketPair, Buffer, Capability, CharKind, CodeLabel,
  109    CursorShape, DiagnosticEntry, DiffOptions, EditPredictionsMode, EditPreview, HighlightedText,
  110    IndentKind, IndentSize, Language, OffsetRangeExt, Point, Selection, SelectionGoal, TextObject,
  111    TransactionId, TreeSitterOptions, WordsQuery,
  112    language_settings::{
  113        self, InlayHintSettings, LspInsertMode, RewrapBehavior, WordsCompletionMode,
  114        all_language_settings, language_settings,
  115    },
  116    point_from_lsp, text_diff_with_options,
  117};
  118use language::{BufferRow, CharClassifier, Runnable, RunnableRange, point_to_lsp};
  119use linked_editing_ranges::refresh_linked_ranges;
  120use mouse_context_menu::MouseContextMenu;
  121use persistence::DB;
  122use project::{
  123    ProjectPath,
  124    debugger::breakpoint_store::{
  125        BreakpointEditAction, BreakpointState, BreakpointStore, BreakpointStoreEvent,
  126    },
  127};
  128
  129pub use git::blame::BlameRenderer;
  130pub use proposed_changes_editor::{
  131    ProposedChangeLocation, ProposedChangesEditor, ProposedChangesEditorToolbar,
  132};
  133use smallvec::smallvec;
  134use std::{cell::OnceCell, iter::Peekable};
  135use task::{ResolvedTask, RunnableTag, TaskTemplate, TaskVariables};
  136
  137pub use lsp::CompletionContext;
  138use lsp::{
  139    CodeActionKind, CompletionItemKind, CompletionTriggerKind, DiagnosticSeverity,
  140    InsertTextFormat, InsertTextMode, LanguageServerId, LanguageServerName,
  141};
  142
  143use language::BufferSnapshot;
  144pub use lsp_ext::lsp_tasks;
  145use movement::TextLayoutDetails;
  146pub use multi_buffer::{
  147    Anchor, AnchorRangeExt, ExcerptId, ExcerptRange, MultiBuffer, MultiBufferSnapshot, PathKey,
  148    RowInfo, ToOffset, ToPoint,
  149};
  150use multi_buffer::{
  151    ExcerptInfo, ExpandExcerptDirection, MultiBufferDiffHunk, MultiBufferPoint, MultiBufferRow,
  152    MultiOrSingleBufferOffsetRange, ToOffsetUtf16,
  153};
  154use parking_lot::Mutex;
  155use project::{
  156    CodeAction, Completion, CompletionIntent, CompletionSource, DocumentHighlight, InlayHint,
  157    Location, LocationLink, PrepareRenameResponse, Project, ProjectItem, ProjectTransaction,
  158    TaskSourceKind,
  159    debugger::breakpoint_store::Breakpoint,
  160    lsp_store::{CompletionDocumentation, FormatTrigger, LspFormatTarget, OpenLspBufferHandle},
  161    project_settings::{GitGutterSetting, ProjectSettings},
  162};
  163use rand::prelude::*;
  164use rpc::{ErrorExt, proto::*};
  165use scroll::{Autoscroll, OngoingScroll, ScrollAnchor, ScrollManager, ScrollbarAutoHide};
  166use selections_collection::{
  167    MutableSelectionsCollection, SelectionsCollection, resolve_selections,
  168};
  169use serde::{Deserialize, Serialize};
  170use settings::{Settings, SettingsLocation, SettingsStore, update_settings_file};
  171use smallvec::SmallVec;
  172use snippet::Snippet;
  173use std::sync::Arc;
  174use std::{
  175    any::TypeId,
  176    borrow::Cow,
  177    cell::RefCell,
  178    cmp::{self, Ordering, Reverse},
  179    mem,
  180    num::NonZeroU32,
  181    ops::{ControlFlow, Deref, DerefMut, Not as _, Range, RangeInclusive},
  182    path::{Path, PathBuf},
  183    rc::Rc,
  184    time::{Duration, Instant},
  185};
  186pub use sum_tree::Bias;
  187use sum_tree::TreeMap;
  188use text::{BufferId, FromAnchor, OffsetUtf16, Rope};
  189use theme::{
  190    ActiveTheme, PlayerColor, StatusColors, SyntaxTheme, ThemeColors, ThemeSettings,
  191    observe_buffer_font_size_adjustment,
  192};
  193use ui::{
  194    ButtonSize, ButtonStyle, ContextMenu, Disclosure, IconButton, IconButtonShape, IconName,
  195    IconSize, Key, Tooltip, h_flex, prelude::*,
  196};
  197use util::{RangeExt, ResultExt, TryFutureExt, maybe, post_inc};
  198use workspace::{
  199    Item as WorkspaceItem, ItemId, ItemNavHistory, OpenInTerminal, OpenTerminal,
  200    RestoreOnStartupBehavior, SERIALIZATION_THROTTLE_TIME, SplitDirection, TabBarSettings, Toast,
  201    ViewId, Workspace, WorkspaceId, WorkspaceSettings,
  202    item::{ItemHandle, PreviewTabsSettings},
  203    notifications::{DetachAndPromptErr, NotificationId, NotifyTaskExt},
  204    searchable::SearchEvent,
  205};
  206
  207use crate::hover_links::{find_url, find_url_from_range};
  208use crate::signature_help::{SignatureHelpHiddenBy, SignatureHelpState};
  209
  210pub const FILE_HEADER_HEIGHT: u32 = 2;
  211pub const MULTI_BUFFER_EXCERPT_HEADER_HEIGHT: u32 = 1;
  212pub const DEFAULT_MULTIBUFFER_CONTEXT: u32 = 2;
  213const CURSOR_BLINK_INTERVAL: Duration = Duration::from_millis(500);
  214const MAX_LINE_LEN: usize = 1024;
  215const MIN_NAVIGATION_HISTORY_ROW_DELTA: i64 = 10;
  216const MAX_SELECTION_HISTORY_LEN: usize = 1024;
  217pub(crate) const CURSORS_VISIBLE_FOR: Duration = Duration::from_millis(2000);
  218#[doc(hidden)]
  219pub const CODE_ACTIONS_DEBOUNCE_TIMEOUT: Duration = Duration::from_millis(250);
  220const SELECTION_HIGHLIGHT_DEBOUNCE_TIMEOUT: Duration = Duration::from_millis(100);
  221
  222pub(crate) const CODE_ACTION_TIMEOUT: Duration = Duration::from_secs(5);
  223pub(crate) const FORMAT_TIMEOUT: Duration = Duration::from_secs(5);
  224pub(crate) const SCROLL_CENTER_TOP_BOTTOM_DEBOUNCE_TIMEOUT: Duration = Duration::from_secs(1);
  225
  226pub(crate) const EDIT_PREDICTION_KEY_CONTEXT: &str = "edit_prediction";
  227pub(crate) const EDIT_PREDICTION_CONFLICT_KEY_CONTEXT: &str = "edit_prediction_conflict";
  228pub(crate) const MIN_LINE_NUMBER_DIGITS: u32 = 4;
  229
  230pub type RenderDiffHunkControlsFn = Arc<
  231    dyn Fn(
  232        u32,
  233        &DiffHunkStatus,
  234        Range<Anchor>,
  235        bool,
  236        Pixels,
  237        &Entity<Editor>,
  238        &mut Window,
  239        &mut App,
  240    ) -> AnyElement,
  241>;
  242
  243const COLUMNAR_SELECTION_MODIFIERS: Modifiers = Modifiers {
  244    alt: true,
  245    shift: true,
  246    control: false,
  247    platform: false,
  248    function: false,
  249};
  250
  251#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
  252pub enum InlayId {
  253    InlineCompletion(usize),
  254    Hint(usize),
  255}
  256
  257impl InlayId {
  258    fn id(&self) -> usize {
  259        match self {
  260            Self::InlineCompletion(id) => *id,
  261            Self::Hint(id) => *id,
  262        }
  263    }
  264}
  265
  266pub enum DebugCurrentRowHighlight {}
  267enum DocumentHighlightRead {}
  268enum DocumentHighlightWrite {}
  269enum InputComposition {}
  270enum SelectedTextHighlight {}
  271
  272#[derive(Debug, Copy, Clone, PartialEq, Eq)]
  273pub enum Navigated {
  274    Yes,
  275    No,
  276}
  277
  278impl Navigated {
  279    pub fn from_bool(yes: bool) -> Navigated {
  280        if yes { Navigated::Yes } else { Navigated::No }
  281    }
  282}
  283
  284#[derive(Debug, Clone, PartialEq, Eq)]
  285enum DisplayDiffHunk {
  286    Folded {
  287        display_row: DisplayRow,
  288    },
  289    Unfolded {
  290        is_created_file: bool,
  291        diff_base_byte_range: Range<usize>,
  292        display_row_range: Range<DisplayRow>,
  293        multi_buffer_range: Range<Anchor>,
  294        status: DiffHunkStatus,
  295    },
  296}
  297
  298pub enum HideMouseCursorOrigin {
  299    TypingAction,
  300    MovementAction,
  301}
  302
  303pub fn init_settings(cx: &mut App) {
  304    EditorSettings::register(cx);
  305}
  306
  307pub fn init(cx: &mut App) {
  308    init_settings(cx);
  309
  310    cx.set_global(GlobalBlameRenderer(Arc::new(())));
  311
  312    workspace::register_project_item::<Editor>(cx);
  313    workspace::FollowableViewRegistry::register::<Editor>(cx);
  314    workspace::register_serializable_item::<Editor>(cx);
  315
  316    cx.observe_new(
  317        |workspace: &mut Workspace, _: Option<&mut Window>, _cx: &mut Context<Workspace>| {
  318            workspace.register_action(Editor::new_file);
  319            workspace.register_action(Editor::new_file_vertical);
  320            workspace.register_action(Editor::new_file_horizontal);
  321            workspace.register_action(Editor::cancel_language_server_work);
  322        },
  323    )
  324    .detach();
  325
  326    cx.on_action(move |_: &workspace::NewFile, cx| {
  327        let app_state = workspace::AppState::global(cx);
  328        if let Some(app_state) = app_state.upgrade() {
  329            workspace::open_new(
  330                Default::default(),
  331                app_state,
  332                cx,
  333                |workspace, window, cx| {
  334                    Editor::new_file(workspace, &Default::default(), window, cx)
  335                },
  336            )
  337            .detach();
  338        }
  339    });
  340    cx.on_action(move |_: &workspace::NewWindow, cx| {
  341        let app_state = workspace::AppState::global(cx);
  342        if let Some(app_state) = app_state.upgrade() {
  343            workspace::open_new(
  344                Default::default(),
  345                app_state,
  346                cx,
  347                |workspace, window, cx| {
  348                    cx.activate(true);
  349                    Editor::new_file(workspace, &Default::default(), window, cx)
  350                },
  351            )
  352            .detach();
  353        }
  354    });
  355}
  356
  357pub fn set_blame_renderer(renderer: impl BlameRenderer + 'static, cx: &mut App) {
  358    cx.set_global(GlobalBlameRenderer(Arc::new(renderer)));
  359}
  360
  361pub trait DiagnosticRenderer {
  362    fn render_group(
  363        &self,
  364        diagnostic_group: Vec<DiagnosticEntry<Point>>,
  365        buffer_id: BufferId,
  366        snapshot: EditorSnapshot,
  367        editor: WeakEntity<Editor>,
  368        cx: &mut App,
  369    ) -> Vec<BlockProperties<Anchor>>;
  370}
  371
  372pub(crate) struct GlobalDiagnosticRenderer(pub Arc<dyn DiagnosticRenderer>);
  373
  374impl gpui::Global for GlobalDiagnosticRenderer {}
  375pub fn set_diagnostic_renderer(renderer: impl DiagnosticRenderer + 'static, cx: &mut App) {
  376    cx.set_global(GlobalDiagnosticRenderer(Arc::new(renderer)));
  377}
  378
  379pub struct SearchWithinRange;
  380
  381trait InvalidationRegion {
  382    fn ranges(&self) -> &[Range<Anchor>];
  383}
  384
  385#[derive(Clone, Debug, PartialEq)]
  386pub enum SelectPhase {
  387    Begin {
  388        position: DisplayPoint,
  389        add: bool,
  390        click_count: usize,
  391    },
  392    BeginColumnar {
  393        position: DisplayPoint,
  394        reset: bool,
  395        goal_column: u32,
  396    },
  397    Extend {
  398        position: DisplayPoint,
  399        click_count: usize,
  400    },
  401    Update {
  402        position: DisplayPoint,
  403        goal_column: u32,
  404        scroll_delta: gpui::Point<f32>,
  405    },
  406    End,
  407}
  408
  409#[derive(Clone, Debug)]
  410pub enum SelectMode {
  411    Character,
  412    Word(Range<Anchor>),
  413    Line(Range<Anchor>),
  414    All,
  415}
  416
  417#[derive(Copy, Clone, PartialEq, Eq, Debug)]
  418pub enum EditorMode {
  419    SingleLine {
  420        auto_width: bool,
  421    },
  422    AutoHeight {
  423        max_lines: usize,
  424    },
  425    Full {
  426        /// When set to `true`, the editor will scale its UI elements with the buffer font size.
  427        scale_ui_elements_with_buffer_font_size: bool,
  428        /// When set to `true`, the editor will render a background for the active line.
  429        show_active_line_background: bool,
  430    },
  431}
  432
  433impl EditorMode {
  434    pub fn full() -> Self {
  435        Self::Full {
  436            scale_ui_elements_with_buffer_font_size: true,
  437            show_active_line_background: true,
  438        }
  439    }
  440
  441    pub fn is_full(&self) -> bool {
  442        matches!(self, Self::Full { .. })
  443    }
  444}
  445
  446#[derive(Copy, Clone, Debug)]
  447pub enum SoftWrap {
  448    /// Prefer not to wrap at all.
  449    ///
  450    /// Note: this is currently internal, as actually limited by [`crate::MAX_LINE_LEN`] until it wraps.
  451    /// The mode is used inside git diff hunks, where it's seems currently more useful to not wrap as much as possible.
  452    GitDiff,
  453    /// Prefer a single line generally, unless an overly long line is encountered.
  454    None,
  455    /// Soft wrap lines that exceed the editor width.
  456    EditorWidth,
  457    /// Soft wrap lines at the preferred line length.
  458    Column(u32),
  459    /// Soft wrap line at the preferred line length or the editor width (whichever is smaller).
  460    Bounded(u32),
  461}
  462
  463#[derive(Clone)]
  464pub struct EditorStyle {
  465    pub background: Hsla,
  466    pub local_player: PlayerColor,
  467    pub text: TextStyle,
  468    pub scrollbar_width: Pixels,
  469    pub syntax: Arc<SyntaxTheme>,
  470    pub status: StatusColors,
  471    pub inlay_hints_style: HighlightStyle,
  472    pub inline_completion_styles: InlineCompletionStyles,
  473    pub unnecessary_code_fade: f32,
  474}
  475
  476impl Default for EditorStyle {
  477    fn default() -> Self {
  478        Self {
  479            background: Hsla::default(),
  480            local_player: PlayerColor::default(),
  481            text: TextStyle::default(),
  482            scrollbar_width: Pixels::default(),
  483            syntax: Default::default(),
  484            // HACK: Status colors don't have a real default.
  485            // We should look into removing the status colors from the editor
  486            // style and retrieve them directly from the theme.
  487            status: StatusColors::dark(),
  488            inlay_hints_style: HighlightStyle::default(),
  489            inline_completion_styles: InlineCompletionStyles {
  490                insertion: HighlightStyle::default(),
  491                whitespace: HighlightStyle::default(),
  492            },
  493            unnecessary_code_fade: Default::default(),
  494        }
  495    }
  496}
  497
  498pub fn make_inlay_hints_style(cx: &mut App) -> HighlightStyle {
  499    let show_background = language_settings::language_settings(None, None, cx)
  500        .inlay_hints
  501        .show_background;
  502
  503    HighlightStyle {
  504        color: Some(cx.theme().status().hint),
  505        background_color: show_background.then(|| cx.theme().status().hint_background),
  506        ..HighlightStyle::default()
  507    }
  508}
  509
  510pub fn make_suggestion_styles(cx: &mut App) -> InlineCompletionStyles {
  511    InlineCompletionStyles {
  512        insertion: HighlightStyle {
  513            color: Some(cx.theme().status().predictive),
  514            ..HighlightStyle::default()
  515        },
  516        whitespace: HighlightStyle {
  517            background_color: Some(cx.theme().status().created_background),
  518            ..HighlightStyle::default()
  519        },
  520    }
  521}
  522
  523type CompletionId = usize;
  524
  525pub(crate) enum EditDisplayMode {
  526    TabAccept,
  527    DiffPopover,
  528    Inline,
  529}
  530
  531enum InlineCompletion {
  532    Edit {
  533        edits: Vec<(Range<Anchor>, String)>,
  534        edit_preview: Option<EditPreview>,
  535        display_mode: EditDisplayMode,
  536        snapshot: BufferSnapshot,
  537    },
  538    Move {
  539        target: Anchor,
  540        snapshot: BufferSnapshot,
  541    },
  542}
  543
  544struct InlineCompletionState {
  545    inlay_ids: Vec<InlayId>,
  546    completion: InlineCompletion,
  547    completion_id: Option<SharedString>,
  548    invalidation_range: Range<Anchor>,
  549}
  550
  551enum EditPredictionSettings {
  552    Disabled,
  553    Enabled {
  554        show_in_menu: bool,
  555        preview_requires_modifier: bool,
  556    },
  557}
  558
  559enum InlineCompletionHighlight {}
  560
  561#[derive(Debug, Clone)]
  562struct InlineDiagnostic {
  563    message: SharedString,
  564    group_id: usize,
  565    is_primary: bool,
  566    start: Point,
  567    severity: DiagnosticSeverity,
  568}
  569
  570pub enum MenuInlineCompletionsPolicy {
  571    Never,
  572    ByProvider,
  573}
  574
  575pub enum EditPredictionPreview {
  576    /// Modifier is not pressed
  577    Inactive { released_too_fast: bool },
  578    /// Modifier pressed
  579    Active {
  580        since: Instant,
  581        previous_scroll_position: Option<ScrollAnchor>,
  582    },
  583}
  584
  585impl EditPredictionPreview {
  586    pub fn released_too_fast(&self) -> bool {
  587        match self {
  588            EditPredictionPreview::Inactive { released_too_fast } => *released_too_fast,
  589            EditPredictionPreview::Active { .. } => false,
  590        }
  591    }
  592
  593    pub fn set_previous_scroll_position(&mut self, scroll_position: Option<ScrollAnchor>) {
  594        if let EditPredictionPreview::Active {
  595            previous_scroll_position,
  596            ..
  597        } = self
  598        {
  599            *previous_scroll_position = scroll_position;
  600        }
  601    }
  602}
  603
  604pub struct ContextMenuOptions {
  605    pub min_entries_visible: usize,
  606    pub max_entries_visible: usize,
  607    pub placement: Option<ContextMenuPlacement>,
  608}
  609
  610#[derive(Debug, Clone, PartialEq, Eq)]
  611pub enum ContextMenuPlacement {
  612    Above,
  613    Below,
  614}
  615
  616#[derive(Copy, Clone, Eq, PartialEq, PartialOrd, Ord, Debug, Default)]
  617struct EditorActionId(usize);
  618
  619impl EditorActionId {
  620    pub fn post_inc(&mut self) -> Self {
  621        let answer = self.0;
  622
  623        *self = Self(answer + 1);
  624
  625        Self(answer)
  626    }
  627}
  628
  629// type GetFieldEditorTheme = dyn Fn(&theme::Theme) -> theme::FieldEditor;
  630// type OverrideTextStyle = dyn Fn(&EditorStyle) -> Option<HighlightStyle>;
  631
  632type BackgroundHighlight = (fn(&ThemeColors) -> Hsla, Arc<[Range<Anchor>]>);
  633type GutterHighlight = (fn(&App) -> Hsla, Arc<[Range<Anchor>]>);
  634
  635#[derive(Default)]
  636struct ScrollbarMarkerState {
  637    scrollbar_size: Size<Pixels>,
  638    dirty: bool,
  639    markers: Arc<[PaintQuad]>,
  640    pending_refresh: Option<Task<Result<()>>>,
  641}
  642
  643impl ScrollbarMarkerState {
  644    fn should_refresh(&self, scrollbar_size: Size<Pixels>) -> bool {
  645        self.pending_refresh.is_none() && (self.scrollbar_size != scrollbar_size || self.dirty)
  646    }
  647}
  648
  649#[derive(Clone, Debug)]
  650struct RunnableTasks {
  651    templates: Vec<(TaskSourceKind, TaskTemplate)>,
  652    offset: multi_buffer::Anchor,
  653    // We need the column at which the task context evaluation should take place (when we're spawning it via gutter).
  654    column: u32,
  655    // Values of all named captures, including those starting with '_'
  656    extra_variables: HashMap<String, String>,
  657    // Full range of the tagged region. We use it to determine which `extra_variables` to grab for context resolution in e.g. a modal.
  658    context_range: Range<BufferOffset>,
  659}
  660
  661impl RunnableTasks {
  662    fn resolve<'a>(
  663        &'a self,
  664        cx: &'a task::TaskContext,
  665    ) -> impl Iterator<Item = (TaskSourceKind, ResolvedTask)> + 'a {
  666        self.templates.iter().filter_map(|(kind, template)| {
  667            template
  668                .resolve_task(&kind.to_id_base(), cx)
  669                .map(|task| (kind.clone(), task))
  670        })
  671    }
  672}
  673
  674#[derive(Clone)]
  675struct ResolvedTasks {
  676    templates: SmallVec<[(TaskSourceKind, ResolvedTask); 1]>,
  677    position: Anchor,
  678}
  679
  680#[derive(Copy, Clone, Debug, PartialEq, PartialOrd)]
  681struct BufferOffset(usize);
  682
  683// Addons allow storing per-editor state in other crates (e.g. Vim)
  684pub trait Addon: 'static {
  685    fn extend_key_context(&self, _: &mut KeyContext, _: &App) {}
  686
  687    fn render_buffer_header_controls(
  688        &self,
  689        _: &ExcerptInfo,
  690        _: &Window,
  691        _: &App,
  692    ) -> Option<AnyElement> {
  693        None
  694    }
  695
  696    fn to_any(&self) -> &dyn std::any::Any;
  697}
  698
  699/// A set of caret positions, registered when the editor was edited.
  700pub struct ChangeList {
  701    changes: Vec<Vec<Anchor>>,
  702    /// Currently "selected" change.
  703    position: Option<usize>,
  704}
  705
  706impl ChangeList {
  707    pub fn new() -> Self {
  708        Self {
  709            changes: Vec::new(),
  710            position: None,
  711        }
  712    }
  713
  714    /// Moves to the next change in the list (based on the direction given) and returns the caret positions for the next change.
  715    /// If reaches the end of the list in the direction, returns the corresponding change until called for a different direction.
  716    pub fn next_change(&mut self, count: usize, direction: Direction) -> Option<&[Anchor]> {
  717        if self.changes.is_empty() {
  718            return None;
  719        }
  720
  721        let prev = self.position.unwrap_or(self.changes.len());
  722        let next = if direction == Direction::Prev {
  723            prev.saturating_sub(count)
  724        } else {
  725            (prev + count).min(self.changes.len() - 1)
  726        };
  727        self.position = Some(next);
  728        self.changes.get(next).map(|anchors| anchors.as_slice())
  729    }
  730
  731    /// Adds a new change to the list, resetting the change list position.
  732    pub fn push_to_change_list(&mut self, pop_state: bool, new_positions: Vec<Anchor>) {
  733        self.position.take();
  734        if pop_state {
  735            self.changes.pop();
  736        }
  737        self.changes.push(new_positions.clone());
  738    }
  739
  740    pub fn last(&self) -> Option<&[Anchor]> {
  741        self.changes.last().map(|anchors| anchors.as_slice())
  742    }
  743}
  744
  745/// Zed's primary implementation of text input, allowing users to edit a [`MultiBuffer`].
  746///
  747/// See the [module level documentation](self) for more information.
  748pub struct Editor {
  749    focus_handle: FocusHandle,
  750    last_focused_descendant: Option<WeakFocusHandle>,
  751    /// The text buffer being edited
  752    buffer: Entity<MultiBuffer>,
  753    /// Map of how text in the buffer should be displayed.
  754    /// Handles soft wraps, folds, fake inlay text insertions, etc.
  755    pub display_map: Entity<DisplayMap>,
  756    pub selections: SelectionsCollection,
  757    pub scroll_manager: ScrollManager,
  758    /// When inline assist editors are linked, they all render cursors because
  759    /// typing enters text into each of them, even the ones that aren't focused.
  760    pub(crate) show_cursor_when_unfocused: bool,
  761    columnar_selection_tail: Option<Anchor>,
  762    add_selections_state: Option<AddSelectionsState>,
  763    select_next_state: Option<SelectNextState>,
  764    select_prev_state: Option<SelectNextState>,
  765    selection_history: SelectionHistory,
  766    autoclose_regions: Vec<AutocloseRegion>,
  767    snippet_stack: InvalidationStack<SnippetState>,
  768    select_syntax_node_history: SelectSyntaxNodeHistory,
  769    ime_transaction: Option<TransactionId>,
  770    active_diagnostics: ActiveDiagnostic,
  771    show_inline_diagnostics: bool,
  772    inline_diagnostics_update: Task<()>,
  773    inline_diagnostics_enabled: bool,
  774    inline_diagnostics: Vec<(Anchor, InlineDiagnostic)>,
  775    soft_wrap_mode_override: Option<language_settings::SoftWrap>,
  776    hard_wrap: Option<usize>,
  777
  778    // TODO: make this a access method
  779    pub project: Option<Entity<Project>>,
  780    semantics_provider: Option<Rc<dyn SemanticsProvider>>,
  781    completion_provider: Option<Box<dyn CompletionProvider>>,
  782    collaboration_hub: Option<Box<dyn CollaborationHub>>,
  783    blink_manager: Entity<BlinkManager>,
  784    show_cursor_names: bool,
  785    hovered_cursors: HashMap<HoveredCursor, Task<()>>,
  786    pub show_local_selections: bool,
  787    mode: EditorMode,
  788    show_breadcrumbs: bool,
  789    show_gutter: bool,
  790    show_scrollbars: bool,
  791    show_line_numbers: Option<bool>,
  792    use_relative_line_numbers: Option<bool>,
  793    show_git_diff_gutter: Option<bool>,
  794    show_code_actions: Option<bool>,
  795    show_runnables: Option<bool>,
  796    show_breakpoints: Option<bool>,
  797    show_wrap_guides: Option<bool>,
  798    show_indent_guides: Option<bool>,
  799    placeholder_text: Option<Arc<str>>,
  800    highlight_order: usize,
  801    highlighted_rows: HashMap<TypeId, Vec<RowHighlight>>,
  802    background_highlights: TreeMap<TypeId, BackgroundHighlight>,
  803    gutter_highlights: TreeMap<TypeId, GutterHighlight>,
  804    scrollbar_marker_state: ScrollbarMarkerState,
  805    active_indent_guides_state: ActiveIndentGuidesState,
  806    nav_history: Option<ItemNavHistory>,
  807    context_menu: RefCell<Option<CodeContextMenu>>,
  808    context_menu_options: Option<ContextMenuOptions>,
  809    mouse_context_menu: Option<MouseContextMenu>,
  810    completion_tasks: Vec<(CompletionId, Task<Option<()>>)>,
  811    signature_help_state: SignatureHelpState,
  812    auto_signature_help: Option<bool>,
  813    find_all_references_task_sources: Vec<Anchor>,
  814    next_completion_id: CompletionId,
  815    available_code_actions: Option<(Location, Rc<[AvailableCodeAction]>)>,
  816    code_actions_task: Option<Task<Result<()>>>,
  817    quick_selection_highlight_task: Option<(Range<Anchor>, Task<()>)>,
  818    debounced_selection_highlight_task: Option<(Range<Anchor>, Task<()>)>,
  819    document_highlights_task: Option<Task<()>>,
  820    linked_editing_range_task: Option<Task<Option<()>>>,
  821    linked_edit_ranges: linked_editing_ranges::LinkedEditingRanges,
  822    pending_rename: Option<RenameState>,
  823    searchable: bool,
  824    cursor_shape: CursorShape,
  825    current_line_highlight: Option<CurrentLineHighlight>,
  826    collapse_matches: bool,
  827    autoindent_mode: Option<AutoindentMode>,
  828    workspace: Option<(WeakEntity<Workspace>, Option<WorkspaceId>)>,
  829    input_enabled: bool,
  830    use_modal_editing: bool,
  831    read_only: bool,
  832    leader_peer_id: Option<PeerId>,
  833    remote_id: Option<ViewId>,
  834    hover_state: HoverState,
  835    pending_mouse_down: Option<Rc<RefCell<Option<MouseDownEvent>>>>,
  836    gutter_hovered: bool,
  837    hovered_link_state: Option<HoveredLinkState>,
  838    edit_prediction_provider: Option<RegisteredInlineCompletionProvider>,
  839    code_action_providers: Vec<Rc<dyn CodeActionProvider>>,
  840    active_inline_completion: Option<InlineCompletionState>,
  841    /// Used to prevent flickering as the user types while the menu is open
  842    stale_inline_completion_in_menu: Option<InlineCompletionState>,
  843    edit_prediction_settings: EditPredictionSettings,
  844    inline_completions_hidden_for_vim_mode: bool,
  845    show_inline_completions_override: Option<bool>,
  846    menu_inline_completions_policy: MenuInlineCompletionsPolicy,
  847    edit_prediction_preview: EditPredictionPreview,
  848    edit_prediction_indent_conflict: bool,
  849    edit_prediction_requires_modifier_in_indent_conflict: bool,
  850    inlay_hint_cache: InlayHintCache,
  851    next_inlay_id: usize,
  852    _subscriptions: Vec<Subscription>,
  853    pixel_position_of_newest_cursor: Option<gpui::Point<Pixels>>,
  854    gutter_dimensions: GutterDimensions,
  855    style: Option<EditorStyle>,
  856    text_style_refinement: Option<TextStyleRefinement>,
  857    next_editor_action_id: EditorActionId,
  858    editor_actions:
  859        Rc<RefCell<BTreeMap<EditorActionId, Box<dyn Fn(&mut Window, &mut Context<Self>)>>>>,
  860    use_autoclose: bool,
  861    use_auto_surround: bool,
  862    auto_replace_emoji_shortcode: bool,
  863    jsx_tag_auto_close_enabled_in_any_buffer: bool,
  864    show_git_blame_gutter: bool,
  865    show_git_blame_inline: bool,
  866    show_git_blame_inline_delay_task: Option<Task<()>>,
  867    pub git_blame_inline_tooltip: Option<AnyWeakEntity>,
  868    git_blame_inline_enabled: bool,
  869    render_diff_hunk_controls: RenderDiffHunkControlsFn,
  870    serialize_dirty_buffers: bool,
  871    show_selection_menu: Option<bool>,
  872    blame: Option<Entity<GitBlame>>,
  873    blame_subscription: Option<Subscription>,
  874    custom_context_menu: Option<
  875        Box<
  876            dyn 'static
  877                + Fn(
  878                    &mut Self,
  879                    DisplayPoint,
  880                    &mut Window,
  881                    &mut Context<Self>,
  882                ) -> Option<Entity<ui::ContextMenu>>,
  883        >,
  884    >,
  885    last_bounds: Option<Bounds<Pixels>>,
  886    last_position_map: Option<Rc<PositionMap>>,
  887    expect_bounds_change: Option<Bounds<Pixels>>,
  888    tasks: BTreeMap<(BufferId, BufferRow), RunnableTasks>,
  889    tasks_update_task: Option<Task<()>>,
  890    breakpoint_store: Option<Entity<BreakpointStore>>,
  891    /// Allow's a user to create a breakpoint by selecting this indicator
  892    /// It should be None while a user is not hovering over the gutter
  893    /// Otherwise it represents the point that the breakpoint will be shown
  894    gutter_breakpoint_indicator: (Option<(DisplayPoint, bool)>, Option<Task<()>>),
  895    in_project_search: bool,
  896    previous_search_ranges: Option<Arc<[Range<Anchor>]>>,
  897    breadcrumb_header: Option<String>,
  898    focused_block: Option<FocusedBlock>,
  899    next_scroll_position: NextScrollCursorCenterTopBottom,
  900    addons: HashMap<TypeId, Box<dyn Addon>>,
  901    registered_buffers: HashMap<BufferId, OpenLspBufferHandle>,
  902    load_diff_task: Option<Shared<Task<()>>>,
  903    selection_mark_mode: bool,
  904    toggle_fold_multiple_buffers: Task<()>,
  905    _scroll_cursor_center_top_bottom_task: Task<()>,
  906    serialize_selections: Task<()>,
  907    serialize_folds: Task<()>,
  908    mouse_cursor_hidden: bool,
  909    hide_mouse_mode: HideMouseMode,
  910    pub change_list: ChangeList,
  911}
  912
  913#[derive(Copy, Clone, Debug, PartialEq, Eq, Default)]
  914enum NextScrollCursorCenterTopBottom {
  915    #[default]
  916    Center,
  917    Top,
  918    Bottom,
  919}
  920
  921impl NextScrollCursorCenterTopBottom {
  922    fn next(&self) -> Self {
  923        match self {
  924            Self::Center => Self::Top,
  925            Self::Top => Self::Bottom,
  926            Self::Bottom => Self::Center,
  927        }
  928    }
  929}
  930
  931#[derive(Clone)]
  932pub struct EditorSnapshot {
  933    pub mode: EditorMode,
  934    show_gutter: bool,
  935    show_line_numbers: Option<bool>,
  936    show_git_diff_gutter: Option<bool>,
  937    show_code_actions: Option<bool>,
  938    show_runnables: Option<bool>,
  939    show_breakpoints: Option<bool>,
  940    git_blame_gutter_max_author_length: Option<usize>,
  941    pub display_snapshot: DisplaySnapshot,
  942    pub placeholder_text: Option<Arc<str>>,
  943    is_focused: bool,
  944    scroll_anchor: ScrollAnchor,
  945    ongoing_scroll: OngoingScroll,
  946    current_line_highlight: CurrentLineHighlight,
  947    gutter_hovered: bool,
  948}
  949
  950#[derive(Default, Debug, Clone, Copy)]
  951pub struct GutterDimensions {
  952    pub left_padding: Pixels,
  953    pub right_padding: Pixels,
  954    pub width: Pixels,
  955    pub margin: Pixels,
  956    pub git_blame_entries_width: Option<Pixels>,
  957}
  958
  959impl GutterDimensions {
  960    /// The full width of the space taken up by the gutter.
  961    pub fn full_width(&self) -> Pixels {
  962        self.margin + self.width
  963    }
  964
  965    /// The width of the space reserved for the fold indicators,
  966    /// use alongside 'justify_end' and `gutter_width` to
  967    /// right align content with the line numbers
  968    pub fn fold_area_width(&self) -> Pixels {
  969        self.margin + self.right_padding
  970    }
  971}
  972
  973#[derive(Debug)]
  974pub struct RemoteSelection {
  975    pub replica_id: ReplicaId,
  976    pub selection: Selection<Anchor>,
  977    pub cursor_shape: CursorShape,
  978    pub peer_id: PeerId,
  979    pub line_mode: bool,
  980    pub participant_index: Option<ParticipantIndex>,
  981    pub user_name: Option<SharedString>,
  982}
  983
  984#[derive(Clone, Debug)]
  985struct SelectionHistoryEntry {
  986    selections: Arc<[Selection<Anchor>]>,
  987    select_next_state: Option<SelectNextState>,
  988    select_prev_state: Option<SelectNextState>,
  989    add_selections_state: Option<AddSelectionsState>,
  990}
  991
  992enum SelectionHistoryMode {
  993    Normal,
  994    Undoing,
  995    Redoing,
  996}
  997
  998#[derive(Clone, PartialEq, Eq, Hash)]
  999struct HoveredCursor {
 1000    replica_id: u16,
 1001    selection_id: usize,
 1002}
 1003
 1004impl Default for SelectionHistoryMode {
 1005    fn default() -> Self {
 1006        Self::Normal
 1007    }
 1008}
 1009
 1010#[derive(Default)]
 1011struct SelectionHistory {
 1012    #[allow(clippy::type_complexity)]
 1013    selections_by_transaction:
 1014        HashMap<TransactionId, (Arc<[Selection<Anchor>]>, Option<Arc<[Selection<Anchor>]>>)>,
 1015    mode: SelectionHistoryMode,
 1016    undo_stack: VecDeque<SelectionHistoryEntry>,
 1017    redo_stack: VecDeque<SelectionHistoryEntry>,
 1018}
 1019
 1020impl SelectionHistory {
 1021    fn insert_transaction(
 1022        &mut self,
 1023        transaction_id: TransactionId,
 1024        selections: Arc<[Selection<Anchor>]>,
 1025    ) {
 1026        self.selections_by_transaction
 1027            .insert(transaction_id, (selections, None));
 1028    }
 1029
 1030    #[allow(clippy::type_complexity)]
 1031    fn transaction(
 1032        &self,
 1033        transaction_id: TransactionId,
 1034    ) -> Option<&(Arc<[Selection<Anchor>]>, Option<Arc<[Selection<Anchor>]>>)> {
 1035        self.selections_by_transaction.get(&transaction_id)
 1036    }
 1037
 1038    #[allow(clippy::type_complexity)]
 1039    fn transaction_mut(
 1040        &mut self,
 1041        transaction_id: TransactionId,
 1042    ) -> Option<&mut (Arc<[Selection<Anchor>]>, Option<Arc<[Selection<Anchor>]>>)> {
 1043        self.selections_by_transaction.get_mut(&transaction_id)
 1044    }
 1045
 1046    fn push(&mut self, entry: SelectionHistoryEntry) {
 1047        if !entry.selections.is_empty() {
 1048            match self.mode {
 1049                SelectionHistoryMode::Normal => {
 1050                    self.push_undo(entry);
 1051                    self.redo_stack.clear();
 1052                }
 1053                SelectionHistoryMode::Undoing => self.push_redo(entry),
 1054                SelectionHistoryMode::Redoing => self.push_undo(entry),
 1055            }
 1056        }
 1057    }
 1058
 1059    fn push_undo(&mut self, entry: SelectionHistoryEntry) {
 1060        if self
 1061            .undo_stack
 1062            .back()
 1063            .map_or(true, |e| e.selections != entry.selections)
 1064        {
 1065            self.undo_stack.push_back(entry);
 1066            if self.undo_stack.len() > MAX_SELECTION_HISTORY_LEN {
 1067                self.undo_stack.pop_front();
 1068            }
 1069        }
 1070    }
 1071
 1072    fn push_redo(&mut self, entry: SelectionHistoryEntry) {
 1073        if self
 1074            .redo_stack
 1075            .back()
 1076            .map_or(true, |e| e.selections != entry.selections)
 1077        {
 1078            self.redo_stack.push_back(entry);
 1079            if self.redo_stack.len() > MAX_SELECTION_HISTORY_LEN {
 1080                self.redo_stack.pop_front();
 1081            }
 1082        }
 1083    }
 1084}
 1085
 1086struct RowHighlight {
 1087    index: usize,
 1088    range: Range<Anchor>,
 1089    color: Hsla,
 1090    should_autoscroll: bool,
 1091}
 1092
 1093#[derive(Clone, Debug)]
 1094struct AddSelectionsState {
 1095    above: bool,
 1096    stack: Vec<usize>,
 1097}
 1098
 1099#[derive(Clone)]
 1100struct SelectNextState {
 1101    query: AhoCorasick,
 1102    wordwise: bool,
 1103    done: bool,
 1104}
 1105
 1106impl std::fmt::Debug for SelectNextState {
 1107    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
 1108        f.debug_struct(std::any::type_name::<Self>())
 1109            .field("wordwise", &self.wordwise)
 1110            .field("done", &self.done)
 1111            .finish()
 1112    }
 1113}
 1114
 1115#[derive(Debug)]
 1116struct AutocloseRegion {
 1117    selection_id: usize,
 1118    range: Range<Anchor>,
 1119    pair: BracketPair,
 1120}
 1121
 1122#[derive(Debug)]
 1123struct SnippetState {
 1124    ranges: Vec<Vec<Range<Anchor>>>,
 1125    active_index: usize,
 1126    choices: Vec<Option<Vec<String>>>,
 1127}
 1128
 1129#[doc(hidden)]
 1130pub struct RenameState {
 1131    pub range: Range<Anchor>,
 1132    pub old_name: Arc<str>,
 1133    pub editor: Entity<Editor>,
 1134    block_id: CustomBlockId,
 1135}
 1136
 1137struct InvalidationStack<T>(Vec<T>);
 1138
 1139struct RegisteredInlineCompletionProvider {
 1140    provider: Arc<dyn InlineCompletionProviderHandle>,
 1141    _subscription: Subscription,
 1142}
 1143
 1144#[derive(Debug, PartialEq, Eq)]
 1145pub struct ActiveDiagnosticGroup {
 1146    pub active_range: Range<Anchor>,
 1147    pub active_message: String,
 1148    pub group_id: usize,
 1149    pub blocks: HashSet<CustomBlockId>,
 1150}
 1151
 1152#[derive(Debug, PartialEq, Eq)]
 1153#[allow(clippy::large_enum_variant)]
 1154pub(crate) enum ActiveDiagnostic {
 1155    None,
 1156    All,
 1157    Group(ActiveDiagnosticGroup),
 1158}
 1159
 1160#[derive(Serialize, Deserialize, Clone, Debug)]
 1161pub struct ClipboardSelection {
 1162    /// The number of bytes in this selection.
 1163    pub len: usize,
 1164    /// Whether this was a full-line selection.
 1165    pub is_entire_line: bool,
 1166    /// The indentation of the first line when this content was originally copied.
 1167    pub first_line_indent: u32,
 1168}
 1169
 1170// selections, scroll behavior, was newest selection reversed
 1171type SelectSyntaxNodeHistoryState = (
 1172    Box<[Selection<usize>]>,
 1173    SelectSyntaxNodeScrollBehavior,
 1174    bool,
 1175);
 1176
 1177#[derive(Default)]
 1178struct SelectSyntaxNodeHistory {
 1179    stack: Vec<SelectSyntaxNodeHistoryState>,
 1180    // disable temporarily to allow changing selections without losing the stack
 1181    pub disable_clearing: bool,
 1182}
 1183
 1184impl SelectSyntaxNodeHistory {
 1185    pub fn try_clear(&mut self) {
 1186        if !self.disable_clearing {
 1187            self.stack.clear();
 1188        }
 1189    }
 1190
 1191    pub fn push(&mut self, selection: SelectSyntaxNodeHistoryState) {
 1192        self.stack.push(selection);
 1193    }
 1194
 1195    pub fn pop(&mut self) -> Option<SelectSyntaxNodeHistoryState> {
 1196        self.stack.pop()
 1197    }
 1198}
 1199
 1200enum SelectSyntaxNodeScrollBehavior {
 1201    CursorTop,
 1202    FitSelection,
 1203    CursorBottom,
 1204}
 1205
 1206#[derive(Debug)]
 1207pub(crate) struct NavigationData {
 1208    cursor_anchor: Anchor,
 1209    cursor_position: Point,
 1210    scroll_anchor: ScrollAnchor,
 1211    scroll_top_row: u32,
 1212}
 1213
 1214#[derive(Debug, Clone, Copy, PartialEq, Eq)]
 1215pub enum GotoDefinitionKind {
 1216    Symbol,
 1217    Declaration,
 1218    Type,
 1219    Implementation,
 1220}
 1221
 1222#[derive(Debug, Clone)]
 1223enum InlayHintRefreshReason {
 1224    ModifiersChanged(bool),
 1225    Toggle(bool),
 1226    SettingsChange(InlayHintSettings),
 1227    NewLinesShown,
 1228    BufferEdited(HashSet<Arc<Language>>),
 1229    RefreshRequested,
 1230    ExcerptsRemoved(Vec<ExcerptId>),
 1231}
 1232
 1233impl InlayHintRefreshReason {
 1234    fn description(&self) -> &'static str {
 1235        match self {
 1236            Self::ModifiersChanged(_) => "modifiers changed",
 1237            Self::Toggle(_) => "toggle",
 1238            Self::SettingsChange(_) => "settings change",
 1239            Self::NewLinesShown => "new lines shown",
 1240            Self::BufferEdited(_) => "buffer edited",
 1241            Self::RefreshRequested => "refresh requested",
 1242            Self::ExcerptsRemoved(_) => "excerpts removed",
 1243        }
 1244    }
 1245}
 1246
 1247pub enum FormatTarget {
 1248    Buffers,
 1249    Ranges(Vec<Range<MultiBufferPoint>>),
 1250}
 1251
 1252pub(crate) struct FocusedBlock {
 1253    id: BlockId,
 1254    focus_handle: WeakFocusHandle,
 1255}
 1256
 1257#[derive(Clone)]
 1258enum JumpData {
 1259    MultiBufferRow {
 1260        row: MultiBufferRow,
 1261        line_offset_from_top: u32,
 1262    },
 1263    MultiBufferPoint {
 1264        excerpt_id: ExcerptId,
 1265        position: Point,
 1266        anchor: text::Anchor,
 1267        line_offset_from_top: u32,
 1268    },
 1269}
 1270
 1271pub enum MultibufferSelectionMode {
 1272    First,
 1273    All,
 1274}
 1275
 1276#[derive(Clone, Copy, Debug, Default)]
 1277pub struct RewrapOptions {
 1278    pub override_language_settings: bool,
 1279    pub preserve_existing_whitespace: bool,
 1280}
 1281
 1282impl Editor {
 1283    pub fn single_line(window: &mut Window, cx: &mut Context<Self>) -> Self {
 1284        let buffer = cx.new(|cx| Buffer::local("", cx));
 1285        let buffer = cx.new(|cx| MultiBuffer::singleton(buffer, cx));
 1286        Self::new(
 1287            EditorMode::SingleLine { auto_width: false },
 1288            buffer,
 1289            None,
 1290            window,
 1291            cx,
 1292        )
 1293    }
 1294
 1295    pub fn multi_line(window: &mut Window, cx: &mut Context<Self>) -> Self {
 1296        let buffer = cx.new(|cx| Buffer::local("", cx));
 1297        let buffer = cx.new(|cx| MultiBuffer::singleton(buffer, cx));
 1298        Self::new(EditorMode::full(), buffer, None, window, cx)
 1299    }
 1300
 1301    pub fn auto_width(window: &mut Window, cx: &mut Context<Self>) -> Self {
 1302        let buffer = cx.new(|cx| Buffer::local("", cx));
 1303        let buffer = cx.new(|cx| MultiBuffer::singleton(buffer, cx));
 1304        Self::new(
 1305            EditorMode::SingleLine { auto_width: true },
 1306            buffer,
 1307            None,
 1308            window,
 1309            cx,
 1310        )
 1311    }
 1312
 1313    pub fn auto_height(max_lines: usize, window: &mut Window, cx: &mut Context<Self>) -> Self {
 1314        let buffer = cx.new(|cx| Buffer::local("", cx));
 1315        let buffer = cx.new(|cx| MultiBuffer::singleton(buffer, cx));
 1316        Self::new(
 1317            EditorMode::AutoHeight { max_lines },
 1318            buffer,
 1319            None,
 1320            window,
 1321            cx,
 1322        )
 1323    }
 1324
 1325    pub fn for_buffer(
 1326        buffer: Entity<Buffer>,
 1327        project: Option<Entity<Project>>,
 1328        window: &mut Window,
 1329        cx: &mut Context<Self>,
 1330    ) -> Self {
 1331        let buffer = cx.new(|cx| MultiBuffer::singleton(buffer, cx));
 1332        Self::new(EditorMode::full(), buffer, project, window, cx)
 1333    }
 1334
 1335    pub fn for_multibuffer(
 1336        buffer: Entity<MultiBuffer>,
 1337        project: Option<Entity<Project>>,
 1338        window: &mut Window,
 1339        cx: &mut Context<Self>,
 1340    ) -> Self {
 1341        Self::new(EditorMode::full(), buffer, project, window, cx)
 1342    }
 1343
 1344    pub fn clone(&self, window: &mut Window, cx: &mut Context<Self>) -> Self {
 1345        let mut clone = Self::new(
 1346            self.mode,
 1347            self.buffer.clone(),
 1348            self.project.clone(),
 1349            window,
 1350            cx,
 1351        );
 1352        self.display_map.update(cx, |display_map, cx| {
 1353            let snapshot = display_map.snapshot(cx);
 1354            clone.display_map.update(cx, |display_map, cx| {
 1355                display_map.set_state(&snapshot, cx);
 1356            });
 1357        });
 1358        clone.folds_did_change(cx);
 1359        clone.selections.clone_state(&self.selections);
 1360        clone.scroll_manager.clone_state(&self.scroll_manager);
 1361        clone.searchable = self.searchable;
 1362        clone.read_only = self.read_only;
 1363        clone
 1364    }
 1365
 1366    pub fn new(
 1367        mode: EditorMode,
 1368        buffer: Entity<MultiBuffer>,
 1369        project: Option<Entity<Project>>,
 1370        window: &mut Window,
 1371        cx: &mut Context<Self>,
 1372    ) -> Self {
 1373        let style = window.text_style();
 1374        let font_size = style.font_size.to_pixels(window.rem_size());
 1375        let editor = cx.entity().downgrade();
 1376        let fold_placeholder = FoldPlaceholder {
 1377            constrain_width: true,
 1378            render: Arc::new(move |fold_id, fold_range, cx| {
 1379                let editor = editor.clone();
 1380                div()
 1381                    .id(fold_id)
 1382                    .bg(cx.theme().colors().ghost_element_background)
 1383                    .hover(|style| style.bg(cx.theme().colors().ghost_element_hover))
 1384                    .active(|style| style.bg(cx.theme().colors().ghost_element_active))
 1385                    .rounded_xs()
 1386                    .size_full()
 1387                    .cursor_pointer()
 1388                    .child("")
 1389                    .on_mouse_down(MouseButton::Left, |_, _, cx| cx.stop_propagation())
 1390                    .on_click(move |_, _window, cx| {
 1391                        editor
 1392                            .update(cx, |editor, cx| {
 1393                                editor.unfold_ranges(
 1394                                    &[fold_range.start..fold_range.end],
 1395                                    true,
 1396                                    false,
 1397                                    cx,
 1398                                );
 1399                                cx.stop_propagation();
 1400                            })
 1401                            .ok();
 1402                    })
 1403                    .into_any()
 1404            }),
 1405            merge_adjacent: true,
 1406            ..Default::default()
 1407        };
 1408        let display_map = cx.new(|cx| {
 1409            DisplayMap::new(
 1410                buffer.clone(),
 1411                style.font(),
 1412                font_size,
 1413                None,
 1414                FILE_HEADER_HEIGHT,
 1415                MULTI_BUFFER_EXCERPT_HEADER_HEIGHT,
 1416                fold_placeholder,
 1417                cx,
 1418            )
 1419        });
 1420
 1421        let selections = SelectionsCollection::new(display_map.clone(), buffer.clone());
 1422
 1423        let blink_manager = cx.new(|cx| BlinkManager::new(CURSOR_BLINK_INTERVAL, cx));
 1424
 1425        let soft_wrap_mode_override = matches!(mode, EditorMode::SingleLine { .. })
 1426            .then(|| language_settings::SoftWrap::None);
 1427
 1428        let mut project_subscriptions = Vec::new();
 1429        if mode.is_full() {
 1430            if let Some(project) = project.as_ref() {
 1431                project_subscriptions.push(cx.subscribe_in(
 1432                    project,
 1433                    window,
 1434                    |editor, _, event, window, cx| match event {
 1435                        project::Event::RefreshCodeLens => {
 1436                            // we always query lens with actions, without storing them, always refreshing them
 1437                        }
 1438                        project::Event::RefreshInlayHints => {
 1439                            editor
 1440                                .refresh_inlay_hints(InlayHintRefreshReason::RefreshRequested, cx);
 1441                        }
 1442                        project::Event::SnippetEdit(id, snippet_edits) => {
 1443                            if let Some(buffer) = editor.buffer.read(cx).buffer(*id) {
 1444                                let focus_handle = editor.focus_handle(cx);
 1445                                if focus_handle.is_focused(window) {
 1446                                    let snapshot = buffer.read(cx).snapshot();
 1447                                    for (range, snippet) in snippet_edits {
 1448                                        let editor_range =
 1449                                            language::range_from_lsp(*range).to_offset(&snapshot);
 1450                                        editor
 1451                                            .insert_snippet(
 1452                                                &[editor_range],
 1453                                                snippet.clone(),
 1454                                                window,
 1455                                                cx,
 1456                                            )
 1457                                            .ok();
 1458                                    }
 1459                                }
 1460                            }
 1461                        }
 1462                        _ => {}
 1463                    },
 1464                ));
 1465                if let Some(task_inventory) = project
 1466                    .read(cx)
 1467                    .task_store()
 1468                    .read(cx)
 1469                    .task_inventory()
 1470                    .cloned()
 1471                {
 1472                    project_subscriptions.push(cx.observe_in(
 1473                        &task_inventory,
 1474                        window,
 1475                        |editor, _, window, cx| {
 1476                            editor.tasks_update_task = Some(editor.refresh_runnables(window, cx));
 1477                        },
 1478                    ));
 1479                };
 1480
 1481                project_subscriptions.push(cx.subscribe_in(
 1482                    &project.read(cx).breakpoint_store(),
 1483                    window,
 1484                    |editor, _, event, window, cx| match event {
 1485                        BreakpointStoreEvent::ActiveDebugLineChanged => {
 1486                            if editor.go_to_active_debug_line(window, cx) {
 1487                                cx.stop_propagation();
 1488                            }
 1489                        }
 1490                        _ => {}
 1491                    },
 1492                ));
 1493            }
 1494        }
 1495
 1496        let buffer_snapshot = buffer.read(cx).snapshot(cx);
 1497
 1498        let inlay_hint_settings =
 1499            inlay_hint_settings(selections.newest_anchor().head(), &buffer_snapshot, cx);
 1500        let focus_handle = cx.focus_handle();
 1501        cx.on_focus(&focus_handle, window, Self::handle_focus)
 1502            .detach();
 1503        cx.on_focus_in(&focus_handle, window, Self::handle_focus_in)
 1504            .detach();
 1505        cx.on_focus_out(&focus_handle, window, Self::handle_focus_out)
 1506            .detach();
 1507        cx.on_blur(&focus_handle, window, Self::handle_blur)
 1508            .detach();
 1509
 1510        let show_indent_guides = if matches!(mode, EditorMode::SingleLine { .. }) {
 1511            Some(false)
 1512        } else {
 1513            None
 1514        };
 1515
 1516        let breakpoint_store = match (mode, project.as_ref()) {
 1517            (EditorMode::Full { .. }, Some(project)) => Some(project.read(cx).breakpoint_store()),
 1518            _ => None,
 1519        };
 1520
 1521        let mut code_action_providers = Vec::new();
 1522        let mut load_uncommitted_diff = None;
 1523        if let Some(project) = project.clone() {
 1524            load_uncommitted_diff = Some(
 1525                get_uncommitted_diff_for_buffer(
 1526                    &project,
 1527                    buffer.read(cx).all_buffers(),
 1528                    buffer.clone(),
 1529                    cx,
 1530                )
 1531                .shared(),
 1532            );
 1533            code_action_providers.push(Rc::new(project) as Rc<_>);
 1534        }
 1535
 1536        let mut this = Self {
 1537            focus_handle,
 1538            show_cursor_when_unfocused: false,
 1539            last_focused_descendant: None,
 1540            buffer: buffer.clone(),
 1541            display_map: display_map.clone(),
 1542            selections,
 1543            scroll_manager: ScrollManager::new(cx),
 1544            columnar_selection_tail: None,
 1545            add_selections_state: None,
 1546            select_next_state: None,
 1547            select_prev_state: None,
 1548            selection_history: Default::default(),
 1549            autoclose_regions: Default::default(),
 1550            snippet_stack: Default::default(),
 1551            select_syntax_node_history: SelectSyntaxNodeHistory::default(),
 1552            ime_transaction: Default::default(),
 1553            active_diagnostics: ActiveDiagnostic::None,
 1554            show_inline_diagnostics: ProjectSettings::get_global(cx).diagnostics.inline.enabled,
 1555            inline_diagnostics_update: Task::ready(()),
 1556            inline_diagnostics: Vec::new(),
 1557            soft_wrap_mode_override,
 1558            hard_wrap: None,
 1559            completion_provider: project.clone().map(|project| Box::new(project) as _),
 1560            semantics_provider: project.clone().map(|project| Rc::new(project) as _),
 1561            collaboration_hub: project.clone().map(|project| Box::new(project) as _),
 1562            project,
 1563            blink_manager: blink_manager.clone(),
 1564            show_local_selections: true,
 1565            show_scrollbars: true,
 1566            mode,
 1567            show_breadcrumbs: EditorSettings::get_global(cx).toolbar.breadcrumbs,
 1568            show_gutter: mode.is_full(),
 1569            show_line_numbers: None,
 1570            use_relative_line_numbers: None,
 1571            show_git_diff_gutter: None,
 1572            show_code_actions: None,
 1573            show_runnables: None,
 1574            show_breakpoints: None,
 1575            show_wrap_guides: None,
 1576            show_indent_guides,
 1577            placeholder_text: None,
 1578            highlight_order: 0,
 1579            highlighted_rows: HashMap::default(),
 1580            background_highlights: Default::default(),
 1581            gutter_highlights: TreeMap::default(),
 1582            scrollbar_marker_state: ScrollbarMarkerState::default(),
 1583            active_indent_guides_state: ActiveIndentGuidesState::default(),
 1584            nav_history: None,
 1585            context_menu: RefCell::new(None),
 1586            context_menu_options: None,
 1587            mouse_context_menu: None,
 1588            completion_tasks: Default::default(),
 1589            signature_help_state: SignatureHelpState::default(),
 1590            auto_signature_help: None,
 1591            find_all_references_task_sources: Vec::new(),
 1592            next_completion_id: 0,
 1593            next_inlay_id: 0,
 1594            code_action_providers,
 1595            available_code_actions: Default::default(),
 1596            code_actions_task: Default::default(),
 1597            quick_selection_highlight_task: Default::default(),
 1598            debounced_selection_highlight_task: Default::default(),
 1599            document_highlights_task: Default::default(),
 1600            linked_editing_range_task: Default::default(),
 1601            pending_rename: Default::default(),
 1602            searchable: true,
 1603            cursor_shape: EditorSettings::get_global(cx)
 1604                .cursor_shape
 1605                .unwrap_or_default(),
 1606            current_line_highlight: None,
 1607            autoindent_mode: Some(AutoindentMode::EachLine),
 1608            collapse_matches: false,
 1609            workspace: None,
 1610            input_enabled: true,
 1611            use_modal_editing: mode.is_full(),
 1612            read_only: false,
 1613            use_autoclose: true,
 1614            use_auto_surround: true,
 1615            auto_replace_emoji_shortcode: false,
 1616            jsx_tag_auto_close_enabled_in_any_buffer: false,
 1617            leader_peer_id: None,
 1618            remote_id: None,
 1619            hover_state: Default::default(),
 1620            pending_mouse_down: None,
 1621            hovered_link_state: Default::default(),
 1622            edit_prediction_provider: None,
 1623            active_inline_completion: None,
 1624            stale_inline_completion_in_menu: None,
 1625            edit_prediction_preview: EditPredictionPreview::Inactive {
 1626                released_too_fast: false,
 1627            },
 1628            inline_diagnostics_enabled: mode.is_full(),
 1629            inlay_hint_cache: InlayHintCache::new(inlay_hint_settings),
 1630
 1631            gutter_hovered: false,
 1632            pixel_position_of_newest_cursor: None,
 1633            last_bounds: None,
 1634            last_position_map: None,
 1635            expect_bounds_change: None,
 1636            gutter_dimensions: GutterDimensions::default(),
 1637            style: None,
 1638            show_cursor_names: false,
 1639            hovered_cursors: Default::default(),
 1640            next_editor_action_id: EditorActionId::default(),
 1641            editor_actions: Rc::default(),
 1642            inline_completions_hidden_for_vim_mode: false,
 1643            show_inline_completions_override: None,
 1644            menu_inline_completions_policy: MenuInlineCompletionsPolicy::ByProvider,
 1645            edit_prediction_settings: EditPredictionSettings::Disabled,
 1646            edit_prediction_indent_conflict: false,
 1647            edit_prediction_requires_modifier_in_indent_conflict: true,
 1648            custom_context_menu: None,
 1649            show_git_blame_gutter: false,
 1650            show_git_blame_inline: false,
 1651            show_selection_menu: None,
 1652            show_git_blame_inline_delay_task: None,
 1653            git_blame_inline_tooltip: None,
 1654            git_blame_inline_enabled: ProjectSettings::get_global(cx).git.inline_blame_enabled(),
 1655            render_diff_hunk_controls: Arc::new(render_diff_hunk_controls),
 1656            serialize_dirty_buffers: ProjectSettings::get_global(cx)
 1657                .session
 1658                .restore_unsaved_buffers,
 1659            blame: None,
 1660            blame_subscription: None,
 1661            tasks: Default::default(),
 1662
 1663            breakpoint_store,
 1664            gutter_breakpoint_indicator: (None, None),
 1665            _subscriptions: vec![
 1666                cx.observe(&buffer, Self::on_buffer_changed),
 1667                cx.subscribe_in(&buffer, window, Self::on_buffer_event),
 1668                cx.observe_in(&display_map, window, Self::on_display_map_changed),
 1669                cx.observe(&blink_manager, |_, _, cx| cx.notify()),
 1670                cx.observe_global_in::<SettingsStore>(window, Self::settings_changed),
 1671                observe_buffer_font_size_adjustment(cx, |_, cx| cx.notify()),
 1672                cx.observe_window_activation(window, |editor, window, cx| {
 1673                    let active = window.is_window_active();
 1674                    editor.blink_manager.update(cx, |blink_manager, cx| {
 1675                        if active {
 1676                            blink_manager.enable(cx);
 1677                        } else {
 1678                            blink_manager.disable(cx);
 1679                        }
 1680                    });
 1681                }),
 1682            ],
 1683            tasks_update_task: None,
 1684            linked_edit_ranges: Default::default(),
 1685            in_project_search: false,
 1686            previous_search_ranges: None,
 1687            breadcrumb_header: None,
 1688            focused_block: None,
 1689            next_scroll_position: NextScrollCursorCenterTopBottom::default(),
 1690            addons: HashMap::default(),
 1691            registered_buffers: HashMap::default(),
 1692            _scroll_cursor_center_top_bottom_task: Task::ready(()),
 1693            selection_mark_mode: false,
 1694            toggle_fold_multiple_buffers: Task::ready(()),
 1695            serialize_selections: Task::ready(()),
 1696            serialize_folds: Task::ready(()),
 1697            text_style_refinement: None,
 1698            load_diff_task: load_uncommitted_diff,
 1699            mouse_cursor_hidden: false,
 1700            hide_mouse_mode: EditorSettings::get_global(cx)
 1701                .hide_mouse
 1702                .unwrap_or_default(),
 1703            change_list: ChangeList::new(),
 1704        };
 1705        if let Some(breakpoints) = this.breakpoint_store.as_ref() {
 1706            this._subscriptions
 1707                .push(cx.observe(breakpoints, |_, _, cx| {
 1708                    cx.notify();
 1709                }));
 1710        }
 1711        this.tasks_update_task = Some(this.refresh_runnables(window, cx));
 1712        this._subscriptions.extend(project_subscriptions);
 1713
 1714        this._subscriptions.push(cx.subscribe_in(
 1715            &cx.entity(),
 1716            window,
 1717            |editor, _, e: &EditorEvent, window, cx| match e {
 1718                EditorEvent::ScrollPositionChanged { local, .. } => {
 1719                    if *local {
 1720                        let new_anchor = editor.scroll_manager.anchor();
 1721                        let snapshot = editor.snapshot(window, cx);
 1722                        editor.update_restoration_data(cx, move |data| {
 1723                            data.scroll_position = (
 1724                                new_anchor.top_row(&snapshot.buffer_snapshot),
 1725                                new_anchor.offset,
 1726                            );
 1727                        });
 1728                        editor.hide_signature_help(cx, SignatureHelpHiddenBy::Escape);
 1729                    }
 1730                }
 1731                EditorEvent::Edited { .. } => {
 1732                    if !vim_enabled(cx) {
 1733                        let (map, selections) = editor.selections.all_adjusted_display(cx);
 1734                        let pop_state = editor
 1735                            .change_list
 1736                            .last()
 1737                            .map(|previous| {
 1738                                previous.len() == selections.len()
 1739                                    && previous.iter().enumerate().all(|(ix, p)| {
 1740                                        p.to_display_point(&map).row()
 1741                                            == selections[ix].head().row()
 1742                                    })
 1743                            })
 1744                            .unwrap_or(false);
 1745                        let new_positions = selections
 1746                            .into_iter()
 1747                            .map(|s| map.display_point_to_anchor(s.head(), Bias::Left))
 1748                            .collect();
 1749                        editor
 1750                            .change_list
 1751                            .push_to_change_list(pop_state, new_positions);
 1752                    }
 1753                }
 1754                _ => (),
 1755            },
 1756        ));
 1757
 1758        this.end_selection(window, cx);
 1759        this.scroll_manager.show_scrollbars(window, cx);
 1760        jsx_tag_auto_close::refresh_enabled_in_any_buffer(&mut this, &buffer, cx);
 1761
 1762        if mode.is_full() {
 1763            let should_auto_hide_scrollbars = cx.should_auto_hide_scrollbars();
 1764            cx.set_global(ScrollbarAutoHide(should_auto_hide_scrollbars));
 1765
 1766            if this.git_blame_inline_enabled {
 1767                this.git_blame_inline_enabled = true;
 1768                this.start_git_blame_inline(false, window, cx);
 1769            }
 1770
 1771            this.go_to_active_debug_line(window, cx);
 1772
 1773            if let Some(buffer) = buffer.read(cx).as_singleton() {
 1774                if let Some(project) = this.project.as_ref() {
 1775                    let handle = project.update(cx, |project, cx| {
 1776                        project.register_buffer_with_language_servers(&buffer, cx)
 1777                    });
 1778                    this.registered_buffers
 1779                        .insert(buffer.read(cx).remote_id(), handle);
 1780                }
 1781            }
 1782        }
 1783
 1784        this.report_editor_event("Editor Opened", None, cx);
 1785        this
 1786    }
 1787
 1788    pub fn deploy_mouse_context_menu(
 1789        &mut self,
 1790        position: gpui::Point<Pixels>,
 1791        context_menu: Entity<ContextMenu>,
 1792        window: &mut Window,
 1793        cx: &mut Context<Self>,
 1794    ) {
 1795        self.mouse_context_menu = Some(MouseContextMenu::new(
 1796            self,
 1797            crate::mouse_context_menu::MenuPosition::PinnedToScreen(position),
 1798            context_menu,
 1799            window,
 1800            cx,
 1801        ));
 1802    }
 1803
 1804    pub fn mouse_menu_is_focused(&self, window: &Window, cx: &App) -> bool {
 1805        self.mouse_context_menu
 1806            .as_ref()
 1807            .is_some_and(|menu| menu.context_menu.focus_handle(cx).is_focused(window))
 1808    }
 1809
 1810    fn key_context(&self, window: &Window, cx: &App) -> KeyContext {
 1811        self.key_context_internal(self.has_active_inline_completion(), window, cx)
 1812    }
 1813
 1814    fn key_context_internal(
 1815        &self,
 1816        has_active_edit_prediction: bool,
 1817        window: &Window,
 1818        cx: &App,
 1819    ) -> KeyContext {
 1820        let mut key_context = KeyContext::new_with_defaults();
 1821        key_context.add("Editor");
 1822        let mode = match self.mode {
 1823            EditorMode::SingleLine { .. } => "single_line",
 1824            EditorMode::AutoHeight { .. } => "auto_height",
 1825            EditorMode::Full { .. } => "full",
 1826        };
 1827
 1828        if EditorSettings::jupyter_enabled(cx) {
 1829            key_context.add("jupyter");
 1830        }
 1831
 1832        key_context.set("mode", mode);
 1833        if self.pending_rename.is_some() {
 1834            key_context.add("renaming");
 1835        }
 1836
 1837        match self.context_menu.borrow().as_ref() {
 1838            Some(CodeContextMenu::Completions(_)) => {
 1839                key_context.add("menu");
 1840                key_context.add("showing_completions");
 1841            }
 1842            Some(CodeContextMenu::CodeActions(_)) => {
 1843                key_context.add("menu");
 1844                key_context.add("showing_code_actions")
 1845            }
 1846            None => {}
 1847        }
 1848
 1849        // Disable vim contexts when a sub-editor (e.g. rename/inline assistant) is focused.
 1850        if !self.focus_handle(cx).contains_focused(window, cx)
 1851            || (self.is_focused(window) || self.mouse_menu_is_focused(window, cx))
 1852        {
 1853            for addon in self.addons.values() {
 1854                addon.extend_key_context(&mut key_context, cx)
 1855            }
 1856        }
 1857
 1858        if let Some(singleton_buffer) = self.buffer.read(cx).as_singleton() {
 1859            if let Some(extension) = singleton_buffer
 1860                .read(cx)
 1861                .file()
 1862                .and_then(|file| file.path().extension()?.to_str())
 1863            {
 1864                key_context.set("extension", extension.to_string());
 1865            }
 1866        } else {
 1867            key_context.add("multibuffer");
 1868        }
 1869
 1870        if has_active_edit_prediction {
 1871            if self.edit_prediction_in_conflict() {
 1872                key_context.add(EDIT_PREDICTION_CONFLICT_KEY_CONTEXT);
 1873            } else {
 1874                key_context.add(EDIT_PREDICTION_KEY_CONTEXT);
 1875                key_context.add("copilot_suggestion");
 1876            }
 1877        }
 1878
 1879        if self.selection_mark_mode {
 1880            key_context.add("selection_mode");
 1881        }
 1882
 1883        key_context
 1884    }
 1885
 1886    pub fn hide_mouse_cursor(&mut self, origin: &HideMouseCursorOrigin) {
 1887        self.mouse_cursor_hidden = match origin {
 1888            HideMouseCursorOrigin::TypingAction => {
 1889                matches!(
 1890                    self.hide_mouse_mode,
 1891                    HideMouseMode::OnTyping | HideMouseMode::OnTypingAndMovement
 1892                )
 1893            }
 1894            HideMouseCursorOrigin::MovementAction => {
 1895                matches!(self.hide_mouse_mode, HideMouseMode::OnTypingAndMovement)
 1896            }
 1897        };
 1898    }
 1899
 1900    pub fn edit_prediction_in_conflict(&self) -> bool {
 1901        if !self.show_edit_predictions_in_menu() {
 1902            return false;
 1903        }
 1904
 1905        let showing_completions = self
 1906            .context_menu
 1907            .borrow()
 1908            .as_ref()
 1909            .map_or(false, |context| {
 1910                matches!(context, CodeContextMenu::Completions(_))
 1911            });
 1912
 1913        showing_completions
 1914            || self.edit_prediction_requires_modifier()
 1915            // Require modifier key when the cursor is on leading whitespace, to allow `tab`
 1916            // bindings to insert tab characters.
 1917            || (self.edit_prediction_requires_modifier_in_indent_conflict && self.edit_prediction_indent_conflict)
 1918    }
 1919
 1920    pub fn accept_edit_prediction_keybind(
 1921        &self,
 1922        window: &Window,
 1923        cx: &App,
 1924    ) -> AcceptEditPredictionBinding {
 1925        let key_context = self.key_context_internal(true, window, cx);
 1926        let in_conflict = self.edit_prediction_in_conflict();
 1927
 1928        AcceptEditPredictionBinding(
 1929            window
 1930                .bindings_for_action_in_context(&AcceptEditPrediction, key_context)
 1931                .into_iter()
 1932                .filter(|binding| {
 1933                    !in_conflict
 1934                        || binding
 1935                            .keystrokes()
 1936                            .first()
 1937                            .map_or(false, |keystroke| keystroke.modifiers.modified())
 1938                })
 1939                .rev()
 1940                .min_by_key(|binding| {
 1941                    binding
 1942                        .keystrokes()
 1943                        .first()
 1944                        .map_or(u8::MAX, |k| k.modifiers.number_of_modifiers())
 1945                }),
 1946        )
 1947    }
 1948
 1949    pub fn new_file(
 1950        workspace: &mut Workspace,
 1951        _: &workspace::NewFile,
 1952        window: &mut Window,
 1953        cx: &mut Context<Workspace>,
 1954    ) {
 1955        Self::new_in_workspace(workspace, window, cx).detach_and_prompt_err(
 1956            "Failed to create buffer",
 1957            window,
 1958            cx,
 1959            |e, _, _| match e.error_code() {
 1960                ErrorCode::RemoteUpgradeRequired => Some(format!(
 1961                "The remote instance of Zed does not support this yet. It must be upgraded to {}",
 1962                e.error_tag("required").unwrap_or("the latest version")
 1963            )),
 1964                _ => None,
 1965            },
 1966        );
 1967    }
 1968
 1969    pub fn new_in_workspace(
 1970        workspace: &mut Workspace,
 1971        window: &mut Window,
 1972        cx: &mut Context<Workspace>,
 1973    ) -> Task<Result<Entity<Editor>>> {
 1974        let project = workspace.project().clone();
 1975        let create = project.update(cx, |project, cx| project.create_buffer(cx));
 1976
 1977        cx.spawn_in(window, async move |workspace, cx| {
 1978            let buffer = create.await?;
 1979            workspace.update_in(cx, |workspace, window, cx| {
 1980                let editor =
 1981                    cx.new(|cx| Editor::for_buffer(buffer, Some(project.clone()), window, cx));
 1982                workspace.add_item_to_active_pane(Box::new(editor.clone()), None, true, window, cx);
 1983                editor
 1984            })
 1985        })
 1986    }
 1987
 1988    fn new_file_vertical(
 1989        workspace: &mut Workspace,
 1990        _: &workspace::NewFileSplitVertical,
 1991        window: &mut Window,
 1992        cx: &mut Context<Workspace>,
 1993    ) {
 1994        Self::new_file_in_direction(workspace, SplitDirection::vertical(cx), window, cx)
 1995    }
 1996
 1997    fn new_file_horizontal(
 1998        workspace: &mut Workspace,
 1999        _: &workspace::NewFileSplitHorizontal,
 2000        window: &mut Window,
 2001        cx: &mut Context<Workspace>,
 2002    ) {
 2003        Self::new_file_in_direction(workspace, SplitDirection::horizontal(cx), window, cx)
 2004    }
 2005
 2006    fn new_file_in_direction(
 2007        workspace: &mut Workspace,
 2008        direction: SplitDirection,
 2009        window: &mut Window,
 2010        cx: &mut Context<Workspace>,
 2011    ) {
 2012        let project = workspace.project().clone();
 2013        let create = project.update(cx, |project, cx| project.create_buffer(cx));
 2014
 2015        cx.spawn_in(window, async move |workspace, cx| {
 2016            let buffer = create.await?;
 2017            workspace.update_in(cx, move |workspace, window, cx| {
 2018                workspace.split_item(
 2019                    direction,
 2020                    Box::new(
 2021                        cx.new(|cx| Editor::for_buffer(buffer, Some(project.clone()), window, cx)),
 2022                    ),
 2023                    window,
 2024                    cx,
 2025                )
 2026            })?;
 2027            anyhow::Ok(())
 2028        })
 2029        .detach_and_prompt_err("Failed to create buffer", window, cx, |e, _, _| {
 2030            match e.error_code() {
 2031                ErrorCode::RemoteUpgradeRequired => Some(format!(
 2032                "The remote instance of Zed does not support this yet. It must be upgraded to {}",
 2033                e.error_tag("required").unwrap_or("the latest version")
 2034            )),
 2035                _ => None,
 2036            }
 2037        });
 2038    }
 2039
 2040    pub fn leader_peer_id(&self) -> Option<PeerId> {
 2041        self.leader_peer_id
 2042    }
 2043
 2044    pub fn buffer(&self) -> &Entity<MultiBuffer> {
 2045        &self.buffer
 2046    }
 2047
 2048    pub fn workspace(&self) -> Option<Entity<Workspace>> {
 2049        self.workspace.as_ref()?.0.upgrade()
 2050    }
 2051
 2052    pub fn title<'a>(&self, cx: &'a App) -> Cow<'a, str> {
 2053        self.buffer().read(cx).title(cx)
 2054    }
 2055
 2056    pub fn snapshot(&self, window: &mut Window, cx: &mut App) -> EditorSnapshot {
 2057        let git_blame_gutter_max_author_length = self
 2058            .render_git_blame_gutter(cx)
 2059            .then(|| {
 2060                if let Some(blame) = self.blame.as_ref() {
 2061                    let max_author_length =
 2062                        blame.update(cx, |blame, cx| blame.max_author_length(cx));
 2063                    Some(max_author_length)
 2064                } else {
 2065                    None
 2066                }
 2067            })
 2068            .flatten();
 2069
 2070        EditorSnapshot {
 2071            mode: self.mode,
 2072            show_gutter: self.show_gutter,
 2073            show_line_numbers: self.show_line_numbers,
 2074            show_git_diff_gutter: self.show_git_diff_gutter,
 2075            show_code_actions: self.show_code_actions,
 2076            show_runnables: self.show_runnables,
 2077            show_breakpoints: self.show_breakpoints,
 2078            git_blame_gutter_max_author_length,
 2079            display_snapshot: self.display_map.update(cx, |map, cx| map.snapshot(cx)),
 2080            scroll_anchor: self.scroll_manager.anchor(),
 2081            ongoing_scroll: self.scroll_manager.ongoing_scroll(),
 2082            placeholder_text: self.placeholder_text.clone(),
 2083            is_focused: self.focus_handle.is_focused(window),
 2084            current_line_highlight: self
 2085                .current_line_highlight
 2086                .unwrap_or_else(|| EditorSettings::get_global(cx).current_line_highlight),
 2087            gutter_hovered: self.gutter_hovered,
 2088        }
 2089    }
 2090
 2091    pub fn language_at<T: ToOffset>(&self, point: T, cx: &App) -> Option<Arc<Language>> {
 2092        self.buffer.read(cx).language_at(point, cx)
 2093    }
 2094
 2095    pub fn file_at<T: ToOffset>(&self, point: T, cx: &App) -> Option<Arc<dyn language::File>> {
 2096        self.buffer.read(cx).read(cx).file_at(point).cloned()
 2097    }
 2098
 2099    pub fn active_excerpt(
 2100        &self,
 2101        cx: &App,
 2102    ) -> Option<(ExcerptId, Entity<Buffer>, Range<text::Anchor>)> {
 2103        self.buffer
 2104            .read(cx)
 2105            .excerpt_containing(self.selections.newest_anchor().head(), cx)
 2106    }
 2107
 2108    pub fn mode(&self) -> EditorMode {
 2109        self.mode
 2110    }
 2111
 2112    pub fn set_mode(&mut self, mode: EditorMode) {
 2113        self.mode = mode;
 2114    }
 2115
 2116    pub fn collaboration_hub(&self) -> Option<&dyn CollaborationHub> {
 2117        self.collaboration_hub.as_deref()
 2118    }
 2119
 2120    pub fn set_collaboration_hub(&mut self, hub: Box<dyn CollaborationHub>) {
 2121        self.collaboration_hub = Some(hub);
 2122    }
 2123
 2124    pub fn set_in_project_search(&mut self, in_project_search: bool) {
 2125        self.in_project_search = in_project_search;
 2126    }
 2127
 2128    pub fn set_custom_context_menu(
 2129        &mut self,
 2130        f: impl 'static
 2131        + Fn(
 2132            &mut Self,
 2133            DisplayPoint,
 2134            &mut Window,
 2135            &mut Context<Self>,
 2136        ) -> Option<Entity<ui::ContextMenu>>,
 2137    ) {
 2138        self.custom_context_menu = Some(Box::new(f))
 2139    }
 2140
 2141    pub fn set_completion_provider(&mut self, provider: Option<Box<dyn CompletionProvider>>) {
 2142        self.completion_provider = provider;
 2143    }
 2144
 2145    pub fn semantics_provider(&self) -> Option<Rc<dyn SemanticsProvider>> {
 2146        self.semantics_provider.clone()
 2147    }
 2148
 2149    pub fn set_semantics_provider(&mut self, provider: Option<Rc<dyn SemanticsProvider>>) {
 2150        self.semantics_provider = provider;
 2151    }
 2152
 2153    pub fn set_edit_prediction_provider<T>(
 2154        &mut self,
 2155        provider: Option<Entity<T>>,
 2156        window: &mut Window,
 2157        cx: &mut Context<Self>,
 2158    ) where
 2159        T: EditPredictionProvider,
 2160    {
 2161        self.edit_prediction_provider =
 2162            provider.map(|provider| RegisteredInlineCompletionProvider {
 2163                _subscription: cx.observe_in(&provider, window, |this, _, window, cx| {
 2164                    if this.focus_handle.is_focused(window) {
 2165                        this.update_visible_inline_completion(window, cx);
 2166                    }
 2167                }),
 2168                provider: Arc::new(provider),
 2169            });
 2170        self.update_edit_prediction_settings(cx);
 2171        self.refresh_inline_completion(false, false, window, cx);
 2172    }
 2173
 2174    pub fn placeholder_text(&self) -> Option<&str> {
 2175        self.placeholder_text.as_deref()
 2176    }
 2177
 2178    pub fn set_placeholder_text(
 2179        &mut self,
 2180        placeholder_text: impl Into<Arc<str>>,
 2181        cx: &mut Context<Self>,
 2182    ) {
 2183        let placeholder_text = Some(placeholder_text.into());
 2184        if self.placeholder_text != placeholder_text {
 2185            self.placeholder_text = placeholder_text;
 2186            cx.notify();
 2187        }
 2188    }
 2189
 2190    pub fn set_cursor_shape(&mut self, cursor_shape: CursorShape, cx: &mut Context<Self>) {
 2191        self.cursor_shape = cursor_shape;
 2192
 2193        // Disrupt blink for immediate user feedback that the cursor shape has changed
 2194        self.blink_manager.update(cx, BlinkManager::show_cursor);
 2195
 2196        cx.notify();
 2197    }
 2198
 2199    pub fn set_current_line_highlight(
 2200        &mut self,
 2201        current_line_highlight: Option<CurrentLineHighlight>,
 2202    ) {
 2203        self.current_line_highlight = current_line_highlight;
 2204    }
 2205
 2206    pub fn set_collapse_matches(&mut self, collapse_matches: bool) {
 2207        self.collapse_matches = collapse_matches;
 2208    }
 2209
 2210    fn register_buffers_with_language_servers(&mut self, cx: &mut Context<Self>) {
 2211        let buffers = self.buffer.read(cx).all_buffers();
 2212        let Some(project) = self.project.as_ref() else {
 2213            return;
 2214        };
 2215        project.update(cx, |project, cx| {
 2216            for buffer in buffers {
 2217                self.registered_buffers
 2218                    .entry(buffer.read(cx).remote_id())
 2219                    .or_insert_with(|| project.register_buffer_with_language_servers(&buffer, cx));
 2220            }
 2221        })
 2222    }
 2223
 2224    pub fn range_for_match<T: std::marker::Copy>(&self, range: &Range<T>) -> Range<T> {
 2225        if self.collapse_matches {
 2226            return range.start..range.start;
 2227        }
 2228        range.clone()
 2229    }
 2230
 2231    pub fn set_clip_at_line_ends(&mut self, clip: bool, cx: &mut Context<Self>) {
 2232        if self.display_map.read(cx).clip_at_line_ends != clip {
 2233            self.display_map
 2234                .update(cx, |map, _| map.clip_at_line_ends = clip);
 2235        }
 2236    }
 2237
 2238    pub fn set_input_enabled(&mut self, input_enabled: bool) {
 2239        self.input_enabled = input_enabled;
 2240    }
 2241
 2242    pub fn set_inline_completions_hidden_for_vim_mode(
 2243        &mut self,
 2244        hidden: bool,
 2245        window: &mut Window,
 2246        cx: &mut Context<Self>,
 2247    ) {
 2248        if hidden != self.inline_completions_hidden_for_vim_mode {
 2249            self.inline_completions_hidden_for_vim_mode = hidden;
 2250            if hidden {
 2251                self.update_visible_inline_completion(window, cx);
 2252            } else {
 2253                self.refresh_inline_completion(true, false, window, cx);
 2254            }
 2255        }
 2256    }
 2257
 2258    pub fn set_menu_inline_completions_policy(&mut self, value: MenuInlineCompletionsPolicy) {
 2259        self.menu_inline_completions_policy = value;
 2260    }
 2261
 2262    pub fn set_autoindent(&mut self, autoindent: bool) {
 2263        if autoindent {
 2264            self.autoindent_mode = Some(AutoindentMode::EachLine);
 2265        } else {
 2266            self.autoindent_mode = None;
 2267        }
 2268    }
 2269
 2270    pub fn read_only(&self, cx: &App) -> bool {
 2271        self.read_only || self.buffer.read(cx).read_only()
 2272    }
 2273
 2274    pub fn set_read_only(&mut self, read_only: bool) {
 2275        self.read_only = read_only;
 2276    }
 2277
 2278    pub fn set_use_autoclose(&mut self, autoclose: bool) {
 2279        self.use_autoclose = autoclose;
 2280    }
 2281
 2282    pub fn set_use_auto_surround(&mut self, auto_surround: bool) {
 2283        self.use_auto_surround = auto_surround;
 2284    }
 2285
 2286    pub fn set_auto_replace_emoji_shortcode(&mut self, auto_replace: bool) {
 2287        self.auto_replace_emoji_shortcode = auto_replace;
 2288    }
 2289
 2290    pub fn toggle_edit_predictions(
 2291        &mut self,
 2292        _: &ToggleEditPrediction,
 2293        window: &mut Window,
 2294        cx: &mut Context<Self>,
 2295    ) {
 2296        if self.show_inline_completions_override.is_some() {
 2297            self.set_show_edit_predictions(None, window, cx);
 2298        } else {
 2299            let show_edit_predictions = !self.edit_predictions_enabled();
 2300            self.set_show_edit_predictions(Some(show_edit_predictions), window, cx);
 2301        }
 2302    }
 2303
 2304    pub fn set_show_edit_predictions(
 2305        &mut self,
 2306        show_edit_predictions: Option<bool>,
 2307        window: &mut Window,
 2308        cx: &mut Context<Self>,
 2309    ) {
 2310        self.show_inline_completions_override = show_edit_predictions;
 2311        self.update_edit_prediction_settings(cx);
 2312
 2313        if let Some(false) = show_edit_predictions {
 2314            self.discard_inline_completion(false, cx);
 2315        } else {
 2316            self.refresh_inline_completion(false, true, window, cx);
 2317        }
 2318    }
 2319
 2320    fn inline_completions_disabled_in_scope(
 2321        &self,
 2322        buffer: &Entity<Buffer>,
 2323        buffer_position: language::Anchor,
 2324        cx: &App,
 2325    ) -> bool {
 2326        let snapshot = buffer.read(cx).snapshot();
 2327        let settings = snapshot.settings_at(buffer_position, cx);
 2328
 2329        let Some(scope) = snapshot.language_scope_at(buffer_position) else {
 2330            return false;
 2331        };
 2332
 2333        scope.override_name().map_or(false, |scope_name| {
 2334            settings
 2335                .edit_predictions_disabled_in
 2336                .iter()
 2337                .any(|s| s == scope_name)
 2338        })
 2339    }
 2340
 2341    pub fn set_use_modal_editing(&mut self, to: bool) {
 2342        self.use_modal_editing = to;
 2343    }
 2344
 2345    pub fn use_modal_editing(&self) -> bool {
 2346        self.use_modal_editing
 2347    }
 2348
 2349    fn selections_did_change(
 2350        &mut self,
 2351        local: bool,
 2352        old_cursor_position: &Anchor,
 2353        show_completions: bool,
 2354        window: &mut Window,
 2355        cx: &mut Context<Self>,
 2356    ) {
 2357        window.invalidate_character_coordinates();
 2358
 2359        // Copy selections to primary selection buffer
 2360        #[cfg(any(target_os = "linux", target_os = "freebsd"))]
 2361        if local {
 2362            let selections = self.selections.all::<usize>(cx);
 2363            let buffer_handle = self.buffer.read(cx).read(cx);
 2364
 2365            let mut text = String::new();
 2366            for (index, selection) in selections.iter().enumerate() {
 2367                let text_for_selection = buffer_handle
 2368                    .text_for_range(selection.start..selection.end)
 2369                    .collect::<String>();
 2370
 2371                text.push_str(&text_for_selection);
 2372                if index != selections.len() - 1 {
 2373                    text.push('\n');
 2374                }
 2375            }
 2376
 2377            if !text.is_empty() {
 2378                cx.write_to_primary(ClipboardItem::new_string(text));
 2379            }
 2380        }
 2381
 2382        if self.focus_handle.is_focused(window) && self.leader_peer_id.is_none() {
 2383            self.buffer.update(cx, |buffer, cx| {
 2384                buffer.set_active_selections(
 2385                    &self.selections.disjoint_anchors(),
 2386                    self.selections.line_mode,
 2387                    self.cursor_shape,
 2388                    cx,
 2389                )
 2390            });
 2391        }
 2392        let display_map = self
 2393            .display_map
 2394            .update(cx, |display_map, cx| display_map.snapshot(cx));
 2395        let buffer = &display_map.buffer_snapshot;
 2396        self.add_selections_state = None;
 2397        self.select_next_state = None;
 2398        self.select_prev_state = None;
 2399        self.select_syntax_node_history.try_clear();
 2400        self.invalidate_autoclose_regions(&self.selections.disjoint_anchors(), buffer);
 2401        self.snippet_stack
 2402            .invalidate(&self.selections.disjoint_anchors(), buffer);
 2403        self.take_rename(false, window, cx);
 2404
 2405        let new_cursor_position = self.selections.newest_anchor().head();
 2406
 2407        self.push_to_nav_history(
 2408            *old_cursor_position,
 2409            Some(new_cursor_position.to_point(buffer)),
 2410            false,
 2411            cx,
 2412        );
 2413
 2414        if local {
 2415            let new_cursor_position = self.selections.newest_anchor().head();
 2416            let mut context_menu = self.context_menu.borrow_mut();
 2417            let completion_menu = match context_menu.as_ref() {
 2418                Some(CodeContextMenu::Completions(menu)) => Some(menu),
 2419                _ => {
 2420                    *context_menu = None;
 2421                    None
 2422                }
 2423            };
 2424            if let Some(buffer_id) = new_cursor_position.buffer_id {
 2425                if !self.registered_buffers.contains_key(&buffer_id) {
 2426                    if let Some(project) = self.project.as_ref() {
 2427                        project.update(cx, |project, cx| {
 2428                            let Some(buffer) = self.buffer.read(cx).buffer(buffer_id) else {
 2429                                return;
 2430                            };
 2431                            self.registered_buffers.insert(
 2432                                buffer_id,
 2433                                project.register_buffer_with_language_servers(&buffer, cx),
 2434                            );
 2435                        })
 2436                    }
 2437                }
 2438            }
 2439
 2440            if let Some(completion_menu) = completion_menu {
 2441                let cursor_position = new_cursor_position.to_offset(buffer);
 2442                let (word_range, kind) =
 2443                    buffer.surrounding_word(completion_menu.initial_position, true);
 2444                if kind == Some(CharKind::Word)
 2445                    && word_range.to_inclusive().contains(&cursor_position)
 2446                {
 2447                    let mut completion_menu = completion_menu.clone();
 2448                    drop(context_menu);
 2449
 2450                    let query = Self::completion_query(buffer, cursor_position);
 2451                    cx.spawn(async move |this, cx| {
 2452                        completion_menu
 2453                            .filter(query.as_deref(), cx.background_executor().clone())
 2454                            .await;
 2455
 2456                        this.update(cx, |this, cx| {
 2457                            let mut context_menu = this.context_menu.borrow_mut();
 2458                            let Some(CodeContextMenu::Completions(menu)) = context_menu.as_ref()
 2459                            else {
 2460                                return;
 2461                            };
 2462
 2463                            if menu.id > completion_menu.id {
 2464                                return;
 2465                            }
 2466
 2467                            *context_menu = Some(CodeContextMenu::Completions(completion_menu));
 2468                            drop(context_menu);
 2469                            cx.notify();
 2470                        })
 2471                    })
 2472                    .detach();
 2473
 2474                    if show_completions {
 2475                        self.show_completions(&ShowCompletions { trigger: None }, window, cx);
 2476                    }
 2477                } else {
 2478                    drop(context_menu);
 2479                    self.hide_context_menu(window, cx);
 2480                }
 2481            } else {
 2482                drop(context_menu);
 2483            }
 2484
 2485            hide_hover(self, cx);
 2486
 2487            if old_cursor_position.to_display_point(&display_map).row()
 2488                != new_cursor_position.to_display_point(&display_map).row()
 2489            {
 2490                self.available_code_actions.take();
 2491            }
 2492            self.refresh_code_actions(window, cx);
 2493            self.refresh_document_highlights(cx);
 2494            self.refresh_selected_text_highlights(window, cx);
 2495            refresh_matching_bracket_highlights(self, window, cx);
 2496            self.update_visible_inline_completion(window, cx);
 2497            self.edit_prediction_requires_modifier_in_indent_conflict = true;
 2498            linked_editing_ranges::refresh_linked_ranges(self, window, cx);
 2499            if self.git_blame_inline_enabled {
 2500                self.start_inline_blame_timer(window, cx);
 2501            }
 2502        }
 2503
 2504        self.blink_manager.update(cx, BlinkManager::pause_blinking);
 2505        cx.emit(EditorEvent::SelectionsChanged { local });
 2506
 2507        let selections = &self.selections.disjoint;
 2508        if selections.len() == 1 {
 2509            cx.emit(SearchEvent::ActiveMatchChanged)
 2510        }
 2511        if local {
 2512            if let Some((_, _, buffer_snapshot)) = buffer.as_singleton() {
 2513                let inmemory_selections = selections
 2514                    .iter()
 2515                    .map(|s| {
 2516                        text::ToPoint::to_point(&s.range().start.text_anchor, buffer_snapshot)
 2517                            ..text::ToPoint::to_point(&s.range().end.text_anchor, buffer_snapshot)
 2518                    })
 2519                    .collect();
 2520                self.update_restoration_data(cx, |data| {
 2521                    data.selections = inmemory_selections;
 2522                });
 2523
 2524                if WorkspaceSettings::get(None, cx).restore_on_startup
 2525                    != RestoreOnStartupBehavior::None
 2526                {
 2527                    if let Some(workspace_id) =
 2528                        self.workspace.as_ref().and_then(|workspace| workspace.1)
 2529                    {
 2530                        let snapshot = self.buffer().read(cx).snapshot(cx);
 2531                        let selections = selections.clone();
 2532                        let background_executor = cx.background_executor().clone();
 2533                        let editor_id = cx.entity().entity_id().as_u64() as ItemId;
 2534                        self.serialize_selections = cx.background_spawn(async move {
 2535                    background_executor.timer(SERIALIZATION_THROTTLE_TIME).await;
 2536                    let db_selections = selections
 2537                        .iter()
 2538                        .map(|selection| {
 2539                            (
 2540                                selection.start.to_offset(&snapshot),
 2541                                selection.end.to_offset(&snapshot),
 2542                            )
 2543                        })
 2544                        .collect();
 2545
 2546                    DB.save_editor_selections(editor_id, workspace_id, db_selections)
 2547                        .await
 2548                        .with_context(|| format!("persisting editor selections for editor {editor_id}, workspace {workspace_id:?}"))
 2549                        .log_err();
 2550                });
 2551                    }
 2552                }
 2553            }
 2554        }
 2555
 2556        cx.notify();
 2557    }
 2558
 2559    fn folds_did_change(&mut self, cx: &mut Context<Self>) {
 2560        use text::ToOffset as _;
 2561        use text::ToPoint as _;
 2562
 2563        if WorkspaceSettings::get(None, cx).restore_on_startup == RestoreOnStartupBehavior::None {
 2564            return;
 2565        }
 2566
 2567        let Some(singleton) = self.buffer().read(cx).as_singleton() else {
 2568            return;
 2569        };
 2570
 2571        let snapshot = singleton.read(cx).snapshot();
 2572        let inmemory_folds = self.display_map.update(cx, |display_map, cx| {
 2573            let display_snapshot = display_map.snapshot(cx);
 2574
 2575            display_snapshot
 2576                .folds_in_range(0..display_snapshot.buffer_snapshot.len())
 2577                .map(|fold| {
 2578                    fold.range.start.text_anchor.to_point(&snapshot)
 2579                        ..fold.range.end.text_anchor.to_point(&snapshot)
 2580                })
 2581                .collect()
 2582        });
 2583        self.update_restoration_data(cx, |data| {
 2584            data.folds = inmemory_folds;
 2585        });
 2586
 2587        let Some(workspace_id) = self.workspace.as_ref().and_then(|workspace| workspace.1) else {
 2588            return;
 2589        };
 2590        let background_executor = cx.background_executor().clone();
 2591        let editor_id = cx.entity().entity_id().as_u64() as ItemId;
 2592        let db_folds = self.display_map.update(cx, |display_map, cx| {
 2593            display_map
 2594                .snapshot(cx)
 2595                .folds_in_range(0..snapshot.len())
 2596                .map(|fold| {
 2597                    (
 2598                        fold.range.start.text_anchor.to_offset(&snapshot),
 2599                        fold.range.end.text_anchor.to_offset(&snapshot),
 2600                    )
 2601                })
 2602                .collect()
 2603        });
 2604        self.serialize_folds = cx.background_spawn(async move {
 2605            background_executor.timer(SERIALIZATION_THROTTLE_TIME).await;
 2606            DB.save_editor_folds(editor_id, workspace_id, db_folds)
 2607                .await
 2608                .with_context(|| {
 2609                    format!(
 2610                        "persisting editor folds for editor {editor_id}, workspace {workspace_id:?}"
 2611                    )
 2612                })
 2613                .log_err();
 2614        });
 2615    }
 2616
 2617    pub fn sync_selections(
 2618        &mut self,
 2619        other: Entity<Editor>,
 2620        cx: &mut Context<Self>,
 2621    ) -> gpui::Subscription {
 2622        let other_selections = other.read(cx).selections.disjoint.to_vec();
 2623        self.selections.change_with(cx, |selections| {
 2624            selections.select_anchors(other_selections);
 2625        });
 2626
 2627        let other_subscription =
 2628            cx.subscribe(&other, |this, other, other_evt, cx| match other_evt {
 2629                EditorEvent::SelectionsChanged { local: true } => {
 2630                    let other_selections = other.read(cx).selections.disjoint.to_vec();
 2631                    if other_selections.is_empty() {
 2632                        return;
 2633                    }
 2634                    this.selections.change_with(cx, |selections| {
 2635                        selections.select_anchors(other_selections);
 2636                    });
 2637                }
 2638                _ => {}
 2639            });
 2640
 2641        let this_subscription =
 2642            cx.subscribe_self::<EditorEvent>(move |this, this_evt, cx| match this_evt {
 2643                EditorEvent::SelectionsChanged { local: true } => {
 2644                    let these_selections = this.selections.disjoint.to_vec();
 2645                    if these_selections.is_empty() {
 2646                        return;
 2647                    }
 2648                    other.update(cx, |other_editor, cx| {
 2649                        other_editor.selections.change_with(cx, |selections| {
 2650                            selections.select_anchors(these_selections);
 2651                        })
 2652                    });
 2653                }
 2654                _ => {}
 2655            });
 2656
 2657        Subscription::join(other_subscription, this_subscription)
 2658    }
 2659
 2660    pub fn change_selections<R>(
 2661        &mut self,
 2662        autoscroll: Option<Autoscroll>,
 2663        window: &mut Window,
 2664        cx: &mut Context<Self>,
 2665        change: impl FnOnce(&mut MutableSelectionsCollection<'_>) -> R,
 2666    ) -> R {
 2667        self.change_selections_inner(autoscroll, true, window, cx, change)
 2668    }
 2669
 2670    fn change_selections_inner<R>(
 2671        &mut self,
 2672        autoscroll: Option<Autoscroll>,
 2673        request_completions: bool,
 2674        window: &mut Window,
 2675        cx: &mut Context<Self>,
 2676        change: impl FnOnce(&mut MutableSelectionsCollection<'_>) -> R,
 2677    ) -> R {
 2678        let old_cursor_position = self.selections.newest_anchor().head();
 2679        self.push_to_selection_history();
 2680
 2681        let (changed, result) = self.selections.change_with(cx, change);
 2682
 2683        if changed {
 2684            if let Some(autoscroll) = autoscroll {
 2685                self.request_autoscroll(autoscroll, cx);
 2686            }
 2687            self.selections_did_change(true, &old_cursor_position, request_completions, window, cx);
 2688
 2689            if self.should_open_signature_help_automatically(
 2690                &old_cursor_position,
 2691                self.signature_help_state.backspace_pressed(),
 2692                cx,
 2693            ) {
 2694                self.show_signature_help(&ShowSignatureHelp, window, cx);
 2695            }
 2696            self.signature_help_state.set_backspace_pressed(false);
 2697        }
 2698
 2699        result
 2700    }
 2701
 2702    pub fn edit<I, S, T>(&mut self, edits: I, cx: &mut Context<Self>)
 2703    where
 2704        I: IntoIterator<Item = (Range<S>, T)>,
 2705        S: ToOffset,
 2706        T: Into<Arc<str>>,
 2707    {
 2708        if self.read_only(cx) {
 2709            return;
 2710        }
 2711
 2712        self.buffer
 2713            .update(cx, |buffer, cx| buffer.edit(edits, None, cx));
 2714    }
 2715
 2716    pub fn edit_with_autoindent<I, S, T>(&mut self, edits: I, cx: &mut Context<Self>)
 2717    where
 2718        I: IntoIterator<Item = (Range<S>, T)>,
 2719        S: ToOffset,
 2720        T: Into<Arc<str>>,
 2721    {
 2722        if self.read_only(cx) {
 2723            return;
 2724        }
 2725
 2726        self.buffer.update(cx, |buffer, cx| {
 2727            buffer.edit(edits, self.autoindent_mode.clone(), cx)
 2728        });
 2729    }
 2730
 2731    pub fn edit_with_block_indent<I, S, T>(
 2732        &mut self,
 2733        edits: I,
 2734        original_indent_columns: Vec<Option<u32>>,
 2735        cx: &mut Context<Self>,
 2736    ) where
 2737        I: IntoIterator<Item = (Range<S>, T)>,
 2738        S: ToOffset,
 2739        T: Into<Arc<str>>,
 2740    {
 2741        if self.read_only(cx) {
 2742            return;
 2743        }
 2744
 2745        self.buffer.update(cx, |buffer, cx| {
 2746            buffer.edit(
 2747                edits,
 2748                Some(AutoindentMode::Block {
 2749                    original_indent_columns,
 2750                }),
 2751                cx,
 2752            )
 2753        });
 2754    }
 2755
 2756    fn select(&mut self, phase: SelectPhase, window: &mut Window, cx: &mut Context<Self>) {
 2757        self.hide_context_menu(window, cx);
 2758
 2759        match phase {
 2760            SelectPhase::Begin {
 2761                position,
 2762                add,
 2763                click_count,
 2764            } => self.begin_selection(position, add, click_count, window, cx),
 2765            SelectPhase::BeginColumnar {
 2766                position,
 2767                goal_column,
 2768                reset,
 2769            } => self.begin_columnar_selection(position, goal_column, reset, window, cx),
 2770            SelectPhase::Extend {
 2771                position,
 2772                click_count,
 2773            } => self.extend_selection(position, click_count, window, cx),
 2774            SelectPhase::Update {
 2775                position,
 2776                goal_column,
 2777                scroll_delta,
 2778            } => self.update_selection(position, goal_column, scroll_delta, window, cx),
 2779            SelectPhase::End => self.end_selection(window, cx),
 2780        }
 2781    }
 2782
 2783    fn extend_selection(
 2784        &mut self,
 2785        position: DisplayPoint,
 2786        click_count: usize,
 2787        window: &mut Window,
 2788        cx: &mut Context<Self>,
 2789    ) {
 2790        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 2791        let tail = self.selections.newest::<usize>(cx).tail();
 2792        self.begin_selection(position, false, click_count, window, cx);
 2793
 2794        let position = position.to_offset(&display_map, Bias::Left);
 2795        let tail_anchor = display_map.buffer_snapshot.anchor_before(tail);
 2796
 2797        let mut pending_selection = self
 2798            .selections
 2799            .pending_anchor()
 2800            .expect("extend_selection not called with pending selection");
 2801        if position >= tail {
 2802            pending_selection.start = tail_anchor;
 2803        } else {
 2804            pending_selection.end = tail_anchor;
 2805            pending_selection.reversed = true;
 2806        }
 2807
 2808        let mut pending_mode = self.selections.pending_mode().unwrap();
 2809        match &mut pending_mode {
 2810            SelectMode::Word(range) | SelectMode::Line(range) => *range = tail_anchor..tail_anchor,
 2811            _ => {}
 2812        }
 2813
 2814        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 2815            s.set_pending(pending_selection, pending_mode)
 2816        });
 2817    }
 2818
 2819    fn begin_selection(
 2820        &mut self,
 2821        position: DisplayPoint,
 2822        add: bool,
 2823        click_count: usize,
 2824        window: &mut Window,
 2825        cx: &mut Context<Self>,
 2826    ) {
 2827        if !self.focus_handle.is_focused(window) {
 2828            self.last_focused_descendant = None;
 2829            window.focus(&self.focus_handle);
 2830        }
 2831
 2832        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 2833        let buffer = &display_map.buffer_snapshot;
 2834        let newest_selection = self.selections.newest_anchor().clone();
 2835        let position = display_map.clip_point(position, Bias::Left);
 2836
 2837        let start;
 2838        let end;
 2839        let mode;
 2840        let mut auto_scroll;
 2841        match click_count {
 2842            1 => {
 2843                start = buffer.anchor_before(position.to_point(&display_map));
 2844                end = start;
 2845                mode = SelectMode::Character;
 2846                auto_scroll = true;
 2847            }
 2848            2 => {
 2849                let range = movement::surrounding_word(&display_map, position);
 2850                start = buffer.anchor_before(range.start.to_point(&display_map));
 2851                end = buffer.anchor_before(range.end.to_point(&display_map));
 2852                mode = SelectMode::Word(start..end);
 2853                auto_scroll = true;
 2854            }
 2855            3 => {
 2856                let position = display_map
 2857                    .clip_point(position, Bias::Left)
 2858                    .to_point(&display_map);
 2859                let line_start = display_map.prev_line_boundary(position).0;
 2860                let next_line_start = buffer.clip_point(
 2861                    display_map.next_line_boundary(position).0 + Point::new(1, 0),
 2862                    Bias::Left,
 2863                );
 2864                start = buffer.anchor_before(line_start);
 2865                end = buffer.anchor_before(next_line_start);
 2866                mode = SelectMode::Line(start..end);
 2867                auto_scroll = true;
 2868            }
 2869            _ => {
 2870                start = buffer.anchor_before(0);
 2871                end = buffer.anchor_before(buffer.len());
 2872                mode = SelectMode::All;
 2873                auto_scroll = false;
 2874            }
 2875        }
 2876        auto_scroll &= EditorSettings::get_global(cx).autoscroll_on_clicks;
 2877
 2878        let point_to_delete: Option<usize> = {
 2879            let selected_points: Vec<Selection<Point>> =
 2880                self.selections.disjoint_in_range(start..end, cx);
 2881
 2882            if !add || click_count > 1 {
 2883                None
 2884            } else if !selected_points.is_empty() {
 2885                Some(selected_points[0].id)
 2886            } else {
 2887                let clicked_point_already_selected =
 2888                    self.selections.disjoint.iter().find(|selection| {
 2889                        selection.start.to_point(buffer) == start.to_point(buffer)
 2890                            || selection.end.to_point(buffer) == end.to_point(buffer)
 2891                    });
 2892
 2893                clicked_point_already_selected.map(|selection| selection.id)
 2894            }
 2895        };
 2896
 2897        let selections_count = self.selections.count();
 2898
 2899        self.change_selections(auto_scroll.then(Autoscroll::newest), window, cx, |s| {
 2900            if let Some(point_to_delete) = point_to_delete {
 2901                s.delete(point_to_delete);
 2902
 2903                if selections_count == 1 {
 2904                    s.set_pending_anchor_range(start..end, mode);
 2905                }
 2906            } else {
 2907                if !add {
 2908                    s.clear_disjoint();
 2909                } else if click_count > 1 {
 2910                    s.delete(newest_selection.id)
 2911                }
 2912
 2913                s.set_pending_anchor_range(start..end, mode);
 2914            }
 2915        });
 2916    }
 2917
 2918    fn begin_columnar_selection(
 2919        &mut self,
 2920        position: DisplayPoint,
 2921        goal_column: u32,
 2922        reset: bool,
 2923        window: &mut Window,
 2924        cx: &mut Context<Self>,
 2925    ) {
 2926        if !self.focus_handle.is_focused(window) {
 2927            self.last_focused_descendant = None;
 2928            window.focus(&self.focus_handle);
 2929        }
 2930
 2931        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 2932
 2933        if reset {
 2934            let pointer_position = display_map
 2935                .buffer_snapshot
 2936                .anchor_before(position.to_point(&display_map));
 2937
 2938            self.change_selections(Some(Autoscroll::newest()), window, cx, |s| {
 2939                s.clear_disjoint();
 2940                s.set_pending_anchor_range(
 2941                    pointer_position..pointer_position,
 2942                    SelectMode::Character,
 2943                );
 2944            });
 2945        }
 2946
 2947        let tail = self.selections.newest::<Point>(cx).tail();
 2948        self.columnar_selection_tail = Some(display_map.buffer_snapshot.anchor_before(tail));
 2949
 2950        if !reset {
 2951            self.select_columns(
 2952                tail.to_display_point(&display_map),
 2953                position,
 2954                goal_column,
 2955                &display_map,
 2956                window,
 2957                cx,
 2958            );
 2959        }
 2960    }
 2961
 2962    fn update_selection(
 2963        &mut self,
 2964        position: DisplayPoint,
 2965        goal_column: u32,
 2966        scroll_delta: gpui::Point<f32>,
 2967        window: &mut Window,
 2968        cx: &mut Context<Self>,
 2969    ) {
 2970        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 2971
 2972        if let Some(tail) = self.columnar_selection_tail.as_ref() {
 2973            let tail = tail.to_display_point(&display_map);
 2974            self.select_columns(tail, position, goal_column, &display_map, window, cx);
 2975        } else if let Some(mut pending) = self.selections.pending_anchor() {
 2976            let buffer = self.buffer.read(cx).snapshot(cx);
 2977            let head;
 2978            let tail;
 2979            let mode = self.selections.pending_mode().unwrap();
 2980            match &mode {
 2981                SelectMode::Character => {
 2982                    head = position.to_point(&display_map);
 2983                    tail = pending.tail().to_point(&buffer);
 2984                }
 2985                SelectMode::Word(original_range) => {
 2986                    let original_display_range = original_range.start.to_display_point(&display_map)
 2987                        ..original_range.end.to_display_point(&display_map);
 2988                    let original_buffer_range = original_display_range.start.to_point(&display_map)
 2989                        ..original_display_range.end.to_point(&display_map);
 2990                    if movement::is_inside_word(&display_map, position)
 2991                        || original_display_range.contains(&position)
 2992                    {
 2993                        let word_range = movement::surrounding_word(&display_map, position);
 2994                        if word_range.start < original_display_range.start {
 2995                            head = word_range.start.to_point(&display_map);
 2996                        } else {
 2997                            head = word_range.end.to_point(&display_map);
 2998                        }
 2999                    } else {
 3000                        head = position.to_point(&display_map);
 3001                    }
 3002
 3003                    if head <= original_buffer_range.start {
 3004                        tail = original_buffer_range.end;
 3005                    } else {
 3006                        tail = original_buffer_range.start;
 3007                    }
 3008                }
 3009                SelectMode::Line(original_range) => {
 3010                    let original_range = original_range.to_point(&display_map.buffer_snapshot);
 3011
 3012                    let position = display_map
 3013                        .clip_point(position, Bias::Left)
 3014                        .to_point(&display_map);
 3015                    let line_start = display_map.prev_line_boundary(position).0;
 3016                    let next_line_start = buffer.clip_point(
 3017                        display_map.next_line_boundary(position).0 + Point::new(1, 0),
 3018                        Bias::Left,
 3019                    );
 3020
 3021                    if line_start < original_range.start {
 3022                        head = line_start
 3023                    } else {
 3024                        head = next_line_start
 3025                    }
 3026
 3027                    if head <= original_range.start {
 3028                        tail = original_range.end;
 3029                    } else {
 3030                        tail = original_range.start;
 3031                    }
 3032                }
 3033                SelectMode::All => {
 3034                    return;
 3035                }
 3036            };
 3037
 3038            if head < tail {
 3039                pending.start = buffer.anchor_before(head);
 3040                pending.end = buffer.anchor_before(tail);
 3041                pending.reversed = true;
 3042            } else {
 3043                pending.start = buffer.anchor_before(tail);
 3044                pending.end = buffer.anchor_before(head);
 3045                pending.reversed = false;
 3046            }
 3047
 3048            self.change_selections(None, window, cx, |s| {
 3049                s.set_pending(pending, mode);
 3050            });
 3051        } else {
 3052            log::error!("update_selection dispatched with no pending selection");
 3053            return;
 3054        }
 3055
 3056        self.apply_scroll_delta(scroll_delta, window, cx);
 3057        cx.notify();
 3058    }
 3059
 3060    fn end_selection(&mut self, window: &mut Window, cx: &mut Context<Self>) {
 3061        self.columnar_selection_tail.take();
 3062        if self.selections.pending_anchor().is_some() {
 3063            let selections = self.selections.all::<usize>(cx);
 3064            self.change_selections(None, window, cx, |s| {
 3065                s.select(selections);
 3066                s.clear_pending();
 3067            });
 3068        }
 3069    }
 3070
 3071    fn select_columns(
 3072        &mut self,
 3073        tail: DisplayPoint,
 3074        head: DisplayPoint,
 3075        goal_column: u32,
 3076        display_map: &DisplaySnapshot,
 3077        window: &mut Window,
 3078        cx: &mut Context<Self>,
 3079    ) {
 3080        let start_row = cmp::min(tail.row(), head.row());
 3081        let end_row = cmp::max(tail.row(), head.row());
 3082        let start_column = cmp::min(tail.column(), goal_column);
 3083        let end_column = cmp::max(tail.column(), goal_column);
 3084        let reversed = start_column < tail.column();
 3085
 3086        let selection_ranges = (start_row.0..=end_row.0)
 3087            .map(DisplayRow)
 3088            .filter_map(|row| {
 3089                if start_column <= display_map.line_len(row) && !display_map.is_block_line(row) {
 3090                    let start = display_map
 3091                        .clip_point(DisplayPoint::new(row, start_column), Bias::Left)
 3092                        .to_point(display_map);
 3093                    let end = display_map
 3094                        .clip_point(DisplayPoint::new(row, end_column), Bias::Right)
 3095                        .to_point(display_map);
 3096                    if reversed {
 3097                        Some(end..start)
 3098                    } else {
 3099                        Some(start..end)
 3100                    }
 3101                } else {
 3102                    None
 3103                }
 3104            })
 3105            .collect::<Vec<_>>();
 3106
 3107        self.change_selections(None, window, cx, |s| {
 3108            s.select_ranges(selection_ranges);
 3109        });
 3110        cx.notify();
 3111    }
 3112
 3113    pub fn has_non_empty_selection(&self, cx: &mut App) -> bool {
 3114        self.selections
 3115            .all_adjusted(cx)
 3116            .iter()
 3117            .any(|selection| !selection.is_empty())
 3118    }
 3119
 3120    pub fn has_pending_nonempty_selection(&self) -> bool {
 3121        let pending_nonempty_selection = match self.selections.pending_anchor() {
 3122            Some(Selection { start, end, .. }) => start != end,
 3123            None => false,
 3124        };
 3125
 3126        pending_nonempty_selection
 3127            || (self.columnar_selection_tail.is_some() && self.selections.disjoint.len() > 1)
 3128    }
 3129
 3130    pub fn has_pending_selection(&self) -> bool {
 3131        self.selections.pending_anchor().is_some() || self.columnar_selection_tail.is_some()
 3132    }
 3133
 3134    pub fn cancel(&mut self, _: &Cancel, window: &mut Window, cx: &mut Context<Self>) {
 3135        self.selection_mark_mode = false;
 3136
 3137        if self.clear_expanded_diff_hunks(cx) {
 3138            cx.notify();
 3139            return;
 3140        }
 3141        if self.dismiss_menus_and_popups(true, window, cx) {
 3142            return;
 3143        }
 3144
 3145        if self.mode.is_full()
 3146            && self.change_selections(Some(Autoscroll::fit()), window, cx, |s| s.try_cancel())
 3147        {
 3148            return;
 3149        }
 3150
 3151        cx.propagate();
 3152    }
 3153
 3154    pub fn dismiss_menus_and_popups(
 3155        &mut self,
 3156        is_user_requested: bool,
 3157        window: &mut Window,
 3158        cx: &mut Context<Self>,
 3159    ) -> bool {
 3160        if self.take_rename(false, window, cx).is_some() {
 3161            return true;
 3162        }
 3163
 3164        if hide_hover(self, cx) {
 3165            return true;
 3166        }
 3167
 3168        if self.hide_signature_help(cx, SignatureHelpHiddenBy::Escape) {
 3169            return true;
 3170        }
 3171
 3172        if self.hide_context_menu(window, cx).is_some() {
 3173            return true;
 3174        }
 3175
 3176        if self.mouse_context_menu.take().is_some() {
 3177            return true;
 3178        }
 3179
 3180        if is_user_requested && self.discard_inline_completion(true, cx) {
 3181            return true;
 3182        }
 3183
 3184        if self.snippet_stack.pop().is_some() {
 3185            return true;
 3186        }
 3187
 3188        if self.mode.is_full() && matches!(self.active_diagnostics, ActiveDiagnostic::Group(_)) {
 3189            self.dismiss_diagnostics(cx);
 3190            return true;
 3191        }
 3192
 3193        false
 3194    }
 3195
 3196    fn linked_editing_ranges_for(
 3197        &self,
 3198        selection: Range<text::Anchor>,
 3199        cx: &App,
 3200    ) -> Option<HashMap<Entity<Buffer>, Vec<Range<text::Anchor>>>> {
 3201        if self.linked_edit_ranges.is_empty() {
 3202            return None;
 3203        }
 3204        let ((base_range, linked_ranges), buffer_snapshot, buffer) =
 3205            selection.end.buffer_id.and_then(|end_buffer_id| {
 3206                if selection.start.buffer_id != Some(end_buffer_id) {
 3207                    return None;
 3208                }
 3209                let buffer = self.buffer.read(cx).buffer(end_buffer_id)?;
 3210                let snapshot = buffer.read(cx).snapshot();
 3211                self.linked_edit_ranges
 3212                    .get(end_buffer_id, selection.start..selection.end, &snapshot)
 3213                    .map(|ranges| (ranges, snapshot, buffer))
 3214            })?;
 3215        use text::ToOffset as TO;
 3216        // find offset from the start of current range to current cursor position
 3217        let start_byte_offset = TO::to_offset(&base_range.start, &buffer_snapshot);
 3218
 3219        let start_offset = TO::to_offset(&selection.start, &buffer_snapshot);
 3220        let start_difference = start_offset - start_byte_offset;
 3221        let end_offset = TO::to_offset(&selection.end, &buffer_snapshot);
 3222        let end_difference = end_offset - start_byte_offset;
 3223        // Current range has associated linked ranges.
 3224        let mut linked_edits = HashMap::<_, Vec<_>>::default();
 3225        for range in linked_ranges.iter() {
 3226            let start_offset = TO::to_offset(&range.start, &buffer_snapshot);
 3227            let end_offset = start_offset + end_difference;
 3228            let start_offset = start_offset + start_difference;
 3229            if start_offset > buffer_snapshot.len() || end_offset > buffer_snapshot.len() {
 3230                continue;
 3231            }
 3232            if self.selections.disjoint_anchor_ranges().any(|s| {
 3233                if s.start.buffer_id != selection.start.buffer_id
 3234                    || s.end.buffer_id != selection.end.buffer_id
 3235                {
 3236                    return false;
 3237                }
 3238                TO::to_offset(&s.start.text_anchor, &buffer_snapshot) <= end_offset
 3239                    && TO::to_offset(&s.end.text_anchor, &buffer_snapshot) >= start_offset
 3240            }) {
 3241                continue;
 3242            }
 3243            let start = buffer_snapshot.anchor_after(start_offset);
 3244            let end = buffer_snapshot.anchor_after(end_offset);
 3245            linked_edits
 3246                .entry(buffer.clone())
 3247                .or_default()
 3248                .push(start..end);
 3249        }
 3250        Some(linked_edits)
 3251    }
 3252
 3253    pub fn handle_input(&mut self, text: &str, window: &mut Window, cx: &mut Context<Self>) {
 3254        let text: Arc<str> = text.into();
 3255
 3256        if self.read_only(cx) {
 3257            return;
 3258        }
 3259
 3260        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
 3261
 3262        let selections = self.selections.all_adjusted(cx);
 3263        let mut bracket_inserted = false;
 3264        let mut edits = Vec::new();
 3265        let mut linked_edits = HashMap::<_, Vec<_>>::default();
 3266        let mut new_selections = Vec::with_capacity(selections.len());
 3267        let mut new_autoclose_regions = Vec::new();
 3268        let snapshot = self.buffer.read(cx).read(cx);
 3269        let mut clear_linked_edit_ranges = false;
 3270
 3271        for (selection, autoclose_region) in
 3272            self.selections_with_autoclose_regions(selections, &snapshot)
 3273        {
 3274            if let Some(scope) = snapshot.language_scope_at(selection.head()) {
 3275                // Determine if the inserted text matches the opening or closing
 3276                // bracket of any of this language's bracket pairs.
 3277                let mut bracket_pair = None;
 3278                let mut is_bracket_pair_start = false;
 3279                let mut is_bracket_pair_end = false;
 3280                if !text.is_empty() {
 3281                    let mut bracket_pair_matching_end = None;
 3282                    // `text` can be empty when a user is using IME (e.g. Chinese Wubi Simplified)
 3283                    //  and they are removing the character that triggered IME popup.
 3284                    for (pair, enabled) in scope.brackets() {
 3285                        if !pair.close && !pair.surround {
 3286                            continue;
 3287                        }
 3288
 3289                        if enabled && pair.start.ends_with(text.as_ref()) {
 3290                            let prefix_len = pair.start.len() - text.len();
 3291                            let preceding_text_matches_prefix = prefix_len == 0
 3292                                || (selection.start.column >= (prefix_len as u32)
 3293                                    && snapshot.contains_str_at(
 3294                                        Point::new(
 3295                                            selection.start.row,
 3296                                            selection.start.column - (prefix_len as u32),
 3297                                        ),
 3298                                        &pair.start[..prefix_len],
 3299                                    ));
 3300                            if preceding_text_matches_prefix {
 3301                                bracket_pair = Some(pair.clone());
 3302                                is_bracket_pair_start = true;
 3303                                break;
 3304                            }
 3305                        }
 3306                        if pair.end.as_str() == text.as_ref() && bracket_pair_matching_end.is_none()
 3307                        {
 3308                            // take first bracket pair matching end, but don't break in case a later bracket
 3309                            // pair matches start
 3310                            bracket_pair_matching_end = Some(pair.clone());
 3311                        }
 3312                    }
 3313                    if bracket_pair.is_none() && bracket_pair_matching_end.is_some() {
 3314                        bracket_pair = Some(bracket_pair_matching_end.unwrap());
 3315                        is_bracket_pair_end = true;
 3316                    }
 3317                }
 3318
 3319                if let Some(bracket_pair) = bracket_pair {
 3320                    let snapshot_settings = snapshot.language_settings_at(selection.start, cx);
 3321                    let autoclose = self.use_autoclose && snapshot_settings.use_autoclose;
 3322                    let auto_surround =
 3323                        self.use_auto_surround && snapshot_settings.use_auto_surround;
 3324                    if selection.is_empty() {
 3325                        if is_bracket_pair_start {
 3326                            // If the inserted text is a suffix of an opening bracket and the
 3327                            // selection is preceded by the rest of the opening bracket, then
 3328                            // insert the closing bracket.
 3329                            let following_text_allows_autoclose = snapshot
 3330                                .chars_at(selection.start)
 3331                                .next()
 3332                                .map_or(true, |c| scope.should_autoclose_before(c));
 3333
 3334                            let preceding_text_allows_autoclose = selection.start.column == 0
 3335                                || snapshot.reversed_chars_at(selection.start).next().map_or(
 3336                                    true,
 3337                                    |c| {
 3338                                        bracket_pair.start != bracket_pair.end
 3339                                            || !snapshot
 3340                                                .char_classifier_at(selection.start)
 3341                                                .is_word(c)
 3342                                    },
 3343                                );
 3344
 3345                            let is_closing_quote = if bracket_pair.end == bracket_pair.start
 3346                                && bracket_pair.start.len() == 1
 3347                            {
 3348                                let target = bracket_pair.start.chars().next().unwrap();
 3349                                let current_line_count = snapshot
 3350                                    .reversed_chars_at(selection.start)
 3351                                    .take_while(|&c| c != '\n')
 3352                                    .filter(|&c| c == target)
 3353                                    .count();
 3354                                current_line_count % 2 == 1
 3355                            } else {
 3356                                false
 3357                            };
 3358
 3359                            if autoclose
 3360                                && bracket_pair.close
 3361                                && following_text_allows_autoclose
 3362                                && preceding_text_allows_autoclose
 3363                                && !is_closing_quote
 3364                            {
 3365                                let anchor = snapshot.anchor_before(selection.end);
 3366                                new_selections.push((selection.map(|_| anchor), text.len()));
 3367                                new_autoclose_regions.push((
 3368                                    anchor,
 3369                                    text.len(),
 3370                                    selection.id,
 3371                                    bracket_pair.clone(),
 3372                                ));
 3373                                edits.push((
 3374                                    selection.range(),
 3375                                    format!("{}{}", text, bracket_pair.end).into(),
 3376                                ));
 3377                                bracket_inserted = true;
 3378                                continue;
 3379                            }
 3380                        }
 3381
 3382                        if let Some(region) = autoclose_region {
 3383                            // If the selection is followed by an auto-inserted closing bracket,
 3384                            // then don't insert that closing bracket again; just move the selection
 3385                            // past the closing bracket.
 3386                            let should_skip = selection.end == region.range.end.to_point(&snapshot)
 3387                                && text.as_ref() == region.pair.end.as_str();
 3388                            if should_skip {
 3389                                let anchor = snapshot.anchor_after(selection.end);
 3390                                new_selections
 3391                                    .push((selection.map(|_| anchor), region.pair.end.len()));
 3392                                continue;
 3393                            }
 3394                        }
 3395
 3396                        let always_treat_brackets_as_autoclosed = snapshot
 3397                            .language_settings_at(selection.start, cx)
 3398                            .always_treat_brackets_as_autoclosed;
 3399                        if always_treat_brackets_as_autoclosed
 3400                            && is_bracket_pair_end
 3401                            && snapshot.contains_str_at(selection.end, text.as_ref())
 3402                        {
 3403                            // Otherwise, when `always_treat_brackets_as_autoclosed` is set to `true
 3404                            // and the inserted text is a closing bracket and the selection is followed
 3405                            // by the closing bracket then move the selection past the closing bracket.
 3406                            let anchor = snapshot.anchor_after(selection.end);
 3407                            new_selections.push((selection.map(|_| anchor), text.len()));
 3408                            continue;
 3409                        }
 3410                    }
 3411                    // If an opening bracket is 1 character long and is typed while
 3412                    // text is selected, then surround that text with the bracket pair.
 3413                    else if auto_surround
 3414                        && bracket_pair.surround
 3415                        && is_bracket_pair_start
 3416                        && bracket_pair.start.chars().count() == 1
 3417                    {
 3418                        edits.push((selection.start..selection.start, text.clone()));
 3419                        edits.push((
 3420                            selection.end..selection.end,
 3421                            bracket_pair.end.as_str().into(),
 3422                        ));
 3423                        bracket_inserted = true;
 3424                        new_selections.push((
 3425                            Selection {
 3426                                id: selection.id,
 3427                                start: snapshot.anchor_after(selection.start),
 3428                                end: snapshot.anchor_before(selection.end),
 3429                                reversed: selection.reversed,
 3430                                goal: selection.goal,
 3431                            },
 3432                            0,
 3433                        ));
 3434                        continue;
 3435                    }
 3436                }
 3437            }
 3438
 3439            if self.auto_replace_emoji_shortcode
 3440                && selection.is_empty()
 3441                && text.as_ref().ends_with(':')
 3442            {
 3443                if let Some(possible_emoji_short_code) =
 3444                    Self::find_possible_emoji_shortcode_at_position(&snapshot, selection.start)
 3445                {
 3446                    if !possible_emoji_short_code.is_empty() {
 3447                        if let Some(emoji) = emojis::get_by_shortcode(&possible_emoji_short_code) {
 3448                            let emoji_shortcode_start = Point::new(
 3449                                selection.start.row,
 3450                                selection.start.column - possible_emoji_short_code.len() as u32 - 1,
 3451                            );
 3452
 3453                            // Remove shortcode from buffer
 3454                            edits.push((
 3455                                emoji_shortcode_start..selection.start,
 3456                                "".to_string().into(),
 3457                            ));
 3458                            new_selections.push((
 3459                                Selection {
 3460                                    id: selection.id,
 3461                                    start: snapshot.anchor_after(emoji_shortcode_start),
 3462                                    end: snapshot.anchor_before(selection.start),
 3463                                    reversed: selection.reversed,
 3464                                    goal: selection.goal,
 3465                                },
 3466                                0,
 3467                            ));
 3468
 3469                            // Insert emoji
 3470                            let selection_start_anchor = snapshot.anchor_after(selection.start);
 3471                            new_selections.push((selection.map(|_| selection_start_anchor), 0));
 3472                            edits.push((selection.start..selection.end, emoji.to_string().into()));
 3473
 3474                            continue;
 3475                        }
 3476                    }
 3477                }
 3478            }
 3479
 3480            // If not handling any auto-close operation, then just replace the selected
 3481            // text with the given input and move the selection to the end of the
 3482            // newly inserted text.
 3483            let anchor = snapshot.anchor_after(selection.end);
 3484            if !self.linked_edit_ranges.is_empty() {
 3485                let start_anchor = snapshot.anchor_before(selection.start);
 3486
 3487                let is_word_char = text.chars().next().map_or(true, |char| {
 3488                    let classifier = snapshot.char_classifier_at(start_anchor.to_offset(&snapshot));
 3489                    classifier.is_word(char)
 3490                });
 3491
 3492                if is_word_char {
 3493                    if let Some(ranges) = self
 3494                        .linked_editing_ranges_for(start_anchor.text_anchor..anchor.text_anchor, cx)
 3495                    {
 3496                        for (buffer, edits) in ranges {
 3497                            linked_edits
 3498                                .entry(buffer.clone())
 3499                                .or_default()
 3500                                .extend(edits.into_iter().map(|range| (range, text.clone())));
 3501                        }
 3502                    }
 3503                } else {
 3504                    clear_linked_edit_ranges = true;
 3505                }
 3506            }
 3507
 3508            new_selections.push((selection.map(|_| anchor), 0));
 3509            edits.push((selection.start..selection.end, text.clone()));
 3510        }
 3511
 3512        drop(snapshot);
 3513
 3514        self.transact(window, cx, |this, window, cx| {
 3515            if clear_linked_edit_ranges {
 3516                this.linked_edit_ranges.clear();
 3517            }
 3518            let initial_buffer_versions =
 3519                jsx_tag_auto_close::construct_initial_buffer_versions_map(this, &edits, cx);
 3520
 3521            this.buffer.update(cx, |buffer, cx| {
 3522                buffer.edit(edits, this.autoindent_mode.clone(), cx);
 3523            });
 3524            for (buffer, edits) in linked_edits {
 3525                buffer.update(cx, |buffer, cx| {
 3526                    let snapshot = buffer.snapshot();
 3527                    let edits = edits
 3528                        .into_iter()
 3529                        .map(|(range, text)| {
 3530                            use text::ToPoint as TP;
 3531                            let end_point = TP::to_point(&range.end, &snapshot);
 3532                            let start_point = TP::to_point(&range.start, &snapshot);
 3533                            (start_point..end_point, text)
 3534                        })
 3535                        .sorted_by_key(|(range, _)| range.start);
 3536                    buffer.edit(edits, None, cx);
 3537                })
 3538            }
 3539            let new_anchor_selections = new_selections.iter().map(|e| &e.0);
 3540            let new_selection_deltas = new_selections.iter().map(|e| e.1);
 3541            let map = this.display_map.update(cx, |map, cx| map.snapshot(cx));
 3542            let new_selections = resolve_selections::<usize, _>(new_anchor_selections, &map)
 3543                .zip(new_selection_deltas)
 3544                .map(|(selection, delta)| Selection {
 3545                    id: selection.id,
 3546                    start: selection.start + delta,
 3547                    end: selection.end + delta,
 3548                    reversed: selection.reversed,
 3549                    goal: SelectionGoal::None,
 3550                })
 3551                .collect::<Vec<_>>();
 3552
 3553            let mut i = 0;
 3554            for (position, delta, selection_id, pair) in new_autoclose_regions {
 3555                let position = position.to_offset(&map.buffer_snapshot) + delta;
 3556                let start = map.buffer_snapshot.anchor_before(position);
 3557                let end = map.buffer_snapshot.anchor_after(position);
 3558                while let Some(existing_state) = this.autoclose_regions.get(i) {
 3559                    match existing_state.range.start.cmp(&start, &map.buffer_snapshot) {
 3560                        Ordering::Less => i += 1,
 3561                        Ordering::Greater => break,
 3562                        Ordering::Equal => {
 3563                            match end.cmp(&existing_state.range.end, &map.buffer_snapshot) {
 3564                                Ordering::Less => i += 1,
 3565                                Ordering::Equal => break,
 3566                                Ordering::Greater => break,
 3567                            }
 3568                        }
 3569                    }
 3570                }
 3571                this.autoclose_regions.insert(
 3572                    i,
 3573                    AutocloseRegion {
 3574                        selection_id,
 3575                        range: start..end,
 3576                        pair,
 3577                    },
 3578                );
 3579            }
 3580
 3581            let had_active_inline_completion = this.has_active_inline_completion();
 3582            this.change_selections_inner(Some(Autoscroll::fit()), false, window, cx, |s| {
 3583                s.select(new_selections)
 3584            });
 3585
 3586            if !bracket_inserted {
 3587                if let Some(on_type_format_task) =
 3588                    this.trigger_on_type_formatting(text.to_string(), window, cx)
 3589                {
 3590                    on_type_format_task.detach_and_log_err(cx);
 3591                }
 3592            }
 3593
 3594            let editor_settings = EditorSettings::get_global(cx);
 3595            if bracket_inserted
 3596                && (editor_settings.auto_signature_help
 3597                    || editor_settings.show_signature_help_after_edits)
 3598            {
 3599                this.show_signature_help(&ShowSignatureHelp, window, cx);
 3600            }
 3601
 3602            let trigger_in_words =
 3603                this.show_edit_predictions_in_menu() || !had_active_inline_completion;
 3604            if this.hard_wrap.is_some() {
 3605                let latest: Range<Point> = this.selections.newest(cx).range();
 3606                if latest.is_empty()
 3607                    && this
 3608                        .buffer()
 3609                        .read(cx)
 3610                        .snapshot(cx)
 3611                        .line_len(MultiBufferRow(latest.start.row))
 3612                        == latest.start.column
 3613                {
 3614                    this.rewrap_impl(
 3615                        RewrapOptions {
 3616                            override_language_settings: true,
 3617                            preserve_existing_whitespace: true,
 3618                        },
 3619                        cx,
 3620                    )
 3621                }
 3622            }
 3623            this.trigger_completion_on_input(&text, trigger_in_words, window, cx);
 3624            linked_editing_ranges::refresh_linked_ranges(this, window, cx);
 3625            this.refresh_inline_completion(true, false, window, cx);
 3626            jsx_tag_auto_close::handle_from(this, initial_buffer_versions, window, cx);
 3627        });
 3628    }
 3629
 3630    fn find_possible_emoji_shortcode_at_position(
 3631        snapshot: &MultiBufferSnapshot,
 3632        position: Point,
 3633    ) -> Option<String> {
 3634        let mut chars = Vec::new();
 3635        let mut found_colon = false;
 3636        for char in snapshot.reversed_chars_at(position).take(100) {
 3637            // Found a possible emoji shortcode in the middle of the buffer
 3638            if found_colon {
 3639                if char.is_whitespace() {
 3640                    chars.reverse();
 3641                    return Some(chars.iter().collect());
 3642                }
 3643                // If the previous character is not a whitespace, we are in the middle of a word
 3644                // and we only want to complete the shortcode if the word is made up of other emojis
 3645                let mut containing_word = String::new();
 3646                for ch in snapshot
 3647                    .reversed_chars_at(position)
 3648                    .skip(chars.len() + 1)
 3649                    .take(100)
 3650                {
 3651                    if ch.is_whitespace() {
 3652                        break;
 3653                    }
 3654                    containing_word.push(ch);
 3655                }
 3656                let containing_word = containing_word.chars().rev().collect::<String>();
 3657                if util::word_consists_of_emojis(containing_word.as_str()) {
 3658                    chars.reverse();
 3659                    return Some(chars.iter().collect());
 3660                }
 3661            }
 3662
 3663            if char.is_whitespace() || !char.is_ascii() {
 3664                return None;
 3665            }
 3666            if char == ':' {
 3667                found_colon = true;
 3668            } else {
 3669                chars.push(char);
 3670            }
 3671        }
 3672        // Found a possible emoji shortcode at the beginning of the buffer
 3673        chars.reverse();
 3674        Some(chars.iter().collect())
 3675    }
 3676
 3677    pub fn newline(&mut self, _: &Newline, window: &mut Window, cx: &mut Context<Self>) {
 3678        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
 3679        self.transact(window, cx, |this, window, cx| {
 3680            let (edits, selection_fixup_info): (Vec<_>, Vec<_>) = {
 3681                let selections = this.selections.all::<usize>(cx);
 3682                let multi_buffer = this.buffer.read(cx);
 3683                let buffer = multi_buffer.snapshot(cx);
 3684                selections
 3685                    .iter()
 3686                    .map(|selection| {
 3687                        let start_point = selection.start.to_point(&buffer);
 3688                        let mut indent =
 3689                            buffer.indent_size_for_line(MultiBufferRow(start_point.row));
 3690                        indent.len = cmp::min(indent.len, start_point.column);
 3691                        let start = selection.start;
 3692                        let end = selection.end;
 3693                        let selection_is_empty = start == end;
 3694                        let language_scope = buffer.language_scope_at(start);
 3695                        let (comment_delimiter, insert_extra_newline) = if let Some(language) =
 3696                            &language_scope
 3697                        {
 3698                            let insert_extra_newline =
 3699                                insert_extra_newline_brackets(&buffer, start..end, language)
 3700                                    || insert_extra_newline_tree_sitter(&buffer, start..end);
 3701
 3702                            // Comment extension on newline is allowed only for cursor selections
 3703                            let comment_delimiter = maybe!({
 3704                                if !selection_is_empty {
 3705                                    return None;
 3706                                }
 3707
 3708                                if !multi_buffer.language_settings(cx).extend_comment_on_newline {
 3709                                    return None;
 3710                                }
 3711
 3712                                let delimiters = language.line_comment_prefixes();
 3713                                let max_len_of_delimiter =
 3714                                    delimiters.iter().map(|delimiter| delimiter.len()).max()?;
 3715                                let (snapshot, range) =
 3716                                    buffer.buffer_line_for_row(MultiBufferRow(start_point.row))?;
 3717
 3718                                let mut index_of_first_non_whitespace = 0;
 3719                                let comment_candidate = snapshot
 3720                                    .chars_for_range(range)
 3721                                    .skip_while(|c| {
 3722                                        let should_skip = c.is_whitespace();
 3723                                        if should_skip {
 3724                                            index_of_first_non_whitespace += 1;
 3725                                        }
 3726                                        should_skip
 3727                                    })
 3728                                    .take(max_len_of_delimiter)
 3729                                    .collect::<String>();
 3730                                let comment_prefix = delimiters.iter().find(|comment_prefix| {
 3731                                    comment_candidate.starts_with(comment_prefix.as_ref())
 3732                                })?;
 3733                                let cursor_is_placed_after_comment_marker =
 3734                                    index_of_first_non_whitespace + comment_prefix.len()
 3735                                        <= start_point.column as usize;
 3736                                if cursor_is_placed_after_comment_marker {
 3737                                    Some(comment_prefix.clone())
 3738                                } else {
 3739                                    None
 3740                                }
 3741                            });
 3742                            (comment_delimiter, insert_extra_newline)
 3743                        } else {
 3744                            (None, false)
 3745                        };
 3746
 3747                        let capacity_for_delimiter = comment_delimiter
 3748                            .as_deref()
 3749                            .map(str::len)
 3750                            .unwrap_or_default();
 3751                        let mut new_text =
 3752                            String::with_capacity(1 + capacity_for_delimiter + indent.len as usize);
 3753                        new_text.push('\n');
 3754                        new_text.extend(indent.chars());
 3755                        if let Some(delimiter) = &comment_delimiter {
 3756                            new_text.push_str(delimiter);
 3757                        }
 3758                        if insert_extra_newline {
 3759                            new_text = new_text.repeat(2);
 3760                        }
 3761
 3762                        let anchor = buffer.anchor_after(end);
 3763                        let new_selection = selection.map(|_| anchor);
 3764                        (
 3765                            (start..end, new_text),
 3766                            (insert_extra_newline, new_selection),
 3767                        )
 3768                    })
 3769                    .unzip()
 3770            };
 3771
 3772            this.edit_with_autoindent(edits, cx);
 3773            let buffer = this.buffer.read(cx).snapshot(cx);
 3774            let new_selections = selection_fixup_info
 3775                .into_iter()
 3776                .map(|(extra_newline_inserted, new_selection)| {
 3777                    let mut cursor = new_selection.end.to_point(&buffer);
 3778                    if extra_newline_inserted {
 3779                        cursor.row -= 1;
 3780                        cursor.column = buffer.line_len(MultiBufferRow(cursor.row));
 3781                    }
 3782                    new_selection.map(|_| cursor)
 3783                })
 3784                .collect();
 3785
 3786            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 3787                s.select(new_selections)
 3788            });
 3789            this.refresh_inline_completion(true, false, window, cx);
 3790        });
 3791    }
 3792
 3793    pub fn newline_above(&mut self, _: &NewlineAbove, window: &mut Window, cx: &mut Context<Self>) {
 3794        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
 3795
 3796        let buffer = self.buffer.read(cx);
 3797        let snapshot = buffer.snapshot(cx);
 3798
 3799        let mut edits = Vec::new();
 3800        let mut rows = Vec::new();
 3801
 3802        for (rows_inserted, selection) in self.selections.all_adjusted(cx).into_iter().enumerate() {
 3803            let cursor = selection.head();
 3804            let row = cursor.row;
 3805
 3806            let start_of_line = snapshot.clip_point(Point::new(row, 0), Bias::Left);
 3807
 3808            let newline = "\n".to_string();
 3809            edits.push((start_of_line..start_of_line, newline));
 3810
 3811            rows.push(row + rows_inserted as u32);
 3812        }
 3813
 3814        self.transact(window, cx, |editor, window, cx| {
 3815            editor.edit(edits, cx);
 3816
 3817            editor.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 3818                let mut index = 0;
 3819                s.move_cursors_with(|map, _, _| {
 3820                    let row = rows[index];
 3821                    index += 1;
 3822
 3823                    let point = Point::new(row, 0);
 3824                    let boundary = map.next_line_boundary(point).1;
 3825                    let clipped = map.clip_point(boundary, Bias::Left);
 3826
 3827                    (clipped, SelectionGoal::None)
 3828                });
 3829            });
 3830
 3831            let mut indent_edits = Vec::new();
 3832            let multibuffer_snapshot = editor.buffer.read(cx).snapshot(cx);
 3833            for row in rows {
 3834                let indents = multibuffer_snapshot.suggested_indents(row..row + 1, cx);
 3835                for (row, indent) in indents {
 3836                    if indent.len == 0 {
 3837                        continue;
 3838                    }
 3839
 3840                    let text = match indent.kind {
 3841                        IndentKind::Space => " ".repeat(indent.len as usize),
 3842                        IndentKind::Tab => "\t".repeat(indent.len as usize),
 3843                    };
 3844                    let point = Point::new(row.0, 0);
 3845                    indent_edits.push((point..point, text));
 3846                }
 3847            }
 3848            editor.edit(indent_edits, cx);
 3849        });
 3850    }
 3851
 3852    pub fn newline_below(&mut self, _: &NewlineBelow, window: &mut Window, cx: &mut Context<Self>) {
 3853        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
 3854
 3855        let buffer = self.buffer.read(cx);
 3856        let snapshot = buffer.snapshot(cx);
 3857
 3858        let mut edits = Vec::new();
 3859        let mut rows = Vec::new();
 3860        let mut rows_inserted = 0;
 3861
 3862        for selection in self.selections.all_adjusted(cx) {
 3863            let cursor = selection.head();
 3864            let row = cursor.row;
 3865
 3866            let point = Point::new(row + 1, 0);
 3867            let start_of_line = snapshot.clip_point(point, Bias::Left);
 3868
 3869            let newline = "\n".to_string();
 3870            edits.push((start_of_line..start_of_line, newline));
 3871
 3872            rows_inserted += 1;
 3873            rows.push(row + rows_inserted);
 3874        }
 3875
 3876        self.transact(window, cx, |editor, window, cx| {
 3877            editor.edit(edits, cx);
 3878
 3879            editor.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 3880                let mut index = 0;
 3881                s.move_cursors_with(|map, _, _| {
 3882                    let row = rows[index];
 3883                    index += 1;
 3884
 3885                    let point = Point::new(row, 0);
 3886                    let boundary = map.next_line_boundary(point).1;
 3887                    let clipped = map.clip_point(boundary, Bias::Left);
 3888
 3889                    (clipped, SelectionGoal::None)
 3890                });
 3891            });
 3892
 3893            let mut indent_edits = Vec::new();
 3894            let multibuffer_snapshot = editor.buffer.read(cx).snapshot(cx);
 3895            for row in rows {
 3896                let indents = multibuffer_snapshot.suggested_indents(row..row + 1, cx);
 3897                for (row, indent) in indents {
 3898                    if indent.len == 0 {
 3899                        continue;
 3900                    }
 3901
 3902                    let text = match indent.kind {
 3903                        IndentKind::Space => " ".repeat(indent.len as usize),
 3904                        IndentKind::Tab => "\t".repeat(indent.len as usize),
 3905                    };
 3906                    let point = Point::new(row.0, 0);
 3907                    indent_edits.push((point..point, text));
 3908                }
 3909            }
 3910            editor.edit(indent_edits, cx);
 3911        });
 3912    }
 3913
 3914    pub fn insert(&mut self, text: &str, window: &mut Window, cx: &mut Context<Self>) {
 3915        let autoindent = text.is_empty().not().then(|| AutoindentMode::Block {
 3916            original_indent_columns: Vec::new(),
 3917        });
 3918        self.insert_with_autoindent_mode(text, autoindent, window, cx);
 3919    }
 3920
 3921    fn insert_with_autoindent_mode(
 3922        &mut self,
 3923        text: &str,
 3924        autoindent_mode: Option<AutoindentMode>,
 3925        window: &mut Window,
 3926        cx: &mut Context<Self>,
 3927    ) {
 3928        if self.read_only(cx) {
 3929            return;
 3930        }
 3931
 3932        let text: Arc<str> = text.into();
 3933        self.transact(window, cx, |this, window, cx| {
 3934            let old_selections = this.selections.all_adjusted(cx);
 3935            let selection_anchors = this.buffer.update(cx, |buffer, cx| {
 3936                let anchors = {
 3937                    let snapshot = buffer.read(cx);
 3938                    old_selections
 3939                        .iter()
 3940                        .map(|s| {
 3941                            let anchor = snapshot.anchor_after(s.head());
 3942                            s.map(|_| anchor)
 3943                        })
 3944                        .collect::<Vec<_>>()
 3945                };
 3946                buffer.edit(
 3947                    old_selections
 3948                        .iter()
 3949                        .map(|s| (s.start..s.end, text.clone())),
 3950                    autoindent_mode,
 3951                    cx,
 3952                );
 3953                anchors
 3954            });
 3955
 3956            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 3957                s.select_anchors(selection_anchors);
 3958            });
 3959
 3960            cx.notify();
 3961        });
 3962    }
 3963
 3964    fn trigger_completion_on_input(
 3965        &mut self,
 3966        text: &str,
 3967        trigger_in_words: bool,
 3968        window: &mut Window,
 3969        cx: &mut Context<Self>,
 3970    ) {
 3971        let ignore_completion_provider = self
 3972            .context_menu
 3973            .borrow()
 3974            .as_ref()
 3975            .map(|menu| match menu {
 3976                CodeContextMenu::Completions(completions_menu) => {
 3977                    completions_menu.ignore_completion_provider
 3978                }
 3979                CodeContextMenu::CodeActions(_) => false,
 3980            })
 3981            .unwrap_or(false);
 3982
 3983        if ignore_completion_provider {
 3984            self.show_word_completions(&ShowWordCompletions, window, cx);
 3985        } else if self.is_completion_trigger(text, trigger_in_words, cx) {
 3986            self.show_completions(
 3987                &ShowCompletions {
 3988                    trigger: Some(text.to_owned()).filter(|x| !x.is_empty()),
 3989                },
 3990                window,
 3991                cx,
 3992            );
 3993        } else {
 3994            self.hide_context_menu(window, cx);
 3995        }
 3996    }
 3997
 3998    fn is_completion_trigger(
 3999        &self,
 4000        text: &str,
 4001        trigger_in_words: bool,
 4002        cx: &mut Context<Self>,
 4003    ) -> bool {
 4004        let position = self.selections.newest_anchor().head();
 4005        let multibuffer = self.buffer.read(cx);
 4006        let Some(buffer) = position
 4007            .buffer_id
 4008            .and_then(|buffer_id| multibuffer.buffer(buffer_id).clone())
 4009        else {
 4010            return false;
 4011        };
 4012
 4013        if let Some(completion_provider) = &self.completion_provider {
 4014            completion_provider.is_completion_trigger(
 4015                &buffer,
 4016                position.text_anchor,
 4017                text,
 4018                trigger_in_words,
 4019                cx,
 4020            )
 4021        } else {
 4022            false
 4023        }
 4024    }
 4025
 4026    /// If any empty selections is touching the start of its innermost containing autoclose
 4027    /// region, expand it to select the brackets.
 4028    fn select_autoclose_pair(&mut self, window: &mut Window, cx: &mut Context<Self>) {
 4029        let selections = self.selections.all::<usize>(cx);
 4030        let buffer = self.buffer.read(cx).read(cx);
 4031        let new_selections = self
 4032            .selections_with_autoclose_regions(selections, &buffer)
 4033            .map(|(mut selection, region)| {
 4034                if !selection.is_empty() {
 4035                    return selection;
 4036                }
 4037
 4038                if let Some(region) = region {
 4039                    let mut range = region.range.to_offset(&buffer);
 4040                    if selection.start == range.start && range.start >= region.pair.start.len() {
 4041                        range.start -= region.pair.start.len();
 4042                        if buffer.contains_str_at(range.start, &region.pair.start)
 4043                            && buffer.contains_str_at(range.end, &region.pair.end)
 4044                        {
 4045                            range.end += region.pair.end.len();
 4046                            selection.start = range.start;
 4047                            selection.end = range.end;
 4048
 4049                            return selection;
 4050                        }
 4051                    }
 4052                }
 4053
 4054                let always_treat_brackets_as_autoclosed = buffer
 4055                    .language_settings_at(selection.start, cx)
 4056                    .always_treat_brackets_as_autoclosed;
 4057
 4058                if !always_treat_brackets_as_autoclosed {
 4059                    return selection;
 4060                }
 4061
 4062                if let Some(scope) = buffer.language_scope_at(selection.start) {
 4063                    for (pair, enabled) in scope.brackets() {
 4064                        if !enabled || !pair.close {
 4065                            continue;
 4066                        }
 4067
 4068                        if buffer.contains_str_at(selection.start, &pair.end) {
 4069                            let pair_start_len = pair.start.len();
 4070                            if buffer.contains_str_at(
 4071                                selection.start.saturating_sub(pair_start_len),
 4072                                &pair.start,
 4073                            ) {
 4074                                selection.start -= pair_start_len;
 4075                                selection.end += pair.end.len();
 4076
 4077                                return selection;
 4078                            }
 4079                        }
 4080                    }
 4081                }
 4082
 4083                selection
 4084            })
 4085            .collect();
 4086
 4087        drop(buffer);
 4088        self.change_selections(None, window, cx, |selections| {
 4089            selections.select(new_selections)
 4090        });
 4091    }
 4092
 4093    /// Iterate the given selections, and for each one, find the smallest surrounding
 4094    /// autoclose region. This uses the ordering of the selections and the autoclose
 4095    /// regions to avoid repeated comparisons.
 4096    fn selections_with_autoclose_regions<'a, D: ToOffset + Clone>(
 4097        &'a self,
 4098        selections: impl IntoIterator<Item = Selection<D>>,
 4099        buffer: &'a MultiBufferSnapshot,
 4100    ) -> impl Iterator<Item = (Selection<D>, Option<&'a AutocloseRegion>)> {
 4101        let mut i = 0;
 4102        let mut regions = self.autoclose_regions.as_slice();
 4103        selections.into_iter().map(move |selection| {
 4104            let range = selection.start.to_offset(buffer)..selection.end.to_offset(buffer);
 4105
 4106            let mut enclosing = None;
 4107            while let Some(pair_state) = regions.get(i) {
 4108                if pair_state.range.end.to_offset(buffer) < range.start {
 4109                    regions = &regions[i + 1..];
 4110                    i = 0;
 4111                } else if pair_state.range.start.to_offset(buffer) > range.end {
 4112                    break;
 4113                } else {
 4114                    if pair_state.selection_id == selection.id {
 4115                        enclosing = Some(pair_state);
 4116                    }
 4117                    i += 1;
 4118                }
 4119            }
 4120
 4121            (selection, enclosing)
 4122        })
 4123    }
 4124
 4125    /// Remove any autoclose regions that no longer contain their selection.
 4126    fn invalidate_autoclose_regions(
 4127        &mut self,
 4128        mut selections: &[Selection<Anchor>],
 4129        buffer: &MultiBufferSnapshot,
 4130    ) {
 4131        self.autoclose_regions.retain(|state| {
 4132            let mut i = 0;
 4133            while let Some(selection) = selections.get(i) {
 4134                if selection.end.cmp(&state.range.start, buffer).is_lt() {
 4135                    selections = &selections[1..];
 4136                    continue;
 4137                }
 4138                if selection.start.cmp(&state.range.end, buffer).is_gt() {
 4139                    break;
 4140                }
 4141                if selection.id == state.selection_id {
 4142                    return true;
 4143                } else {
 4144                    i += 1;
 4145                }
 4146            }
 4147            false
 4148        });
 4149    }
 4150
 4151    fn completion_query(buffer: &MultiBufferSnapshot, position: impl ToOffset) -> Option<String> {
 4152        let offset = position.to_offset(buffer);
 4153        let (word_range, kind) = buffer.surrounding_word(offset, true);
 4154        if offset > word_range.start && kind == Some(CharKind::Word) {
 4155            Some(
 4156                buffer
 4157                    .text_for_range(word_range.start..offset)
 4158                    .collect::<String>(),
 4159            )
 4160        } else {
 4161            None
 4162        }
 4163    }
 4164
 4165    pub fn toggle_inlay_hints(
 4166        &mut self,
 4167        _: &ToggleInlayHints,
 4168        _: &mut Window,
 4169        cx: &mut Context<Self>,
 4170    ) {
 4171        self.refresh_inlay_hints(
 4172            InlayHintRefreshReason::Toggle(!self.inlay_hints_enabled()),
 4173            cx,
 4174        );
 4175    }
 4176
 4177    pub fn inlay_hints_enabled(&self) -> bool {
 4178        self.inlay_hint_cache.enabled
 4179    }
 4180
 4181    fn refresh_inlay_hints(&mut self, reason: InlayHintRefreshReason, cx: &mut Context<Self>) {
 4182        if self.semantics_provider.is_none() || !self.mode.is_full() {
 4183            return;
 4184        }
 4185
 4186        let reason_description = reason.description();
 4187        let ignore_debounce = matches!(
 4188            reason,
 4189            InlayHintRefreshReason::SettingsChange(_)
 4190                | InlayHintRefreshReason::Toggle(_)
 4191                | InlayHintRefreshReason::ExcerptsRemoved(_)
 4192                | InlayHintRefreshReason::ModifiersChanged(_)
 4193        );
 4194        let (invalidate_cache, required_languages) = match reason {
 4195            InlayHintRefreshReason::ModifiersChanged(enabled) => {
 4196                match self.inlay_hint_cache.modifiers_override(enabled) {
 4197                    Some(enabled) => {
 4198                        if enabled {
 4199                            (InvalidationStrategy::RefreshRequested, None)
 4200                        } else {
 4201                            self.splice_inlays(
 4202                                &self
 4203                                    .visible_inlay_hints(cx)
 4204                                    .iter()
 4205                                    .map(|inlay| inlay.id)
 4206                                    .collect::<Vec<InlayId>>(),
 4207                                Vec::new(),
 4208                                cx,
 4209                            );
 4210                            return;
 4211                        }
 4212                    }
 4213                    None => return,
 4214                }
 4215            }
 4216            InlayHintRefreshReason::Toggle(enabled) => {
 4217                if self.inlay_hint_cache.toggle(enabled) {
 4218                    if enabled {
 4219                        (InvalidationStrategy::RefreshRequested, None)
 4220                    } else {
 4221                        self.splice_inlays(
 4222                            &self
 4223                                .visible_inlay_hints(cx)
 4224                                .iter()
 4225                                .map(|inlay| inlay.id)
 4226                                .collect::<Vec<InlayId>>(),
 4227                            Vec::new(),
 4228                            cx,
 4229                        );
 4230                        return;
 4231                    }
 4232                } else {
 4233                    return;
 4234                }
 4235            }
 4236            InlayHintRefreshReason::SettingsChange(new_settings) => {
 4237                match self.inlay_hint_cache.update_settings(
 4238                    &self.buffer,
 4239                    new_settings,
 4240                    self.visible_inlay_hints(cx),
 4241                    cx,
 4242                ) {
 4243                    ControlFlow::Break(Some(InlaySplice {
 4244                        to_remove,
 4245                        to_insert,
 4246                    })) => {
 4247                        self.splice_inlays(&to_remove, to_insert, cx);
 4248                        return;
 4249                    }
 4250                    ControlFlow::Break(None) => return,
 4251                    ControlFlow::Continue(()) => (InvalidationStrategy::RefreshRequested, None),
 4252                }
 4253            }
 4254            InlayHintRefreshReason::ExcerptsRemoved(excerpts_removed) => {
 4255                if let Some(InlaySplice {
 4256                    to_remove,
 4257                    to_insert,
 4258                }) = self.inlay_hint_cache.remove_excerpts(&excerpts_removed)
 4259                {
 4260                    self.splice_inlays(&to_remove, to_insert, cx);
 4261                }
 4262                self.display_map.update(cx, |display_map, _| {
 4263                    display_map.remove_inlays_for_excerpts(&excerpts_removed)
 4264                });
 4265                return;
 4266            }
 4267            InlayHintRefreshReason::NewLinesShown => (InvalidationStrategy::None, None),
 4268            InlayHintRefreshReason::BufferEdited(buffer_languages) => {
 4269                (InvalidationStrategy::BufferEdited, Some(buffer_languages))
 4270            }
 4271            InlayHintRefreshReason::RefreshRequested => {
 4272                (InvalidationStrategy::RefreshRequested, None)
 4273            }
 4274        };
 4275
 4276        if let Some(InlaySplice {
 4277            to_remove,
 4278            to_insert,
 4279        }) = self.inlay_hint_cache.spawn_hint_refresh(
 4280            reason_description,
 4281            self.excerpts_for_inlay_hints_query(required_languages.as_ref(), cx),
 4282            invalidate_cache,
 4283            ignore_debounce,
 4284            cx,
 4285        ) {
 4286            self.splice_inlays(&to_remove, to_insert, cx);
 4287        }
 4288    }
 4289
 4290    fn visible_inlay_hints(&self, cx: &Context<Editor>) -> Vec<Inlay> {
 4291        self.display_map
 4292            .read(cx)
 4293            .current_inlays()
 4294            .filter(move |inlay| matches!(inlay.id, InlayId::Hint(_)))
 4295            .cloned()
 4296            .collect()
 4297    }
 4298
 4299    pub fn excerpts_for_inlay_hints_query(
 4300        &self,
 4301        restrict_to_languages: Option<&HashSet<Arc<Language>>>,
 4302        cx: &mut Context<Editor>,
 4303    ) -> HashMap<ExcerptId, (Entity<Buffer>, clock::Global, Range<usize>)> {
 4304        let Some(project) = self.project.as_ref() else {
 4305            return HashMap::default();
 4306        };
 4307        let project = project.read(cx);
 4308        let multi_buffer = self.buffer().read(cx);
 4309        let multi_buffer_snapshot = multi_buffer.snapshot(cx);
 4310        let multi_buffer_visible_start = self
 4311            .scroll_manager
 4312            .anchor()
 4313            .anchor
 4314            .to_point(&multi_buffer_snapshot);
 4315        let multi_buffer_visible_end = multi_buffer_snapshot.clip_point(
 4316            multi_buffer_visible_start
 4317                + Point::new(self.visible_line_count().unwrap_or(0.).ceil() as u32, 0),
 4318            Bias::Left,
 4319        );
 4320        let multi_buffer_visible_range = multi_buffer_visible_start..multi_buffer_visible_end;
 4321        multi_buffer_snapshot
 4322            .range_to_buffer_ranges(multi_buffer_visible_range)
 4323            .into_iter()
 4324            .filter(|(_, excerpt_visible_range, _)| !excerpt_visible_range.is_empty())
 4325            .filter_map(|(buffer, excerpt_visible_range, excerpt_id)| {
 4326                let buffer_file = project::File::from_dyn(buffer.file())?;
 4327                let buffer_worktree = project.worktree_for_id(buffer_file.worktree_id(cx), cx)?;
 4328                let worktree_entry = buffer_worktree
 4329                    .read(cx)
 4330                    .entry_for_id(buffer_file.project_entry_id(cx)?)?;
 4331                if worktree_entry.is_ignored {
 4332                    return None;
 4333                }
 4334
 4335                let language = buffer.language()?;
 4336                if let Some(restrict_to_languages) = restrict_to_languages {
 4337                    if !restrict_to_languages.contains(language) {
 4338                        return None;
 4339                    }
 4340                }
 4341                Some((
 4342                    excerpt_id,
 4343                    (
 4344                        multi_buffer.buffer(buffer.remote_id()).unwrap(),
 4345                        buffer.version().clone(),
 4346                        excerpt_visible_range,
 4347                    ),
 4348                ))
 4349            })
 4350            .collect()
 4351    }
 4352
 4353    pub fn text_layout_details(&self, window: &mut Window) -> TextLayoutDetails {
 4354        TextLayoutDetails {
 4355            text_system: window.text_system().clone(),
 4356            editor_style: self.style.clone().unwrap(),
 4357            rem_size: window.rem_size(),
 4358            scroll_anchor: self.scroll_manager.anchor(),
 4359            visible_rows: self.visible_line_count(),
 4360            vertical_scroll_margin: self.scroll_manager.vertical_scroll_margin,
 4361        }
 4362    }
 4363
 4364    pub fn splice_inlays(
 4365        &self,
 4366        to_remove: &[InlayId],
 4367        to_insert: Vec<Inlay>,
 4368        cx: &mut Context<Self>,
 4369    ) {
 4370        self.display_map.update(cx, |display_map, cx| {
 4371            display_map.splice_inlays(to_remove, to_insert, cx)
 4372        });
 4373        cx.notify();
 4374    }
 4375
 4376    fn trigger_on_type_formatting(
 4377        &self,
 4378        input: String,
 4379        window: &mut Window,
 4380        cx: &mut Context<Self>,
 4381    ) -> Option<Task<Result<()>>> {
 4382        if input.len() != 1 {
 4383            return None;
 4384        }
 4385
 4386        let project = self.project.as_ref()?;
 4387        let position = self.selections.newest_anchor().head();
 4388        let (buffer, buffer_position) = self
 4389            .buffer
 4390            .read(cx)
 4391            .text_anchor_for_position(position, cx)?;
 4392
 4393        let settings = language_settings::language_settings(
 4394            buffer
 4395                .read(cx)
 4396                .language_at(buffer_position)
 4397                .map(|l| l.name()),
 4398            buffer.read(cx).file(),
 4399            cx,
 4400        );
 4401        if !settings.use_on_type_format {
 4402            return None;
 4403        }
 4404
 4405        // OnTypeFormatting returns a list of edits, no need to pass them between Zed instances,
 4406        // hence we do LSP request & edit on host side only — add formats to host's history.
 4407        let push_to_lsp_host_history = true;
 4408        // If this is not the host, append its history with new edits.
 4409        let push_to_client_history = project.read(cx).is_via_collab();
 4410
 4411        let on_type_formatting = project.update(cx, |project, cx| {
 4412            project.on_type_format(
 4413                buffer.clone(),
 4414                buffer_position,
 4415                input,
 4416                push_to_lsp_host_history,
 4417                cx,
 4418            )
 4419        });
 4420        Some(cx.spawn_in(window, async move |editor, cx| {
 4421            if let Some(transaction) = on_type_formatting.await? {
 4422                if push_to_client_history {
 4423                    buffer
 4424                        .update(cx, |buffer, _| {
 4425                            buffer.push_transaction(transaction, Instant::now());
 4426                            buffer.finalize_last_transaction();
 4427                        })
 4428                        .ok();
 4429                }
 4430                editor.update(cx, |editor, cx| {
 4431                    editor.refresh_document_highlights(cx);
 4432                })?;
 4433            }
 4434            Ok(())
 4435        }))
 4436    }
 4437
 4438    pub fn show_word_completions(
 4439        &mut self,
 4440        _: &ShowWordCompletions,
 4441        window: &mut Window,
 4442        cx: &mut Context<Self>,
 4443    ) {
 4444        self.open_completions_menu(true, None, window, cx);
 4445    }
 4446
 4447    pub fn show_completions(
 4448        &mut self,
 4449        options: &ShowCompletions,
 4450        window: &mut Window,
 4451        cx: &mut Context<Self>,
 4452    ) {
 4453        self.open_completions_menu(false, options.trigger.as_deref(), window, cx);
 4454    }
 4455
 4456    fn open_completions_menu(
 4457        &mut self,
 4458        ignore_completion_provider: bool,
 4459        trigger: Option<&str>,
 4460        window: &mut Window,
 4461        cx: &mut Context<Self>,
 4462    ) {
 4463        if self.pending_rename.is_some() {
 4464            return;
 4465        }
 4466        if !self.snippet_stack.is_empty() && self.context_menu.borrow().as_ref().is_some() {
 4467            return;
 4468        }
 4469
 4470        let position = self.selections.newest_anchor().head();
 4471        if position.diff_base_anchor.is_some() {
 4472            return;
 4473        }
 4474        let (buffer, buffer_position) =
 4475            if let Some(output) = self.buffer.read(cx).text_anchor_for_position(position, cx) {
 4476                output
 4477            } else {
 4478                return;
 4479            };
 4480        let buffer_snapshot = buffer.read(cx).snapshot();
 4481        let show_completion_documentation = buffer_snapshot
 4482            .settings_at(buffer_position, cx)
 4483            .show_completion_documentation;
 4484
 4485        let query = Self::completion_query(&self.buffer.read(cx).read(cx), position);
 4486
 4487        let trigger_kind = match trigger {
 4488            Some(trigger) if buffer.read(cx).completion_triggers().contains(trigger) => {
 4489                CompletionTriggerKind::TRIGGER_CHARACTER
 4490            }
 4491            _ => CompletionTriggerKind::INVOKED,
 4492        };
 4493        let completion_context = CompletionContext {
 4494            trigger_character: trigger.and_then(|trigger| {
 4495                if trigger_kind == CompletionTriggerKind::TRIGGER_CHARACTER {
 4496                    Some(String::from(trigger))
 4497                } else {
 4498                    None
 4499                }
 4500            }),
 4501            trigger_kind,
 4502        };
 4503
 4504        let (old_range, word_kind) = buffer_snapshot.surrounding_word(buffer_position);
 4505        let (old_range, word_to_exclude) = if word_kind == Some(CharKind::Word) {
 4506            let word_to_exclude = buffer_snapshot
 4507                .text_for_range(old_range.clone())
 4508                .collect::<String>();
 4509            (
 4510                buffer_snapshot.anchor_before(old_range.start)
 4511                    ..buffer_snapshot.anchor_after(old_range.end),
 4512                Some(word_to_exclude),
 4513            )
 4514        } else {
 4515            (buffer_position..buffer_position, None)
 4516        };
 4517
 4518        let completion_settings = language_settings(
 4519            buffer_snapshot
 4520                .language_at(buffer_position)
 4521                .map(|language| language.name()),
 4522            buffer_snapshot.file(),
 4523            cx,
 4524        )
 4525        .completions;
 4526
 4527        // The document can be large, so stay in reasonable bounds when searching for words,
 4528        // otherwise completion pop-up might be slow to appear.
 4529        const WORD_LOOKUP_ROWS: u32 = 5_000;
 4530        let buffer_row = text::ToPoint::to_point(&buffer_position, &buffer_snapshot).row;
 4531        let min_word_search = buffer_snapshot.clip_point(
 4532            Point::new(buffer_row.saturating_sub(WORD_LOOKUP_ROWS), 0),
 4533            Bias::Left,
 4534        );
 4535        let max_word_search = buffer_snapshot.clip_point(
 4536            Point::new(buffer_row + WORD_LOOKUP_ROWS, 0).min(buffer_snapshot.max_point()),
 4537            Bias::Right,
 4538        );
 4539        let word_search_range = buffer_snapshot.point_to_offset(min_word_search)
 4540            ..buffer_snapshot.point_to_offset(max_word_search);
 4541
 4542        let provider = self
 4543            .completion_provider
 4544            .as_ref()
 4545            .filter(|_| !ignore_completion_provider);
 4546        let skip_digits = query
 4547            .as_ref()
 4548            .map_or(true, |query| !query.chars().any(|c| c.is_digit(10)));
 4549
 4550        let (mut words, provided_completions) = match provider {
 4551            Some(provider) => {
 4552                let completions = provider.completions(
 4553                    position.excerpt_id,
 4554                    &buffer,
 4555                    buffer_position,
 4556                    completion_context,
 4557                    window,
 4558                    cx,
 4559                );
 4560
 4561                let words = match completion_settings.words {
 4562                    WordsCompletionMode::Disabled => Task::ready(BTreeMap::default()),
 4563                    WordsCompletionMode::Enabled | WordsCompletionMode::Fallback => cx
 4564                        .background_spawn(async move {
 4565                            buffer_snapshot.words_in_range(WordsQuery {
 4566                                fuzzy_contents: None,
 4567                                range: word_search_range,
 4568                                skip_digits,
 4569                            })
 4570                        }),
 4571                };
 4572
 4573                (words, completions)
 4574            }
 4575            None => (
 4576                cx.background_spawn(async move {
 4577                    buffer_snapshot.words_in_range(WordsQuery {
 4578                        fuzzy_contents: None,
 4579                        range: word_search_range,
 4580                        skip_digits,
 4581                    })
 4582                }),
 4583                Task::ready(Ok(None)),
 4584            ),
 4585        };
 4586
 4587        let sort_completions = provider
 4588            .as_ref()
 4589            .map_or(false, |provider| provider.sort_completions());
 4590
 4591        let filter_completions = provider
 4592            .as_ref()
 4593            .map_or(true, |provider| provider.filter_completions());
 4594
 4595        let id = post_inc(&mut self.next_completion_id);
 4596        let task = cx.spawn_in(window, async move |editor, cx| {
 4597            async move {
 4598                editor.update(cx, |this, _| {
 4599                    this.completion_tasks.retain(|(task_id, _)| *task_id >= id);
 4600                })?;
 4601
 4602                let mut completions = Vec::new();
 4603                if let Some(provided_completions) = provided_completions.await.log_err().flatten() {
 4604                    completions.extend(provided_completions);
 4605                    if completion_settings.words == WordsCompletionMode::Fallback {
 4606                        words = Task::ready(BTreeMap::default());
 4607                    }
 4608                }
 4609
 4610                let mut words = words.await;
 4611                if let Some(word_to_exclude) = &word_to_exclude {
 4612                    words.remove(word_to_exclude);
 4613                }
 4614                for lsp_completion in &completions {
 4615                    words.remove(&lsp_completion.new_text);
 4616                }
 4617                completions.extend(words.into_iter().map(|(word, word_range)| Completion {
 4618                    replace_range: old_range.clone(),
 4619                    new_text: word.clone(),
 4620                    label: CodeLabel::plain(word, None),
 4621                    icon_path: None,
 4622                    documentation: None,
 4623                    source: CompletionSource::BufferWord {
 4624                        word_range,
 4625                        resolved: false,
 4626                    },
 4627                    insert_text_mode: Some(InsertTextMode::AS_IS),
 4628                    confirm: None,
 4629                }));
 4630
 4631                let menu = if completions.is_empty() {
 4632                    None
 4633                } else {
 4634                    let mut menu = CompletionsMenu::new(
 4635                        id,
 4636                        sort_completions,
 4637                        show_completion_documentation,
 4638                        ignore_completion_provider,
 4639                        position,
 4640                        buffer.clone(),
 4641                        completions.into(),
 4642                    );
 4643
 4644                    menu.filter(
 4645                        if filter_completions {
 4646                            query.as_deref()
 4647                        } else {
 4648                            None
 4649                        },
 4650                        cx.background_executor().clone(),
 4651                    )
 4652                    .await;
 4653
 4654                    menu.visible().then_some(menu)
 4655                };
 4656
 4657                editor.update_in(cx, |editor, window, cx| {
 4658                    match editor.context_menu.borrow().as_ref() {
 4659                        None => {}
 4660                        Some(CodeContextMenu::Completions(prev_menu)) => {
 4661                            if prev_menu.id > id {
 4662                                return;
 4663                            }
 4664                        }
 4665                        _ => return,
 4666                    }
 4667
 4668                    if editor.focus_handle.is_focused(window) && menu.is_some() {
 4669                        let mut menu = menu.unwrap();
 4670                        menu.resolve_visible_completions(editor.completion_provider.as_deref(), cx);
 4671
 4672                        *editor.context_menu.borrow_mut() =
 4673                            Some(CodeContextMenu::Completions(menu));
 4674
 4675                        if editor.show_edit_predictions_in_menu() {
 4676                            editor.update_visible_inline_completion(window, cx);
 4677                        } else {
 4678                            editor.discard_inline_completion(false, cx);
 4679                        }
 4680
 4681                        cx.notify();
 4682                    } else if editor.completion_tasks.len() <= 1 {
 4683                        // If there are no more completion tasks and the last menu was
 4684                        // empty, we should hide it.
 4685                        let was_hidden = editor.hide_context_menu(window, cx).is_none();
 4686                        // If it was already hidden and we don't show inline
 4687                        // completions in the menu, we should also show the
 4688                        // inline-completion when available.
 4689                        if was_hidden && editor.show_edit_predictions_in_menu() {
 4690                            editor.update_visible_inline_completion(window, cx);
 4691                        }
 4692                    }
 4693                })?;
 4694
 4695                anyhow::Ok(())
 4696            }
 4697            .log_err()
 4698            .await
 4699        });
 4700
 4701        self.completion_tasks.push((id, task));
 4702    }
 4703
 4704    #[cfg(feature = "test-support")]
 4705    pub fn current_completions(&self) -> Option<Vec<project::Completion>> {
 4706        let menu = self.context_menu.borrow();
 4707        if let CodeContextMenu::Completions(menu) = menu.as_ref()? {
 4708            let completions = menu.completions.borrow();
 4709            Some(completions.to_vec())
 4710        } else {
 4711            None
 4712        }
 4713    }
 4714
 4715    pub fn confirm_completion(
 4716        &mut self,
 4717        action: &ConfirmCompletion,
 4718        window: &mut Window,
 4719        cx: &mut Context<Self>,
 4720    ) -> Option<Task<Result<()>>> {
 4721        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
 4722        self.do_completion(action.item_ix, CompletionIntent::Complete, window, cx)
 4723    }
 4724
 4725    pub fn confirm_completion_insert(
 4726        &mut self,
 4727        _: &ConfirmCompletionInsert,
 4728        window: &mut Window,
 4729        cx: &mut Context<Self>,
 4730    ) -> Option<Task<Result<()>>> {
 4731        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
 4732        self.do_completion(None, CompletionIntent::CompleteWithInsert, window, cx)
 4733    }
 4734
 4735    pub fn confirm_completion_replace(
 4736        &mut self,
 4737        _: &ConfirmCompletionReplace,
 4738        window: &mut Window,
 4739        cx: &mut Context<Self>,
 4740    ) -> Option<Task<Result<()>>> {
 4741        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
 4742        self.do_completion(None, CompletionIntent::CompleteWithReplace, window, cx)
 4743    }
 4744
 4745    pub fn compose_completion(
 4746        &mut self,
 4747        action: &ComposeCompletion,
 4748        window: &mut Window,
 4749        cx: &mut Context<Self>,
 4750    ) -> Option<Task<Result<()>>> {
 4751        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
 4752        self.do_completion(action.item_ix, CompletionIntent::Compose, window, cx)
 4753    }
 4754
 4755    fn do_completion(
 4756        &mut self,
 4757        item_ix: Option<usize>,
 4758        intent: CompletionIntent,
 4759        window: &mut Window,
 4760        cx: &mut Context<Editor>,
 4761    ) -> Option<Task<Result<()>>> {
 4762        use language::ToOffset as _;
 4763
 4764        let CodeContextMenu::Completions(completions_menu) = self.hide_context_menu(window, cx)?
 4765        else {
 4766            return None;
 4767        };
 4768
 4769        let candidate_id = {
 4770            let entries = completions_menu.entries.borrow();
 4771            let mat = entries.get(item_ix.unwrap_or(completions_menu.selected_item))?;
 4772            if self.show_edit_predictions_in_menu() {
 4773                self.discard_inline_completion(true, cx);
 4774            }
 4775            mat.candidate_id
 4776        };
 4777
 4778        let buffer_handle = completions_menu.buffer;
 4779        let completion = completions_menu
 4780            .completions
 4781            .borrow()
 4782            .get(candidate_id)?
 4783            .clone();
 4784        cx.stop_propagation();
 4785
 4786        let snippet;
 4787        let new_text;
 4788        if completion.is_snippet() {
 4789            snippet = Some(Snippet::parse(&completion.new_text).log_err()?);
 4790            new_text = snippet.as_ref().unwrap().text.clone();
 4791        } else {
 4792            snippet = None;
 4793            new_text = completion.new_text.clone();
 4794        };
 4795
 4796        let replace_range = choose_completion_range(&completion, intent, &buffer_handle, cx);
 4797        let buffer = buffer_handle.read(cx);
 4798        let snapshot = self.buffer.read(cx).snapshot(cx);
 4799        let replace_range_multibuffer = {
 4800            let excerpt = snapshot
 4801                .excerpt_containing(self.selections.newest_anchor().range())
 4802                .unwrap();
 4803            let multibuffer_anchor = snapshot
 4804                .anchor_in_excerpt(excerpt.id(), buffer.anchor_before(replace_range.start))
 4805                .unwrap()
 4806                ..snapshot
 4807                    .anchor_in_excerpt(excerpt.id(), buffer.anchor_before(replace_range.end))
 4808                    .unwrap();
 4809            multibuffer_anchor.start.to_offset(&snapshot)
 4810                ..multibuffer_anchor.end.to_offset(&snapshot)
 4811        };
 4812        let newest_anchor = self.selections.newest_anchor();
 4813        if newest_anchor.head().buffer_id != Some(buffer.remote_id()) {
 4814            return None;
 4815        }
 4816
 4817        let old_text = buffer
 4818            .text_for_range(replace_range.clone())
 4819            .collect::<String>();
 4820        let lookbehind = newest_anchor
 4821            .start
 4822            .text_anchor
 4823            .to_offset(buffer)
 4824            .saturating_sub(replace_range.start);
 4825        let lookahead = replace_range
 4826            .end
 4827            .saturating_sub(newest_anchor.end.text_anchor.to_offset(buffer));
 4828        let prefix = &old_text[..old_text.len().saturating_sub(lookahead)];
 4829        let suffix = &old_text[lookbehind.min(old_text.len())..];
 4830
 4831        let selections = self.selections.all::<usize>(cx);
 4832        let mut ranges = Vec::new();
 4833        let mut linked_edits = HashMap::<_, Vec<_>>::default();
 4834
 4835        for selection in &selections {
 4836            let range = if selection.id == newest_anchor.id {
 4837                replace_range_multibuffer.clone()
 4838            } else {
 4839                let mut range = selection.range();
 4840
 4841                // if prefix is present, don't duplicate it
 4842                if snapshot.contains_str_at(range.start.saturating_sub(lookbehind), prefix) {
 4843                    range.start = range.start.saturating_sub(lookbehind);
 4844
 4845                    // if suffix is also present, mimic the newest cursor and replace it
 4846                    if selection.id != newest_anchor.id
 4847                        && snapshot.contains_str_at(range.end, suffix)
 4848                    {
 4849                        range.end += lookahead;
 4850                    }
 4851                }
 4852                range
 4853            };
 4854
 4855            ranges.push(range);
 4856
 4857            if !self.linked_edit_ranges.is_empty() {
 4858                let start_anchor = snapshot.anchor_before(selection.head());
 4859                let end_anchor = snapshot.anchor_after(selection.tail());
 4860                if let Some(ranges) = self
 4861                    .linked_editing_ranges_for(start_anchor.text_anchor..end_anchor.text_anchor, cx)
 4862                {
 4863                    for (buffer, edits) in ranges {
 4864                        linked_edits
 4865                            .entry(buffer.clone())
 4866                            .or_default()
 4867                            .extend(edits.into_iter().map(|range| (range, new_text.to_owned())));
 4868                    }
 4869                }
 4870            }
 4871        }
 4872
 4873        cx.emit(EditorEvent::InputHandled {
 4874            utf16_range_to_replace: None,
 4875            text: new_text.clone().into(),
 4876        });
 4877
 4878        self.transact(window, cx, |this, window, cx| {
 4879            if let Some(mut snippet) = snippet {
 4880                snippet.text = new_text.to_string();
 4881                this.insert_snippet(&ranges, snippet, window, cx).log_err();
 4882            } else {
 4883                this.buffer.update(cx, |buffer, cx| {
 4884                    let auto_indent = match completion.insert_text_mode {
 4885                        Some(InsertTextMode::AS_IS) => None,
 4886                        _ => this.autoindent_mode.clone(),
 4887                    };
 4888                    let edits = ranges.into_iter().map(|range| (range, new_text.as_str()));
 4889                    buffer.edit(edits, auto_indent, cx);
 4890                });
 4891            }
 4892            for (buffer, edits) in linked_edits {
 4893                buffer.update(cx, |buffer, cx| {
 4894                    let snapshot = buffer.snapshot();
 4895                    let edits = edits
 4896                        .into_iter()
 4897                        .map(|(range, text)| {
 4898                            use text::ToPoint as TP;
 4899                            let end_point = TP::to_point(&range.end, &snapshot);
 4900                            let start_point = TP::to_point(&range.start, &snapshot);
 4901                            (start_point..end_point, text)
 4902                        })
 4903                        .sorted_by_key(|(range, _)| range.start);
 4904                    buffer.edit(edits, None, cx);
 4905                })
 4906            }
 4907
 4908            this.refresh_inline_completion(true, false, window, cx);
 4909        });
 4910
 4911        let show_new_completions_on_confirm = completion
 4912            .confirm
 4913            .as_ref()
 4914            .map_or(false, |confirm| confirm(intent, window, cx));
 4915        if show_new_completions_on_confirm {
 4916            self.show_completions(&ShowCompletions { trigger: None }, window, cx);
 4917        }
 4918
 4919        let provider = self.completion_provider.as_ref()?;
 4920        drop(completion);
 4921        let apply_edits = provider.apply_additional_edits_for_completion(
 4922            buffer_handle,
 4923            completions_menu.completions.clone(),
 4924            candidate_id,
 4925            true,
 4926            cx,
 4927        );
 4928
 4929        let editor_settings = EditorSettings::get_global(cx);
 4930        if editor_settings.show_signature_help_after_edits || editor_settings.auto_signature_help {
 4931            // After the code completion is finished, users often want to know what signatures are needed.
 4932            // so we should automatically call signature_help
 4933            self.show_signature_help(&ShowSignatureHelp, window, cx);
 4934        }
 4935
 4936        Some(cx.foreground_executor().spawn(async move {
 4937            apply_edits.await?;
 4938            Ok(())
 4939        }))
 4940    }
 4941
 4942    pub fn toggle_code_actions(
 4943        &mut self,
 4944        action: &ToggleCodeActions,
 4945        window: &mut Window,
 4946        cx: &mut Context<Self>,
 4947    ) {
 4948        let mut context_menu = self.context_menu.borrow_mut();
 4949        if let Some(CodeContextMenu::CodeActions(code_actions)) = context_menu.as_ref() {
 4950            if code_actions.deployed_from_indicator == action.deployed_from_indicator {
 4951                // Toggle if we're selecting the same one
 4952                *context_menu = None;
 4953                cx.notify();
 4954                return;
 4955            } else {
 4956                // Otherwise, clear it and start a new one
 4957                *context_menu = None;
 4958                cx.notify();
 4959            }
 4960        }
 4961        drop(context_menu);
 4962        let snapshot = self.snapshot(window, cx);
 4963        let deployed_from_indicator = action.deployed_from_indicator;
 4964        let mut task = self.code_actions_task.take();
 4965        let action = action.clone();
 4966        cx.spawn_in(window, async move |editor, cx| {
 4967            while let Some(prev_task) = task {
 4968                prev_task.await.log_err();
 4969                task = editor.update(cx, |this, _| this.code_actions_task.take())?;
 4970            }
 4971
 4972            let spawned_test_task = editor.update_in(cx, |editor, window, cx| {
 4973                if editor.focus_handle.is_focused(window) {
 4974                    let multibuffer_point = action
 4975                        .deployed_from_indicator
 4976                        .map(|row| DisplayPoint::new(row, 0).to_point(&snapshot))
 4977                        .unwrap_or_else(|| editor.selections.newest::<Point>(cx).head());
 4978                    let (buffer, buffer_row) = snapshot
 4979                        .buffer_snapshot
 4980                        .buffer_line_for_row(MultiBufferRow(multibuffer_point.row))
 4981                        .and_then(|(buffer_snapshot, range)| {
 4982                            editor
 4983                                .buffer
 4984                                .read(cx)
 4985                                .buffer(buffer_snapshot.remote_id())
 4986                                .map(|buffer| (buffer, range.start.row))
 4987                        })?;
 4988                    let (_, code_actions) = editor
 4989                        .available_code_actions
 4990                        .clone()
 4991                        .and_then(|(location, code_actions)| {
 4992                            let snapshot = location.buffer.read(cx).snapshot();
 4993                            let point_range = location.range.to_point(&snapshot);
 4994                            let point_range = point_range.start.row..=point_range.end.row;
 4995                            if point_range.contains(&buffer_row) {
 4996                                Some((location, code_actions))
 4997                            } else {
 4998                                None
 4999                            }
 5000                        })
 5001                        .unzip();
 5002                    let buffer_id = buffer.read(cx).remote_id();
 5003                    let tasks = editor
 5004                        .tasks
 5005                        .get(&(buffer_id, buffer_row))
 5006                        .map(|t| Arc::new(t.to_owned()));
 5007                    if tasks.is_none() && code_actions.is_none() {
 5008                        return None;
 5009                    }
 5010
 5011                    editor.completion_tasks.clear();
 5012                    editor.discard_inline_completion(false, cx);
 5013                    let task_context =
 5014                        tasks
 5015                            .as_ref()
 5016                            .zip(editor.project.clone())
 5017                            .map(|(tasks, project)| {
 5018                                Self::build_tasks_context(&project, &buffer, buffer_row, tasks, cx)
 5019                            });
 5020
 5021                    let debugger_flag = cx.has_flag::<Debugger>();
 5022
 5023                    Some(cx.spawn_in(window, async move |editor, cx| {
 5024                        let task_context = match task_context {
 5025                            Some(task_context) => task_context.await,
 5026                            None => None,
 5027                        };
 5028                        let resolved_tasks =
 5029                            tasks
 5030                                .zip(task_context)
 5031                                .map(|(tasks, task_context)| ResolvedTasks {
 5032                                    templates: tasks.resolve(&task_context).collect(),
 5033                                    position: snapshot.buffer_snapshot.anchor_before(Point::new(
 5034                                        multibuffer_point.row,
 5035                                        tasks.column,
 5036                                    )),
 5037                                });
 5038                        let spawn_straight_away = resolved_tasks.as_ref().map_or(false, |tasks| {
 5039                            tasks
 5040                                .templates
 5041                                .iter()
 5042                                .filter(|task| {
 5043                                    if matches!(task.1.task_type(), task::TaskType::Debug(_)) {
 5044                                        debugger_flag
 5045                                    } else {
 5046                                        true
 5047                                    }
 5048                                })
 5049                                .count()
 5050                                == 1
 5051                        }) && code_actions
 5052                            .as_ref()
 5053                            .map_or(true, |actions| actions.is_empty());
 5054                        if let Ok(task) = editor.update_in(cx, |editor, window, cx| {
 5055                            *editor.context_menu.borrow_mut() =
 5056                                Some(CodeContextMenu::CodeActions(CodeActionsMenu {
 5057                                    buffer,
 5058                                    actions: CodeActionContents::new(
 5059                                        resolved_tasks,
 5060                                        code_actions,
 5061                                        cx,
 5062                                    ),
 5063                                    selected_item: Default::default(),
 5064                                    scroll_handle: UniformListScrollHandle::default(),
 5065                                    deployed_from_indicator,
 5066                                }));
 5067                            if spawn_straight_away {
 5068                                if let Some(task) = editor.confirm_code_action(
 5069                                    &ConfirmCodeAction { item_ix: Some(0) },
 5070                                    window,
 5071                                    cx,
 5072                                ) {
 5073                                    cx.notify();
 5074                                    return task;
 5075                                }
 5076                            }
 5077                            cx.notify();
 5078                            Task::ready(Ok(()))
 5079                        }) {
 5080                            task.await
 5081                        } else {
 5082                            Ok(())
 5083                        }
 5084                    }))
 5085                } else {
 5086                    Some(Task::ready(Ok(())))
 5087                }
 5088            })?;
 5089            if let Some(task) = spawned_test_task {
 5090                task.await?;
 5091            }
 5092
 5093            Ok::<_, anyhow::Error>(())
 5094        })
 5095        .detach_and_log_err(cx);
 5096    }
 5097
 5098    pub fn confirm_code_action(
 5099        &mut self,
 5100        action: &ConfirmCodeAction,
 5101        window: &mut Window,
 5102        cx: &mut Context<Self>,
 5103    ) -> Option<Task<Result<()>>> {
 5104        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
 5105
 5106        let actions_menu =
 5107            if let CodeContextMenu::CodeActions(menu) = self.hide_context_menu(window, cx)? {
 5108                menu
 5109            } else {
 5110                return None;
 5111            };
 5112
 5113        let action_ix = action.item_ix.unwrap_or(actions_menu.selected_item);
 5114        let action = actions_menu.actions.get(action_ix)?;
 5115        let title = action.label();
 5116        let buffer = actions_menu.buffer;
 5117        let workspace = self.workspace()?;
 5118
 5119        match action {
 5120            CodeActionsItem::Task(task_source_kind, resolved_task) => {
 5121                match resolved_task.task_type() {
 5122                    task::TaskType::Script => workspace.update(cx, |workspace, cx| {
 5123                        workspace.schedule_resolved_task(
 5124                            task_source_kind,
 5125                            resolved_task,
 5126                            false,
 5127                            window,
 5128                            cx,
 5129                        );
 5130
 5131                        Some(Task::ready(Ok(())))
 5132                    }),
 5133                    task::TaskType::Debug(_) => {
 5134                        workspace.update(cx, |workspace, cx| {
 5135                            workspace.schedule_debug_task(resolved_task, window, cx);
 5136                        });
 5137                        Some(Task::ready(Ok(())))
 5138                    }
 5139                }
 5140            }
 5141            CodeActionsItem::CodeAction {
 5142                excerpt_id,
 5143                action,
 5144                provider,
 5145            } => {
 5146                let apply_code_action =
 5147                    provider.apply_code_action(buffer, action, excerpt_id, true, window, cx);
 5148                let workspace = workspace.downgrade();
 5149                Some(cx.spawn_in(window, async move |editor, cx| {
 5150                    let project_transaction = apply_code_action.await?;
 5151                    Self::open_project_transaction(
 5152                        &editor,
 5153                        workspace,
 5154                        project_transaction,
 5155                        title,
 5156                        cx,
 5157                    )
 5158                    .await
 5159                }))
 5160            }
 5161        }
 5162    }
 5163
 5164    pub async fn open_project_transaction(
 5165        this: &WeakEntity<Editor>,
 5166        workspace: WeakEntity<Workspace>,
 5167        transaction: ProjectTransaction,
 5168        title: String,
 5169        cx: &mut AsyncWindowContext,
 5170    ) -> Result<()> {
 5171        let mut entries = transaction.0.into_iter().collect::<Vec<_>>();
 5172        cx.update(|_, cx| {
 5173            entries.sort_unstable_by_key(|(buffer, _)| {
 5174                buffer.read(cx).file().map(|f| f.path().clone())
 5175            });
 5176        })?;
 5177
 5178        // If the project transaction's edits are all contained within this editor, then
 5179        // avoid opening a new editor to display them.
 5180
 5181        if let Some((buffer, transaction)) = entries.first() {
 5182            if entries.len() == 1 {
 5183                let excerpt = this.update(cx, |editor, cx| {
 5184                    editor
 5185                        .buffer()
 5186                        .read(cx)
 5187                        .excerpt_containing(editor.selections.newest_anchor().head(), cx)
 5188                })?;
 5189                if let Some((_, excerpted_buffer, excerpt_range)) = excerpt {
 5190                    if excerpted_buffer == *buffer {
 5191                        let all_edits_within_excerpt = buffer.read_with(cx, |buffer, _| {
 5192                            let excerpt_range = excerpt_range.to_offset(buffer);
 5193                            buffer
 5194                                .edited_ranges_for_transaction::<usize>(transaction)
 5195                                .all(|range| {
 5196                                    excerpt_range.start <= range.start
 5197                                        && excerpt_range.end >= range.end
 5198                                })
 5199                        })?;
 5200
 5201                        if all_edits_within_excerpt {
 5202                            return Ok(());
 5203                        }
 5204                    }
 5205                }
 5206            }
 5207        } else {
 5208            return Ok(());
 5209        }
 5210
 5211        let mut ranges_to_highlight = Vec::new();
 5212        let excerpt_buffer = cx.new(|cx| {
 5213            let mut multibuffer = MultiBuffer::new(Capability::ReadWrite).with_title(title);
 5214            for (buffer_handle, transaction) in &entries {
 5215                let edited_ranges = buffer_handle
 5216                    .read(cx)
 5217                    .edited_ranges_for_transaction::<Point>(transaction)
 5218                    .collect::<Vec<_>>();
 5219                let (ranges, _) = multibuffer.set_excerpts_for_path(
 5220                    PathKey::for_buffer(buffer_handle, cx),
 5221                    buffer_handle.clone(),
 5222                    edited_ranges,
 5223                    DEFAULT_MULTIBUFFER_CONTEXT,
 5224                    cx,
 5225                );
 5226
 5227                ranges_to_highlight.extend(ranges);
 5228            }
 5229            multibuffer.push_transaction(entries.iter().map(|(b, t)| (b, t)), cx);
 5230            multibuffer
 5231        })?;
 5232
 5233        workspace.update_in(cx, |workspace, window, cx| {
 5234            let project = workspace.project().clone();
 5235            let editor =
 5236                cx.new(|cx| Editor::for_multibuffer(excerpt_buffer, Some(project), window, cx));
 5237            workspace.add_item_to_active_pane(Box::new(editor.clone()), None, true, window, cx);
 5238            editor.update(cx, |editor, cx| {
 5239                editor.highlight_background::<Self>(
 5240                    &ranges_to_highlight,
 5241                    |theme| theme.editor_highlighted_line_background,
 5242                    cx,
 5243                );
 5244            });
 5245        })?;
 5246
 5247        Ok(())
 5248    }
 5249
 5250    pub fn clear_code_action_providers(&mut self) {
 5251        self.code_action_providers.clear();
 5252        self.available_code_actions.take();
 5253    }
 5254
 5255    pub fn add_code_action_provider(
 5256        &mut self,
 5257        provider: Rc<dyn CodeActionProvider>,
 5258        window: &mut Window,
 5259        cx: &mut Context<Self>,
 5260    ) {
 5261        if self
 5262            .code_action_providers
 5263            .iter()
 5264            .any(|existing_provider| existing_provider.id() == provider.id())
 5265        {
 5266            return;
 5267        }
 5268
 5269        self.code_action_providers.push(provider);
 5270        self.refresh_code_actions(window, cx);
 5271    }
 5272
 5273    pub fn remove_code_action_provider(
 5274        &mut self,
 5275        id: Arc<str>,
 5276        window: &mut Window,
 5277        cx: &mut Context<Self>,
 5278    ) {
 5279        self.code_action_providers
 5280            .retain(|provider| provider.id() != id);
 5281        self.refresh_code_actions(window, cx);
 5282    }
 5283
 5284    fn refresh_code_actions(&mut self, window: &mut Window, cx: &mut Context<Self>) -> Option<()> {
 5285        let newest_selection = self.selections.newest_anchor().clone();
 5286        let newest_selection_adjusted = self.selections.newest_adjusted(cx).clone();
 5287        let buffer = self.buffer.read(cx);
 5288        if newest_selection.head().diff_base_anchor.is_some() {
 5289            return None;
 5290        }
 5291        let (start_buffer, start) =
 5292            buffer.text_anchor_for_position(newest_selection_adjusted.start, cx)?;
 5293        let (end_buffer, end) =
 5294            buffer.text_anchor_for_position(newest_selection_adjusted.end, cx)?;
 5295        if start_buffer != end_buffer {
 5296            return None;
 5297        }
 5298
 5299        self.code_actions_task = Some(cx.spawn_in(window, async move |this, cx| {
 5300            cx.background_executor()
 5301                .timer(CODE_ACTIONS_DEBOUNCE_TIMEOUT)
 5302                .await;
 5303
 5304            let (providers, tasks) = this.update_in(cx, |this, window, cx| {
 5305                let providers = this.code_action_providers.clone();
 5306                let tasks = this
 5307                    .code_action_providers
 5308                    .iter()
 5309                    .map(|provider| provider.code_actions(&start_buffer, start..end, window, cx))
 5310                    .collect::<Vec<_>>();
 5311                (providers, tasks)
 5312            })?;
 5313
 5314            let mut actions = Vec::new();
 5315            for (provider, provider_actions) in
 5316                providers.into_iter().zip(future::join_all(tasks).await)
 5317            {
 5318                if let Some(provider_actions) = provider_actions.log_err() {
 5319                    actions.extend(provider_actions.into_iter().map(|action| {
 5320                        AvailableCodeAction {
 5321                            excerpt_id: newest_selection.start.excerpt_id,
 5322                            action,
 5323                            provider: provider.clone(),
 5324                        }
 5325                    }));
 5326                }
 5327            }
 5328
 5329            this.update(cx, |this, cx| {
 5330                this.available_code_actions = if actions.is_empty() {
 5331                    None
 5332                } else {
 5333                    Some((
 5334                        Location {
 5335                            buffer: start_buffer,
 5336                            range: start..end,
 5337                        },
 5338                        actions.into(),
 5339                    ))
 5340                };
 5341                cx.notify();
 5342            })
 5343        }));
 5344        None
 5345    }
 5346
 5347    fn start_inline_blame_timer(&mut self, window: &mut Window, cx: &mut Context<Self>) {
 5348        if let Some(delay) = ProjectSettings::get_global(cx).git.inline_blame_delay() {
 5349            self.show_git_blame_inline = false;
 5350
 5351            self.show_git_blame_inline_delay_task =
 5352                Some(cx.spawn_in(window, async move |this, cx| {
 5353                    cx.background_executor().timer(delay).await;
 5354
 5355                    this.update(cx, |this, cx| {
 5356                        this.show_git_blame_inline = true;
 5357                        cx.notify();
 5358                    })
 5359                    .log_err();
 5360                }));
 5361        }
 5362    }
 5363
 5364    fn refresh_document_highlights(&mut self, cx: &mut Context<Self>) -> Option<()> {
 5365        if self.pending_rename.is_some() {
 5366            return None;
 5367        }
 5368
 5369        let provider = self.semantics_provider.clone()?;
 5370        let buffer = self.buffer.read(cx);
 5371        let newest_selection = self.selections.newest_anchor().clone();
 5372        let cursor_position = newest_selection.head();
 5373        let (cursor_buffer, cursor_buffer_position) =
 5374            buffer.text_anchor_for_position(cursor_position, cx)?;
 5375        let (tail_buffer, _) = buffer.text_anchor_for_position(newest_selection.tail(), cx)?;
 5376        if cursor_buffer != tail_buffer {
 5377            return None;
 5378        }
 5379        let debounce = EditorSettings::get_global(cx).lsp_highlight_debounce;
 5380        self.document_highlights_task = Some(cx.spawn(async move |this, cx| {
 5381            cx.background_executor()
 5382                .timer(Duration::from_millis(debounce))
 5383                .await;
 5384
 5385            let highlights = if let Some(highlights) = cx
 5386                .update(|cx| {
 5387                    provider.document_highlights(&cursor_buffer, cursor_buffer_position, cx)
 5388                })
 5389                .ok()
 5390                .flatten()
 5391            {
 5392                highlights.await.log_err()
 5393            } else {
 5394                None
 5395            };
 5396
 5397            if let Some(highlights) = highlights {
 5398                this.update(cx, |this, cx| {
 5399                    if this.pending_rename.is_some() {
 5400                        return;
 5401                    }
 5402
 5403                    let buffer_id = cursor_position.buffer_id;
 5404                    let buffer = this.buffer.read(cx);
 5405                    if !buffer
 5406                        .text_anchor_for_position(cursor_position, cx)
 5407                        .map_or(false, |(buffer, _)| buffer == cursor_buffer)
 5408                    {
 5409                        return;
 5410                    }
 5411
 5412                    let cursor_buffer_snapshot = cursor_buffer.read(cx);
 5413                    let mut write_ranges = Vec::new();
 5414                    let mut read_ranges = Vec::new();
 5415                    for highlight in highlights {
 5416                        for (excerpt_id, excerpt_range) in
 5417                            buffer.excerpts_for_buffer(cursor_buffer.read(cx).remote_id(), cx)
 5418                        {
 5419                            let start = highlight
 5420                                .range
 5421                                .start
 5422                                .max(&excerpt_range.context.start, cursor_buffer_snapshot);
 5423                            let end = highlight
 5424                                .range
 5425                                .end
 5426                                .min(&excerpt_range.context.end, cursor_buffer_snapshot);
 5427                            if start.cmp(&end, cursor_buffer_snapshot).is_ge() {
 5428                                continue;
 5429                            }
 5430
 5431                            let range = Anchor {
 5432                                buffer_id,
 5433                                excerpt_id,
 5434                                text_anchor: start,
 5435                                diff_base_anchor: None,
 5436                            }..Anchor {
 5437                                buffer_id,
 5438                                excerpt_id,
 5439                                text_anchor: end,
 5440                                diff_base_anchor: None,
 5441                            };
 5442                            if highlight.kind == lsp::DocumentHighlightKind::WRITE {
 5443                                write_ranges.push(range);
 5444                            } else {
 5445                                read_ranges.push(range);
 5446                            }
 5447                        }
 5448                    }
 5449
 5450                    this.highlight_background::<DocumentHighlightRead>(
 5451                        &read_ranges,
 5452                        |theme| theme.editor_document_highlight_read_background,
 5453                        cx,
 5454                    );
 5455                    this.highlight_background::<DocumentHighlightWrite>(
 5456                        &write_ranges,
 5457                        |theme| theme.editor_document_highlight_write_background,
 5458                        cx,
 5459                    );
 5460                    cx.notify();
 5461                })
 5462                .log_err();
 5463            }
 5464        }));
 5465        None
 5466    }
 5467
 5468    fn prepare_highlight_query_from_selection(
 5469        &mut self,
 5470        cx: &mut Context<Editor>,
 5471    ) -> Option<(String, Range<Anchor>)> {
 5472        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 5473            return None;
 5474        }
 5475        if !EditorSettings::get_global(cx).selection_highlight {
 5476            return None;
 5477        }
 5478        if self.selections.count() != 1 || self.selections.line_mode {
 5479            return None;
 5480        }
 5481        let selection = self.selections.newest::<Point>(cx);
 5482        if selection.is_empty() || selection.start.row != selection.end.row {
 5483            return None;
 5484        }
 5485        let multi_buffer_snapshot = self.buffer().read(cx).snapshot(cx);
 5486        let selection_anchor_range = selection.range().to_anchors(&multi_buffer_snapshot);
 5487        let query = multi_buffer_snapshot
 5488            .text_for_range(selection_anchor_range.clone())
 5489            .collect::<String>();
 5490        if query.trim().is_empty() {
 5491            return None;
 5492        }
 5493        Some((query, selection_anchor_range))
 5494    }
 5495
 5496    fn update_selection_occurrence_highlights(
 5497        &mut self,
 5498        query_text: String,
 5499        query_range: Range<Anchor>,
 5500        multi_buffer_range_to_query: Range<Point>,
 5501        use_debounce: bool,
 5502        window: &mut Window,
 5503        cx: &mut Context<Editor>,
 5504    ) -> Task<()> {
 5505        let multi_buffer_snapshot = self.buffer().read(cx).snapshot(cx);
 5506        cx.spawn_in(window, async move |editor, cx| {
 5507            if use_debounce {
 5508                cx.background_executor()
 5509                    .timer(SELECTION_HIGHLIGHT_DEBOUNCE_TIMEOUT)
 5510                    .await;
 5511            }
 5512            let match_task = cx.background_spawn(async move {
 5513                let buffer_ranges = multi_buffer_snapshot
 5514                    .range_to_buffer_ranges(multi_buffer_range_to_query)
 5515                    .into_iter()
 5516                    .filter(|(_, excerpt_visible_range, _)| !excerpt_visible_range.is_empty());
 5517                let mut match_ranges = Vec::new();
 5518                for (buffer_snapshot, search_range, excerpt_id) in buffer_ranges {
 5519                    match_ranges.extend(
 5520                        project::search::SearchQuery::text(
 5521                            query_text.clone(),
 5522                            false,
 5523                            false,
 5524                            false,
 5525                            Default::default(),
 5526                            Default::default(),
 5527                            false,
 5528                            None,
 5529                        )
 5530                        .unwrap()
 5531                        .search(&buffer_snapshot, Some(search_range.clone()))
 5532                        .await
 5533                        .into_iter()
 5534                        .filter_map(|match_range| {
 5535                            let match_start = buffer_snapshot
 5536                                .anchor_after(search_range.start + match_range.start);
 5537                            let match_end =
 5538                                buffer_snapshot.anchor_before(search_range.start + match_range.end);
 5539                            let match_anchor_range = Anchor::range_in_buffer(
 5540                                excerpt_id,
 5541                                buffer_snapshot.remote_id(),
 5542                                match_start..match_end,
 5543                            );
 5544                            (match_anchor_range != query_range).then_some(match_anchor_range)
 5545                        }),
 5546                    );
 5547                }
 5548                match_ranges
 5549            });
 5550            let match_ranges = match_task.await;
 5551            editor
 5552                .update_in(cx, |editor, _, cx| {
 5553                    editor.clear_background_highlights::<SelectedTextHighlight>(cx);
 5554                    if !match_ranges.is_empty() {
 5555                        editor.highlight_background::<SelectedTextHighlight>(
 5556                            &match_ranges,
 5557                            |theme| theme.editor_document_highlight_bracket_background,
 5558                            cx,
 5559                        )
 5560                    }
 5561                })
 5562                .log_err();
 5563        })
 5564    }
 5565
 5566    fn refresh_selected_text_highlights(&mut self, window: &mut Window, cx: &mut Context<Editor>) {
 5567        let Some((query_text, query_range)) = self.prepare_highlight_query_from_selection(cx)
 5568        else {
 5569            self.clear_background_highlights::<SelectedTextHighlight>(cx);
 5570            self.quick_selection_highlight_task.take();
 5571            self.debounced_selection_highlight_task.take();
 5572            return;
 5573        };
 5574        let multi_buffer_snapshot = self.buffer().read(cx).snapshot(cx);
 5575        if self
 5576            .quick_selection_highlight_task
 5577            .as_ref()
 5578            .map_or(true, |(prev_anchor_range, _)| {
 5579                prev_anchor_range != &query_range
 5580            })
 5581        {
 5582            let multi_buffer_visible_start = self
 5583                .scroll_manager
 5584                .anchor()
 5585                .anchor
 5586                .to_point(&multi_buffer_snapshot);
 5587            let multi_buffer_visible_end = multi_buffer_snapshot.clip_point(
 5588                multi_buffer_visible_start
 5589                    + Point::new(self.visible_line_count().unwrap_or(0.).ceil() as u32, 0),
 5590                Bias::Left,
 5591            );
 5592            let multi_buffer_visible_range = multi_buffer_visible_start..multi_buffer_visible_end;
 5593            self.quick_selection_highlight_task = Some((
 5594                query_range.clone(),
 5595                self.update_selection_occurrence_highlights(
 5596                    query_text.clone(),
 5597                    query_range.clone(),
 5598                    multi_buffer_visible_range,
 5599                    false,
 5600                    window,
 5601                    cx,
 5602                ),
 5603            ));
 5604        }
 5605        if self
 5606            .debounced_selection_highlight_task
 5607            .as_ref()
 5608            .map_or(true, |(prev_anchor_range, _)| {
 5609                prev_anchor_range != &query_range
 5610            })
 5611        {
 5612            let multi_buffer_start = multi_buffer_snapshot
 5613                .anchor_before(0)
 5614                .to_point(&multi_buffer_snapshot);
 5615            let multi_buffer_end = multi_buffer_snapshot
 5616                .anchor_after(multi_buffer_snapshot.len())
 5617                .to_point(&multi_buffer_snapshot);
 5618            let multi_buffer_full_range = multi_buffer_start..multi_buffer_end;
 5619            self.debounced_selection_highlight_task = Some((
 5620                query_range.clone(),
 5621                self.update_selection_occurrence_highlights(
 5622                    query_text,
 5623                    query_range,
 5624                    multi_buffer_full_range,
 5625                    true,
 5626                    window,
 5627                    cx,
 5628                ),
 5629            ));
 5630        }
 5631    }
 5632
 5633    pub fn refresh_inline_completion(
 5634        &mut self,
 5635        debounce: bool,
 5636        user_requested: bool,
 5637        window: &mut Window,
 5638        cx: &mut Context<Self>,
 5639    ) -> Option<()> {
 5640        let provider = self.edit_prediction_provider()?;
 5641        let cursor = self.selections.newest_anchor().head();
 5642        let (buffer, cursor_buffer_position) =
 5643            self.buffer.read(cx).text_anchor_for_position(cursor, cx)?;
 5644
 5645        if !self.edit_predictions_enabled_in_buffer(&buffer, cursor_buffer_position, cx) {
 5646            self.discard_inline_completion(false, cx);
 5647            return None;
 5648        }
 5649
 5650        if !user_requested
 5651            && (!self.should_show_edit_predictions()
 5652                || !self.is_focused(window)
 5653                || buffer.read(cx).is_empty())
 5654        {
 5655            self.discard_inline_completion(false, cx);
 5656            return None;
 5657        }
 5658
 5659        self.update_visible_inline_completion(window, cx);
 5660        provider.refresh(
 5661            self.project.clone(),
 5662            buffer,
 5663            cursor_buffer_position,
 5664            debounce,
 5665            cx,
 5666        );
 5667        Some(())
 5668    }
 5669
 5670    fn show_edit_predictions_in_menu(&self) -> bool {
 5671        match self.edit_prediction_settings {
 5672            EditPredictionSettings::Disabled => false,
 5673            EditPredictionSettings::Enabled { show_in_menu, .. } => show_in_menu,
 5674        }
 5675    }
 5676
 5677    pub fn edit_predictions_enabled(&self) -> bool {
 5678        match self.edit_prediction_settings {
 5679            EditPredictionSettings::Disabled => false,
 5680            EditPredictionSettings::Enabled { .. } => true,
 5681        }
 5682    }
 5683
 5684    fn edit_prediction_requires_modifier(&self) -> bool {
 5685        match self.edit_prediction_settings {
 5686            EditPredictionSettings::Disabled => false,
 5687            EditPredictionSettings::Enabled {
 5688                preview_requires_modifier,
 5689                ..
 5690            } => preview_requires_modifier,
 5691        }
 5692    }
 5693
 5694    pub fn update_edit_prediction_settings(&mut self, cx: &mut Context<Self>) {
 5695        if self.edit_prediction_provider.is_none() {
 5696            self.edit_prediction_settings = EditPredictionSettings::Disabled;
 5697        } else {
 5698            let selection = self.selections.newest_anchor();
 5699            let cursor = selection.head();
 5700
 5701            if let Some((buffer, cursor_buffer_position)) =
 5702                self.buffer.read(cx).text_anchor_for_position(cursor, cx)
 5703            {
 5704                self.edit_prediction_settings =
 5705                    self.edit_prediction_settings_at_position(&buffer, cursor_buffer_position, cx);
 5706            }
 5707        }
 5708    }
 5709
 5710    fn edit_prediction_settings_at_position(
 5711        &self,
 5712        buffer: &Entity<Buffer>,
 5713        buffer_position: language::Anchor,
 5714        cx: &App,
 5715    ) -> EditPredictionSettings {
 5716        if !self.mode.is_full()
 5717            || !self.show_inline_completions_override.unwrap_or(true)
 5718            || self.inline_completions_disabled_in_scope(buffer, buffer_position, cx)
 5719        {
 5720            return EditPredictionSettings::Disabled;
 5721        }
 5722
 5723        let buffer = buffer.read(cx);
 5724
 5725        let file = buffer.file();
 5726
 5727        if !language_settings(buffer.language().map(|l| l.name()), file, cx).show_edit_predictions {
 5728            return EditPredictionSettings::Disabled;
 5729        };
 5730
 5731        let by_provider = matches!(
 5732            self.menu_inline_completions_policy,
 5733            MenuInlineCompletionsPolicy::ByProvider
 5734        );
 5735
 5736        let show_in_menu = by_provider
 5737            && self
 5738                .edit_prediction_provider
 5739                .as_ref()
 5740                .map_or(false, |provider| {
 5741                    provider.provider.show_completions_in_menu()
 5742                });
 5743
 5744        let preview_requires_modifier =
 5745            all_language_settings(file, cx).edit_predictions_mode() == EditPredictionsMode::Subtle;
 5746
 5747        EditPredictionSettings::Enabled {
 5748            show_in_menu,
 5749            preview_requires_modifier,
 5750        }
 5751    }
 5752
 5753    fn should_show_edit_predictions(&self) -> bool {
 5754        self.snippet_stack.is_empty() && self.edit_predictions_enabled()
 5755    }
 5756
 5757    pub fn edit_prediction_preview_is_active(&self) -> bool {
 5758        matches!(
 5759            self.edit_prediction_preview,
 5760            EditPredictionPreview::Active { .. }
 5761        )
 5762    }
 5763
 5764    pub fn edit_predictions_enabled_at_cursor(&self, cx: &App) -> bool {
 5765        let cursor = self.selections.newest_anchor().head();
 5766        if let Some((buffer, cursor_position)) =
 5767            self.buffer.read(cx).text_anchor_for_position(cursor, cx)
 5768        {
 5769            self.edit_predictions_enabled_in_buffer(&buffer, cursor_position, cx)
 5770        } else {
 5771            false
 5772        }
 5773    }
 5774
 5775    fn edit_predictions_enabled_in_buffer(
 5776        &self,
 5777        buffer: &Entity<Buffer>,
 5778        buffer_position: language::Anchor,
 5779        cx: &App,
 5780    ) -> bool {
 5781        maybe!({
 5782            if self.read_only(cx) {
 5783                return Some(false);
 5784            }
 5785            let provider = self.edit_prediction_provider()?;
 5786            if !provider.is_enabled(&buffer, buffer_position, cx) {
 5787                return Some(false);
 5788            }
 5789            let buffer = buffer.read(cx);
 5790            let Some(file) = buffer.file() else {
 5791                return Some(true);
 5792            };
 5793            let settings = all_language_settings(Some(file), cx);
 5794            Some(settings.edit_predictions_enabled_for_file(file, cx))
 5795        })
 5796        .unwrap_or(false)
 5797    }
 5798
 5799    fn cycle_inline_completion(
 5800        &mut self,
 5801        direction: Direction,
 5802        window: &mut Window,
 5803        cx: &mut Context<Self>,
 5804    ) -> Option<()> {
 5805        let provider = self.edit_prediction_provider()?;
 5806        let cursor = self.selections.newest_anchor().head();
 5807        let (buffer, cursor_buffer_position) =
 5808            self.buffer.read(cx).text_anchor_for_position(cursor, cx)?;
 5809        if self.inline_completions_hidden_for_vim_mode || !self.should_show_edit_predictions() {
 5810            return None;
 5811        }
 5812
 5813        provider.cycle(buffer, cursor_buffer_position, direction, cx);
 5814        self.update_visible_inline_completion(window, cx);
 5815
 5816        Some(())
 5817    }
 5818
 5819    pub fn show_inline_completion(
 5820        &mut self,
 5821        _: &ShowEditPrediction,
 5822        window: &mut Window,
 5823        cx: &mut Context<Self>,
 5824    ) {
 5825        if !self.has_active_inline_completion() {
 5826            self.refresh_inline_completion(false, true, window, cx);
 5827            return;
 5828        }
 5829
 5830        self.update_visible_inline_completion(window, cx);
 5831    }
 5832
 5833    pub fn display_cursor_names(
 5834        &mut self,
 5835        _: &DisplayCursorNames,
 5836        window: &mut Window,
 5837        cx: &mut Context<Self>,
 5838    ) {
 5839        self.show_cursor_names(window, cx);
 5840    }
 5841
 5842    fn show_cursor_names(&mut self, window: &mut Window, cx: &mut Context<Self>) {
 5843        self.show_cursor_names = true;
 5844        cx.notify();
 5845        cx.spawn_in(window, async move |this, cx| {
 5846            cx.background_executor().timer(CURSORS_VISIBLE_FOR).await;
 5847            this.update(cx, |this, cx| {
 5848                this.show_cursor_names = false;
 5849                cx.notify()
 5850            })
 5851            .ok()
 5852        })
 5853        .detach();
 5854    }
 5855
 5856    pub fn next_edit_prediction(
 5857        &mut self,
 5858        _: &NextEditPrediction,
 5859        window: &mut Window,
 5860        cx: &mut Context<Self>,
 5861    ) {
 5862        if self.has_active_inline_completion() {
 5863            self.cycle_inline_completion(Direction::Next, window, cx);
 5864        } else {
 5865            let is_copilot_disabled = self
 5866                .refresh_inline_completion(false, true, window, cx)
 5867                .is_none();
 5868            if is_copilot_disabled {
 5869                cx.propagate();
 5870            }
 5871        }
 5872    }
 5873
 5874    pub fn previous_edit_prediction(
 5875        &mut self,
 5876        _: &PreviousEditPrediction,
 5877        window: &mut Window,
 5878        cx: &mut Context<Self>,
 5879    ) {
 5880        if self.has_active_inline_completion() {
 5881            self.cycle_inline_completion(Direction::Prev, window, cx);
 5882        } else {
 5883            let is_copilot_disabled = self
 5884                .refresh_inline_completion(false, true, window, cx)
 5885                .is_none();
 5886            if is_copilot_disabled {
 5887                cx.propagate();
 5888            }
 5889        }
 5890    }
 5891
 5892    pub fn accept_edit_prediction(
 5893        &mut self,
 5894        _: &AcceptEditPrediction,
 5895        window: &mut Window,
 5896        cx: &mut Context<Self>,
 5897    ) {
 5898        if self.show_edit_predictions_in_menu() {
 5899            self.hide_context_menu(window, cx);
 5900        }
 5901
 5902        let Some(active_inline_completion) = self.active_inline_completion.as_ref() else {
 5903            return;
 5904        };
 5905
 5906        self.report_inline_completion_event(
 5907            active_inline_completion.completion_id.clone(),
 5908            true,
 5909            cx,
 5910        );
 5911
 5912        match &active_inline_completion.completion {
 5913            InlineCompletion::Move { target, .. } => {
 5914                let target = *target;
 5915
 5916                if let Some(position_map) = &self.last_position_map {
 5917                    if position_map
 5918                        .visible_row_range
 5919                        .contains(&target.to_display_point(&position_map.snapshot).row())
 5920                        || !self.edit_prediction_requires_modifier()
 5921                    {
 5922                        self.unfold_ranges(&[target..target], true, false, cx);
 5923                        // Note that this is also done in vim's handler of the Tab action.
 5924                        self.change_selections(
 5925                            Some(Autoscroll::newest()),
 5926                            window,
 5927                            cx,
 5928                            |selections| {
 5929                                selections.select_anchor_ranges([target..target]);
 5930                            },
 5931                        );
 5932                        self.clear_row_highlights::<EditPredictionPreview>();
 5933
 5934                        self.edit_prediction_preview
 5935                            .set_previous_scroll_position(None);
 5936                    } else {
 5937                        self.edit_prediction_preview
 5938                            .set_previous_scroll_position(Some(
 5939                                position_map.snapshot.scroll_anchor,
 5940                            ));
 5941
 5942                        self.highlight_rows::<EditPredictionPreview>(
 5943                            target..target,
 5944                            cx.theme().colors().editor_highlighted_line_background,
 5945                            true,
 5946                            cx,
 5947                        );
 5948                        self.request_autoscroll(Autoscroll::fit(), cx);
 5949                    }
 5950                }
 5951            }
 5952            InlineCompletion::Edit { edits, .. } => {
 5953                if let Some(provider) = self.edit_prediction_provider() {
 5954                    provider.accept(cx);
 5955                }
 5956
 5957                let snapshot = self.buffer.read(cx).snapshot(cx);
 5958                let last_edit_end = edits.last().unwrap().0.end.bias_right(&snapshot);
 5959
 5960                self.buffer.update(cx, |buffer, cx| {
 5961                    buffer.edit(edits.iter().cloned(), None, cx)
 5962                });
 5963
 5964                self.change_selections(None, window, cx, |s| {
 5965                    s.select_anchor_ranges([last_edit_end..last_edit_end])
 5966                });
 5967
 5968                self.update_visible_inline_completion(window, cx);
 5969                if self.active_inline_completion.is_none() {
 5970                    self.refresh_inline_completion(true, true, window, cx);
 5971                }
 5972
 5973                cx.notify();
 5974            }
 5975        }
 5976
 5977        self.edit_prediction_requires_modifier_in_indent_conflict = false;
 5978    }
 5979
 5980    pub fn accept_partial_inline_completion(
 5981        &mut self,
 5982        _: &AcceptPartialEditPrediction,
 5983        window: &mut Window,
 5984        cx: &mut Context<Self>,
 5985    ) {
 5986        let Some(active_inline_completion) = self.active_inline_completion.as_ref() else {
 5987            return;
 5988        };
 5989        if self.selections.count() != 1 {
 5990            return;
 5991        }
 5992
 5993        self.report_inline_completion_event(
 5994            active_inline_completion.completion_id.clone(),
 5995            true,
 5996            cx,
 5997        );
 5998
 5999        match &active_inline_completion.completion {
 6000            InlineCompletion::Move { target, .. } => {
 6001                let target = *target;
 6002                self.change_selections(Some(Autoscroll::newest()), window, cx, |selections| {
 6003                    selections.select_anchor_ranges([target..target]);
 6004                });
 6005            }
 6006            InlineCompletion::Edit { edits, .. } => {
 6007                // Find an insertion that starts at the cursor position.
 6008                let snapshot = self.buffer.read(cx).snapshot(cx);
 6009                let cursor_offset = self.selections.newest::<usize>(cx).head();
 6010                let insertion = edits.iter().find_map(|(range, text)| {
 6011                    let range = range.to_offset(&snapshot);
 6012                    if range.is_empty() && range.start == cursor_offset {
 6013                        Some(text)
 6014                    } else {
 6015                        None
 6016                    }
 6017                });
 6018
 6019                if let Some(text) = insertion {
 6020                    let mut partial_completion = text
 6021                        .chars()
 6022                        .by_ref()
 6023                        .take_while(|c| c.is_alphabetic())
 6024                        .collect::<String>();
 6025                    if partial_completion.is_empty() {
 6026                        partial_completion = text
 6027                            .chars()
 6028                            .by_ref()
 6029                            .take_while(|c| c.is_whitespace() || !c.is_alphabetic())
 6030                            .collect::<String>();
 6031                    }
 6032
 6033                    cx.emit(EditorEvent::InputHandled {
 6034                        utf16_range_to_replace: None,
 6035                        text: partial_completion.clone().into(),
 6036                    });
 6037
 6038                    self.insert_with_autoindent_mode(&partial_completion, None, window, cx);
 6039
 6040                    self.refresh_inline_completion(true, true, window, cx);
 6041                    cx.notify();
 6042                } else {
 6043                    self.accept_edit_prediction(&Default::default(), window, cx);
 6044                }
 6045            }
 6046        }
 6047    }
 6048
 6049    fn discard_inline_completion(
 6050        &mut self,
 6051        should_report_inline_completion_event: bool,
 6052        cx: &mut Context<Self>,
 6053    ) -> bool {
 6054        if should_report_inline_completion_event {
 6055            let completion_id = self
 6056                .active_inline_completion
 6057                .as_ref()
 6058                .and_then(|active_completion| active_completion.completion_id.clone());
 6059
 6060            self.report_inline_completion_event(completion_id, false, cx);
 6061        }
 6062
 6063        if let Some(provider) = self.edit_prediction_provider() {
 6064            provider.discard(cx);
 6065        }
 6066
 6067        self.take_active_inline_completion(cx)
 6068    }
 6069
 6070    fn report_inline_completion_event(&self, id: Option<SharedString>, accepted: bool, cx: &App) {
 6071        let Some(provider) = self.edit_prediction_provider() else {
 6072            return;
 6073        };
 6074
 6075        let Some((_, buffer, _)) = self
 6076            .buffer
 6077            .read(cx)
 6078            .excerpt_containing(self.selections.newest_anchor().head(), cx)
 6079        else {
 6080            return;
 6081        };
 6082
 6083        let extension = buffer
 6084            .read(cx)
 6085            .file()
 6086            .and_then(|file| Some(file.path().extension()?.to_string_lossy().to_string()));
 6087
 6088        let event_type = match accepted {
 6089            true => "Edit Prediction Accepted",
 6090            false => "Edit Prediction Discarded",
 6091        };
 6092        telemetry::event!(
 6093            event_type,
 6094            provider = provider.name(),
 6095            prediction_id = id,
 6096            suggestion_accepted = accepted,
 6097            file_extension = extension,
 6098        );
 6099    }
 6100
 6101    pub fn has_active_inline_completion(&self) -> bool {
 6102        self.active_inline_completion.is_some()
 6103    }
 6104
 6105    fn take_active_inline_completion(&mut self, cx: &mut Context<Self>) -> bool {
 6106        let Some(active_inline_completion) = self.active_inline_completion.take() else {
 6107            return false;
 6108        };
 6109
 6110        self.splice_inlays(&active_inline_completion.inlay_ids, Default::default(), cx);
 6111        self.clear_highlights::<InlineCompletionHighlight>(cx);
 6112        self.stale_inline_completion_in_menu = Some(active_inline_completion);
 6113        true
 6114    }
 6115
 6116    /// Returns true when we're displaying the edit prediction popover below the cursor
 6117    /// like we are not previewing and the LSP autocomplete menu is visible
 6118    /// or we are in `when_holding_modifier` mode.
 6119    pub fn edit_prediction_visible_in_cursor_popover(&self, has_completion: bool) -> bool {
 6120        if self.edit_prediction_preview_is_active()
 6121            || !self.show_edit_predictions_in_menu()
 6122            || !self.edit_predictions_enabled()
 6123        {
 6124            return false;
 6125        }
 6126
 6127        if self.has_visible_completions_menu() {
 6128            return true;
 6129        }
 6130
 6131        has_completion && self.edit_prediction_requires_modifier()
 6132    }
 6133
 6134    fn handle_modifiers_changed(
 6135        &mut self,
 6136        modifiers: Modifiers,
 6137        position_map: &PositionMap,
 6138        window: &mut Window,
 6139        cx: &mut Context<Self>,
 6140    ) {
 6141        if self.show_edit_predictions_in_menu() {
 6142            self.update_edit_prediction_preview(&modifiers, window, cx);
 6143        }
 6144
 6145        self.update_selection_mode(&modifiers, position_map, window, cx);
 6146
 6147        let mouse_position = window.mouse_position();
 6148        if !position_map.text_hitbox.is_hovered(window) {
 6149            return;
 6150        }
 6151
 6152        self.update_hovered_link(
 6153            position_map.point_for_position(mouse_position),
 6154            &position_map.snapshot,
 6155            modifiers,
 6156            window,
 6157            cx,
 6158        )
 6159    }
 6160
 6161    fn update_selection_mode(
 6162        &mut self,
 6163        modifiers: &Modifiers,
 6164        position_map: &PositionMap,
 6165        window: &mut Window,
 6166        cx: &mut Context<Self>,
 6167    ) {
 6168        if modifiers != &COLUMNAR_SELECTION_MODIFIERS || self.selections.pending.is_none() {
 6169            return;
 6170        }
 6171
 6172        let mouse_position = window.mouse_position();
 6173        let point_for_position = position_map.point_for_position(mouse_position);
 6174        let position = point_for_position.previous_valid;
 6175
 6176        self.select(
 6177            SelectPhase::BeginColumnar {
 6178                position,
 6179                reset: false,
 6180                goal_column: point_for_position.exact_unclipped.column(),
 6181            },
 6182            window,
 6183            cx,
 6184        );
 6185    }
 6186
 6187    fn update_edit_prediction_preview(
 6188        &mut self,
 6189        modifiers: &Modifiers,
 6190        window: &mut Window,
 6191        cx: &mut Context<Self>,
 6192    ) {
 6193        let accept_keybind = self.accept_edit_prediction_keybind(window, cx);
 6194        let Some(accept_keystroke) = accept_keybind.keystroke() else {
 6195            return;
 6196        };
 6197
 6198        if &accept_keystroke.modifiers == modifiers && accept_keystroke.modifiers.modified() {
 6199            if matches!(
 6200                self.edit_prediction_preview,
 6201                EditPredictionPreview::Inactive { .. }
 6202            ) {
 6203                self.edit_prediction_preview = EditPredictionPreview::Active {
 6204                    previous_scroll_position: None,
 6205                    since: Instant::now(),
 6206                };
 6207
 6208                self.update_visible_inline_completion(window, cx);
 6209                cx.notify();
 6210            }
 6211        } else if let EditPredictionPreview::Active {
 6212            previous_scroll_position,
 6213            since,
 6214        } = self.edit_prediction_preview
 6215        {
 6216            if let (Some(previous_scroll_position), Some(position_map)) =
 6217                (previous_scroll_position, self.last_position_map.as_ref())
 6218            {
 6219                self.set_scroll_position(
 6220                    previous_scroll_position
 6221                        .scroll_position(&position_map.snapshot.display_snapshot),
 6222                    window,
 6223                    cx,
 6224                );
 6225            }
 6226
 6227            self.edit_prediction_preview = EditPredictionPreview::Inactive {
 6228                released_too_fast: since.elapsed() < Duration::from_millis(200),
 6229            };
 6230            self.clear_row_highlights::<EditPredictionPreview>();
 6231            self.update_visible_inline_completion(window, cx);
 6232            cx.notify();
 6233        }
 6234    }
 6235
 6236    fn update_visible_inline_completion(
 6237        &mut self,
 6238        _window: &mut Window,
 6239        cx: &mut Context<Self>,
 6240    ) -> Option<()> {
 6241        let selection = self.selections.newest_anchor();
 6242        let cursor = selection.head();
 6243        let multibuffer = self.buffer.read(cx).snapshot(cx);
 6244        let offset_selection = selection.map(|endpoint| endpoint.to_offset(&multibuffer));
 6245        let excerpt_id = cursor.excerpt_id;
 6246
 6247        let show_in_menu = self.show_edit_predictions_in_menu();
 6248        let completions_menu_has_precedence = !show_in_menu
 6249            && (self.context_menu.borrow().is_some()
 6250                || (!self.completion_tasks.is_empty() && !self.has_active_inline_completion()));
 6251
 6252        if completions_menu_has_precedence
 6253            || !offset_selection.is_empty()
 6254            || self
 6255                .active_inline_completion
 6256                .as_ref()
 6257                .map_or(false, |completion| {
 6258                    let invalidation_range = completion.invalidation_range.to_offset(&multibuffer);
 6259                    let invalidation_range = invalidation_range.start..=invalidation_range.end;
 6260                    !invalidation_range.contains(&offset_selection.head())
 6261                })
 6262        {
 6263            self.discard_inline_completion(false, cx);
 6264            return None;
 6265        }
 6266
 6267        self.take_active_inline_completion(cx);
 6268        let Some(provider) = self.edit_prediction_provider() else {
 6269            self.edit_prediction_settings = EditPredictionSettings::Disabled;
 6270            return None;
 6271        };
 6272
 6273        let (buffer, cursor_buffer_position) =
 6274            self.buffer.read(cx).text_anchor_for_position(cursor, cx)?;
 6275
 6276        self.edit_prediction_settings =
 6277            self.edit_prediction_settings_at_position(&buffer, cursor_buffer_position, cx);
 6278
 6279        self.edit_prediction_indent_conflict = multibuffer.is_line_whitespace_upto(cursor);
 6280
 6281        if self.edit_prediction_indent_conflict {
 6282            let cursor_point = cursor.to_point(&multibuffer);
 6283
 6284            let indents = multibuffer.suggested_indents(cursor_point.row..cursor_point.row + 1, cx);
 6285
 6286            if let Some((_, indent)) = indents.iter().next() {
 6287                if indent.len == cursor_point.column {
 6288                    self.edit_prediction_indent_conflict = false;
 6289                }
 6290            }
 6291        }
 6292
 6293        let inline_completion = provider.suggest(&buffer, cursor_buffer_position, cx)?;
 6294        let edits = inline_completion
 6295            .edits
 6296            .into_iter()
 6297            .flat_map(|(range, new_text)| {
 6298                let start = multibuffer.anchor_in_excerpt(excerpt_id, range.start)?;
 6299                let end = multibuffer.anchor_in_excerpt(excerpt_id, range.end)?;
 6300                Some((start..end, new_text))
 6301            })
 6302            .collect::<Vec<_>>();
 6303        if edits.is_empty() {
 6304            return None;
 6305        }
 6306
 6307        let first_edit_start = edits.first().unwrap().0.start;
 6308        let first_edit_start_point = first_edit_start.to_point(&multibuffer);
 6309        let edit_start_row = first_edit_start_point.row.saturating_sub(2);
 6310
 6311        let last_edit_end = edits.last().unwrap().0.end;
 6312        let last_edit_end_point = last_edit_end.to_point(&multibuffer);
 6313        let edit_end_row = cmp::min(multibuffer.max_point().row, last_edit_end_point.row + 2);
 6314
 6315        let cursor_row = cursor.to_point(&multibuffer).row;
 6316
 6317        let snapshot = multibuffer.buffer_for_excerpt(excerpt_id).cloned()?;
 6318
 6319        let mut inlay_ids = Vec::new();
 6320        let invalidation_row_range;
 6321        let move_invalidation_row_range = if cursor_row < edit_start_row {
 6322            Some(cursor_row..edit_end_row)
 6323        } else if cursor_row > edit_end_row {
 6324            Some(edit_start_row..cursor_row)
 6325        } else {
 6326            None
 6327        };
 6328        let is_move =
 6329            move_invalidation_row_range.is_some() || self.inline_completions_hidden_for_vim_mode;
 6330        let completion = if is_move {
 6331            invalidation_row_range =
 6332                move_invalidation_row_range.unwrap_or(edit_start_row..edit_end_row);
 6333            let target = first_edit_start;
 6334            InlineCompletion::Move { target, snapshot }
 6335        } else {
 6336            let show_completions_in_buffer = !self.edit_prediction_visible_in_cursor_popover(true)
 6337                && !self.inline_completions_hidden_for_vim_mode;
 6338
 6339            if show_completions_in_buffer {
 6340                if edits
 6341                    .iter()
 6342                    .all(|(range, _)| range.to_offset(&multibuffer).is_empty())
 6343                {
 6344                    let mut inlays = Vec::new();
 6345                    for (range, new_text) in &edits {
 6346                        let inlay = Inlay::inline_completion(
 6347                            post_inc(&mut self.next_inlay_id),
 6348                            range.start,
 6349                            new_text.as_str(),
 6350                        );
 6351                        inlay_ids.push(inlay.id);
 6352                        inlays.push(inlay);
 6353                    }
 6354
 6355                    self.splice_inlays(&[], inlays, cx);
 6356                } else {
 6357                    let background_color = cx.theme().status().deleted_background;
 6358                    self.highlight_text::<InlineCompletionHighlight>(
 6359                        edits.iter().map(|(range, _)| range.clone()).collect(),
 6360                        HighlightStyle {
 6361                            background_color: Some(background_color),
 6362                            ..Default::default()
 6363                        },
 6364                        cx,
 6365                    );
 6366                }
 6367            }
 6368
 6369            invalidation_row_range = edit_start_row..edit_end_row;
 6370
 6371            let display_mode = if all_edits_insertions_or_deletions(&edits, &multibuffer) {
 6372                if provider.show_tab_accept_marker() {
 6373                    EditDisplayMode::TabAccept
 6374                } else {
 6375                    EditDisplayMode::Inline
 6376                }
 6377            } else {
 6378                EditDisplayMode::DiffPopover
 6379            };
 6380
 6381            InlineCompletion::Edit {
 6382                edits,
 6383                edit_preview: inline_completion.edit_preview,
 6384                display_mode,
 6385                snapshot,
 6386            }
 6387        };
 6388
 6389        let invalidation_range = multibuffer
 6390            .anchor_before(Point::new(invalidation_row_range.start, 0))
 6391            ..multibuffer.anchor_after(Point::new(
 6392                invalidation_row_range.end,
 6393                multibuffer.line_len(MultiBufferRow(invalidation_row_range.end)),
 6394            ));
 6395
 6396        self.stale_inline_completion_in_menu = None;
 6397        self.active_inline_completion = Some(InlineCompletionState {
 6398            inlay_ids,
 6399            completion,
 6400            completion_id: inline_completion.id,
 6401            invalidation_range,
 6402        });
 6403
 6404        cx.notify();
 6405
 6406        Some(())
 6407    }
 6408
 6409    pub fn edit_prediction_provider(&self) -> Option<Arc<dyn InlineCompletionProviderHandle>> {
 6410        Some(self.edit_prediction_provider.as_ref()?.provider.clone())
 6411    }
 6412
 6413    fn render_code_actions_indicator(
 6414        &self,
 6415        _style: &EditorStyle,
 6416        row: DisplayRow,
 6417        is_active: bool,
 6418        breakpoint: Option<&(Anchor, Breakpoint)>,
 6419        cx: &mut Context<Self>,
 6420    ) -> Option<IconButton> {
 6421        let color = Color::Muted;
 6422        let position = breakpoint.as_ref().map(|(anchor, _)| *anchor);
 6423        let show_tooltip = !self.context_menu_visible();
 6424
 6425        if self.available_code_actions.is_some() {
 6426            Some(
 6427                IconButton::new("code_actions_indicator", ui::IconName::Bolt)
 6428                    .shape(ui::IconButtonShape::Square)
 6429                    .icon_size(IconSize::XSmall)
 6430                    .icon_color(color)
 6431                    .toggle_state(is_active)
 6432                    .when(show_tooltip, |this| {
 6433                        this.tooltip({
 6434                            let focus_handle = self.focus_handle.clone();
 6435                            move |window, cx| {
 6436                                Tooltip::for_action_in(
 6437                                    "Toggle Code Actions",
 6438                                    &ToggleCodeActions {
 6439                                        deployed_from_indicator: None,
 6440                                    },
 6441                                    &focus_handle,
 6442                                    window,
 6443                                    cx,
 6444                                )
 6445                            }
 6446                        })
 6447                    })
 6448                    .on_click(cx.listener(move |editor, _e, window, cx| {
 6449                        window.focus(&editor.focus_handle(cx));
 6450                        editor.toggle_code_actions(
 6451                            &ToggleCodeActions {
 6452                                deployed_from_indicator: Some(row),
 6453                            },
 6454                            window,
 6455                            cx,
 6456                        );
 6457                    }))
 6458                    .on_right_click(cx.listener(move |editor, event: &ClickEvent, window, cx| {
 6459                        editor.set_breakpoint_context_menu(
 6460                            row,
 6461                            position,
 6462                            event.down.position,
 6463                            window,
 6464                            cx,
 6465                        );
 6466                    })),
 6467            )
 6468        } else {
 6469            None
 6470        }
 6471    }
 6472
 6473    fn clear_tasks(&mut self) {
 6474        self.tasks.clear()
 6475    }
 6476
 6477    fn insert_tasks(&mut self, key: (BufferId, BufferRow), value: RunnableTasks) {
 6478        if self.tasks.insert(key, value).is_some() {
 6479            // This case should hopefully be rare, but just in case...
 6480            log::error!(
 6481                "multiple different run targets found on a single line, only the last target will be rendered"
 6482            )
 6483        }
 6484    }
 6485
 6486    /// Get all display points of breakpoints that will be rendered within editor
 6487    ///
 6488    /// This function is used to handle overlaps between breakpoints and Code action/runner symbol.
 6489    /// It's also used to set the color of line numbers with breakpoints to the breakpoint color.
 6490    /// TODO debugger: Use this function to color toggle symbols that house nested breakpoints
 6491    fn active_breakpoints(
 6492        &self,
 6493        range: Range<DisplayRow>,
 6494        window: &mut Window,
 6495        cx: &mut Context<Self>,
 6496    ) -> HashMap<DisplayRow, (Anchor, Breakpoint)> {
 6497        let mut breakpoint_display_points = HashMap::default();
 6498
 6499        let Some(breakpoint_store) = self.breakpoint_store.clone() else {
 6500            return breakpoint_display_points;
 6501        };
 6502
 6503        let snapshot = self.snapshot(window, cx);
 6504
 6505        let multi_buffer_snapshot = &snapshot.display_snapshot.buffer_snapshot;
 6506        let Some(project) = self.project.as_ref() else {
 6507            return breakpoint_display_points;
 6508        };
 6509
 6510        let range = snapshot.display_point_to_point(DisplayPoint::new(range.start, 0), Bias::Left)
 6511            ..snapshot.display_point_to_point(DisplayPoint::new(range.end, 0), Bias::Right);
 6512
 6513        for (buffer_snapshot, range, excerpt_id) in
 6514            multi_buffer_snapshot.range_to_buffer_ranges(range)
 6515        {
 6516            let Some(buffer) = project.read_with(cx, |this, cx| {
 6517                this.buffer_for_id(buffer_snapshot.remote_id(), cx)
 6518            }) else {
 6519                continue;
 6520            };
 6521            let breakpoints = breakpoint_store.read(cx).breakpoints(
 6522                &buffer,
 6523                Some(
 6524                    buffer_snapshot.anchor_before(range.start)
 6525                        ..buffer_snapshot.anchor_after(range.end),
 6526                ),
 6527                buffer_snapshot,
 6528                cx,
 6529            );
 6530            for (anchor, breakpoint) in breakpoints {
 6531                let multi_buffer_anchor =
 6532                    Anchor::in_buffer(excerpt_id, buffer_snapshot.remote_id(), *anchor);
 6533                let position = multi_buffer_anchor
 6534                    .to_point(&multi_buffer_snapshot)
 6535                    .to_display_point(&snapshot);
 6536
 6537                breakpoint_display_points
 6538                    .insert(position.row(), (multi_buffer_anchor, breakpoint.clone()));
 6539            }
 6540        }
 6541
 6542        breakpoint_display_points
 6543    }
 6544
 6545    fn breakpoint_context_menu(
 6546        &self,
 6547        anchor: Anchor,
 6548        window: &mut Window,
 6549        cx: &mut Context<Self>,
 6550    ) -> Entity<ui::ContextMenu> {
 6551        let weak_editor = cx.weak_entity();
 6552        let focus_handle = self.focus_handle(cx);
 6553
 6554        let row = self
 6555            .buffer
 6556            .read(cx)
 6557            .snapshot(cx)
 6558            .summary_for_anchor::<Point>(&anchor)
 6559            .row;
 6560
 6561        let breakpoint = self
 6562            .breakpoint_at_row(row, window, cx)
 6563            .map(|(anchor, bp)| (anchor, Arc::from(bp)));
 6564
 6565        let log_breakpoint_msg = if breakpoint.as_ref().is_some_and(|bp| bp.1.message.is_some()) {
 6566            "Edit Log Breakpoint"
 6567        } else {
 6568            "Set Log Breakpoint"
 6569        };
 6570
 6571        let condition_breakpoint_msg = if breakpoint
 6572            .as_ref()
 6573            .is_some_and(|bp| bp.1.condition.is_some())
 6574        {
 6575            "Edit Condition Breakpoint"
 6576        } else {
 6577            "Set Condition Breakpoint"
 6578        };
 6579
 6580        let hit_condition_breakpoint_msg = if breakpoint
 6581            .as_ref()
 6582            .is_some_and(|bp| bp.1.hit_condition.is_some())
 6583        {
 6584            "Edit Hit Condition Breakpoint"
 6585        } else {
 6586            "Set Hit Condition Breakpoint"
 6587        };
 6588
 6589        let set_breakpoint_msg = if breakpoint.as_ref().is_some() {
 6590            "Unset Breakpoint"
 6591        } else {
 6592            "Set Breakpoint"
 6593        };
 6594
 6595        let run_to_cursor = command_palette_hooks::CommandPaletteFilter::try_global(cx)
 6596            .map_or(false, |filter| !filter.is_hidden(&DebuggerRunToCursor));
 6597
 6598        let toggle_state_msg = breakpoint.as_ref().map_or(None, |bp| match bp.1.state {
 6599            BreakpointState::Enabled => Some("Disable"),
 6600            BreakpointState::Disabled => Some("Enable"),
 6601        });
 6602
 6603        let (anchor, breakpoint) =
 6604            breakpoint.unwrap_or_else(|| (anchor, Arc::new(Breakpoint::new_standard())));
 6605
 6606        ui::ContextMenu::build(window, cx, |menu, _, _cx| {
 6607            menu.on_blur_subscription(Subscription::new(|| {}))
 6608                .context(focus_handle)
 6609                .when(run_to_cursor, |this| {
 6610                    let weak_editor = weak_editor.clone();
 6611                    this.entry("Run to cursor", None, move |window, cx| {
 6612                        weak_editor
 6613                            .update(cx, |editor, cx| {
 6614                                editor.change_selections(None, window, cx, |s| {
 6615                                    s.select_ranges([Point::new(row, 0)..Point::new(row, 0)])
 6616                                });
 6617                            })
 6618                            .ok();
 6619
 6620                        window.dispatch_action(Box::new(DebuggerRunToCursor), cx);
 6621                    })
 6622                    .separator()
 6623                })
 6624                .when_some(toggle_state_msg, |this, msg| {
 6625                    this.entry(msg, None, {
 6626                        let weak_editor = weak_editor.clone();
 6627                        let breakpoint = breakpoint.clone();
 6628                        move |_window, cx| {
 6629                            weak_editor
 6630                                .update(cx, |this, cx| {
 6631                                    this.edit_breakpoint_at_anchor(
 6632                                        anchor,
 6633                                        breakpoint.as_ref().clone(),
 6634                                        BreakpointEditAction::InvertState,
 6635                                        cx,
 6636                                    );
 6637                                })
 6638                                .log_err();
 6639                        }
 6640                    })
 6641                })
 6642                .entry(set_breakpoint_msg, None, {
 6643                    let weak_editor = weak_editor.clone();
 6644                    let breakpoint = breakpoint.clone();
 6645                    move |_window, cx| {
 6646                        weak_editor
 6647                            .update(cx, |this, cx| {
 6648                                this.edit_breakpoint_at_anchor(
 6649                                    anchor,
 6650                                    breakpoint.as_ref().clone(),
 6651                                    BreakpointEditAction::Toggle,
 6652                                    cx,
 6653                                );
 6654                            })
 6655                            .log_err();
 6656                    }
 6657                })
 6658                .entry(log_breakpoint_msg, None, {
 6659                    let breakpoint = breakpoint.clone();
 6660                    let weak_editor = weak_editor.clone();
 6661                    move |window, cx| {
 6662                        weak_editor
 6663                            .update(cx, |this, cx| {
 6664                                this.add_edit_breakpoint_block(
 6665                                    anchor,
 6666                                    breakpoint.as_ref(),
 6667                                    BreakpointPromptEditAction::Log,
 6668                                    window,
 6669                                    cx,
 6670                                );
 6671                            })
 6672                            .log_err();
 6673                    }
 6674                })
 6675                .entry(condition_breakpoint_msg, None, {
 6676                    let breakpoint = breakpoint.clone();
 6677                    let weak_editor = weak_editor.clone();
 6678                    move |window, cx| {
 6679                        weak_editor
 6680                            .update(cx, |this, cx| {
 6681                                this.add_edit_breakpoint_block(
 6682                                    anchor,
 6683                                    breakpoint.as_ref(),
 6684                                    BreakpointPromptEditAction::Condition,
 6685                                    window,
 6686                                    cx,
 6687                                );
 6688                            })
 6689                            .log_err();
 6690                    }
 6691                })
 6692                .entry(hit_condition_breakpoint_msg, None, move |window, cx| {
 6693                    weak_editor
 6694                        .update(cx, |this, cx| {
 6695                            this.add_edit_breakpoint_block(
 6696                                anchor,
 6697                                breakpoint.as_ref(),
 6698                                BreakpointPromptEditAction::HitCondition,
 6699                                window,
 6700                                cx,
 6701                            );
 6702                        })
 6703                        .log_err();
 6704                })
 6705        })
 6706    }
 6707
 6708    fn render_breakpoint(
 6709        &self,
 6710        position: Anchor,
 6711        row: DisplayRow,
 6712        breakpoint: &Breakpoint,
 6713        cx: &mut Context<Self>,
 6714    ) -> IconButton {
 6715        let (color, icon) = {
 6716            let icon = match (&breakpoint.message.is_some(), breakpoint.is_disabled()) {
 6717                (false, false) => ui::IconName::DebugBreakpoint,
 6718                (true, false) => ui::IconName::DebugLogBreakpoint,
 6719                (false, true) => ui::IconName::DebugDisabledBreakpoint,
 6720                (true, true) => ui::IconName::DebugDisabledLogBreakpoint,
 6721            };
 6722
 6723            let color = if self
 6724                .gutter_breakpoint_indicator
 6725                .0
 6726                .is_some_and(|(point, is_visible)| is_visible && point.row() == row)
 6727            {
 6728                Color::Hint
 6729            } else {
 6730                Color::Debugger
 6731            };
 6732
 6733            (color, icon)
 6734        };
 6735
 6736        let breakpoint = Arc::from(breakpoint.clone());
 6737
 6738        IconButton::new(("breakpoint_indicator", row.0 as usize), icon)
 6739            .icon_size(IconSize::XSmall)
 6740            .size(ui::ButtonSize::None)
 6741            .icon_color(color)
 6742            .style(ButtonStyle::Transparent)
 6743            .on_click(cx.listener({
 6744                let breakpoint = breakpoint.clone();
 6745
 6746                move |editor, event: &ClickEvent, window, cx| {
 6747                    let edit_action = if event.modifiers().platform || breakpoint.is_disabled() {
 6748                        BreakpointEditAction::InvertState
 6749                    } else {
 6750                        BreakpointEditAction::Toggle
 6751                    };
 6752
 6753                    window.focus(&editor.focus_handle(cx));
 6754                    editor.edit_breakpoint_at_anchor(
 6755                        position,
 6756                        breakpoint.as_ref().clone(),
 6757                        edit_action,
 6758                        cx,
 6759                    );
 6760                }
 6761            }))
 6762            .on_right_click(cx.listener(move |editor, event: &ClickEvent, window, cx| {
 6763                editor.set_breakpoint_context_menu(
 6764                    row,
 6765                    Some(position),
 6766                    event.down.position,
 6767                    window,
 6768                    cx,
 6769                );
 6770            }))
 6771    }
 6772
 6773    fn build_tasks_context(
 6774        project: &Entity<Project>,
 6775        buffer: &Entity<Buffer>,
 6776        buffer_row: u32,
 6777        tasks: &Arc<RunnableTasks>,
 6778        cx: &mut Context<Self>,
 6779    ) -> Task<Option<task::TaskContext>> {
 6780        let position = Point::new(buffer_row, tasks.column);
 6781        let range_start = buffer.read(cx).anchor_at(position, Bias::Right);
 6782        let location = Location {
 6783            buffer: buffer.clone(),
 6784            range: range_start..range_start,
 6785        };
 6786        // Fill in the environmental variables from the tree-sitter captures
 6787        let mut captured_task_variables = TaskVariables::default();
 6788        for (capture_name, value) in tasks.extra_variables.clone() {
 6789            captured_task_variables.insert(
 6790                task::VariableName::Custom(capture_name.into()),
 6791                value.clone(),
 6792            );
 6793        }
 6794        project.update(cx, |project, cx| {
 6795            project.task_store().update(cx, |task_store, cx| {
 6796                task_store.task_context_for_location(captured_task_variables, location, cx)
 6797            })
 6798        })
 6799    }
 6800
 6801    pub fn spawn_nearest_task(
 6802        &mut self,
 6803        action: &SpawnNearestTask,
 6804        window: &mut Window,
 6805        cx: &mut Context<Self>,
 6806    ) {
 6807        let Some((workspace, _)) = self.workspace.clone() else {
 6808            return;
 6809        };
 6810        let Some(project) = self.project.clone() else {
 6811            return;
 6812        };
 6813
 6814        // Try to find a closest, enclosing node using tree-sitter that has a
 6815        // task
 6816        let Some((buffer, buffer_row, tasks)) = self
 6817            .find_enclosing_node_task(cx)
 6818            // Or find the task that's closest in row-distance.
 6819            .or_else(|| self.find_closest_task(cx))
 6820        else {
 6821            return;
 6822        };
 6823
 6824        let reveal_strategy = action.reveal;
 6825        let task_context = Self::build_tasks_context(&project, &buffer, buffer_row, &tasks, cx);
 6826        cx.spawn_in(window, async move |_, cx| {
 6827            let context = task_context.await?;
 6828            let (task_source_kind, mut resolved_task) = tasks.resolve(&context).next()?;
 6829
 6830            let resolved = resolved_task.resolved.as_mut()?;
 6831            resolved.reveal = reveal_strategy;
 6832
 6833            workspace
 6834                .update_in(cx, |workspace, window, cx| {
 6835                    workspace.schedule_resolved_task(
 6836                        task_source_kind,
 6837                        resolved_task,
 6838                        false,
 6839                        window,
 6840                        cx,
 6841                    );
 6842                })
 6843                .ok()
 6844        })
 6845        .detach();
 6846    }
 6847
 6848    fn find_closest_task(
 6849        &mut self,
 6850        cx: &mut Context<Self>,
 6851    ) -> Option<(Entity<Buffer>, u32, Arc<RunnableTasks>)> {
 6852        let cursor_row = self.selections.newest_adjusted(cx).head().row;
 6853
 6854        let ((buffer_id, row), tasks) = self
 6855            .tasks
 6856            .iter()
 6857            .min_by_key(|((_, row), _)| cursor_row.abs_diff(*row))?;
 6858
 6859        let buffer = self.buffer.read(cx).buffer(*buffer_id)?;
 6860        let tasks = Arc::new(tasks.to_owned());
 6861        Some((buffer, *row, tasks))
 6862    }
 6863
 6864    fn find_enclosing_node_task(
 6865        &mut self,
 6866        cx: &mut Context<Self>,
 6867    ) -> Option<(Entity<Buffer>, u32, Arc<RunnableTasks>)> {
 6868        let snapshot = self.buffer.read(cx).snapshot(cx);
 6869        let offset = self.selections.newest::<usize>(cx).head();
 6870        let excerpt = snapshot.excerpt_containing(offset..offset)?;
 6871        let buffer_id = excerpt.buffer().remote_id();
 6872
 6873        let layer = excerpt.buffer().syntax_layer_at(offset)?;
 6874        let mut cursor = layer.node().walk();
 6875
 6876        while cursor.goto_first_child_for_byte(offset).is_some() {
 6877            if cursor.node().end_byte() == offset {
 6878                cursor.goto_next_sibling();
 6879            }
 6880        }
 6881
 6882        // Ascend to the smallest ancestor that contains the range and has a task.
 6883        loop {
 6884            let node = cursor.node();
 6885            let node_range = node.byte_range();
 6886            let symbol_start_row = excerpt.buffer().offset_to_point(node.start_byte()).row;
 6887
 6888            // Check if this node contains our offset
 6889            if node_range.start <= offset && node_range.end >= offset {
 6890                // If it contains offset, check for task
 6891                if let Some(tasks) = self.tasks.get(&(buffer_id, symbol_start_row)) {
 6892                    let buffer = self.buffer.read(cx).buffer(buffer_id)?;
 6893                    return Some((buffer, symbol_start_row, Arc::new(tasks.to_owned())));
 6894                }
 6895            }
 6896
 6897            if !cursor.goto_parent() {
 6898                break;
 6899            }
 6900        }
 6901        None
 6902    }
 6903
 6904    fn render_run_indicator(
 6905        &self,
 6906        _style: &EditorStyle,
 6907        is_active: bool,
 6908        row: DisplayRow,
 6909        breakpoint: Option<(Anchor, Breakpoint)>,
 6910        cx: &mut Context<Self>,
 6911    ) -> IconButton {
 6912        let color = Color::Muted;
 6913        let position = breakpoint.as_ref().map(|(anchor, _)| *anchor);
 6914
 6915        IconButton::new(("run_indicator", row.0 as usize), ui::IconName::Play)
 6916            .shape(ui::IconButtonShape::Square)
 6917            .icon_size(IconSize::XSmall)
 6918            .icon_color(color)
 6919            .toggle_state(is_active)
 6920            .on_click(cx.listener(move |editor, _e, window, cx| {
 6921                window.focus(&editor.focus_handle(cx));
 6922                editor.toggle_code_actions(
 6923                    &ToggleCodeActions {
 6924                        deployed_from_indicator: Some(row),
 6925                    },
 6926                    window,
 6927                    cx,
 6928                );
 6929            }))
 6930            .on_right_click(cx.listener(move |editor, event: &ClickEvent, window, cx| {
 6931                editor.set_breakpoint_context_menu(row, position, event.down.position, window, cx);
 6932            }))
 6933    }
 6934
 6935    pub fn context_menu_visible(&self) -> bool {
 6936        !self.edit_prediction_preview_is_active()
 6937            && self
 6938                .context_menu
 6939                .borrow()
 6940                .as_ref()
 6941                .map_or(false, |menu| menu.visible())
 6942    }
 6943
 6944    fn context_menu_origin(&self) -> Option<ContextMenuOrigin> {
 6945        self.context_menu
 6946            .borrow()
 6947            .as_ref()
 6948            .map(|menu| menu.origin())
 6949    }
 6950
 6951    pub fn set_context_menu_options(&mut self, options: ContextMenuOptions) {
 6952        self.context_menu_options = Some(options);
 6953    }
 6954
 6955    const EDIT_PREDICTION_POPOVER_PADDING_X: Pixels = Pixels(24.);
 6956    const EDIT_PREDICTION_POPOVER_PADDING_Y: Pixels = Pixels(2.);
 6957
 6958    fn render_edit_prediction_popover(
 6959        &mut self,
 6960        text_bounds: &Bounds<Pixels>,
 6961        content_origin: gpui::Point<Pixels>,
 6962        editor_snapshot: &EditorSnapshot,
 6963        visible_row_range: Range<DisplayRow>,
 6964        scroll_top: f32,
 6965        scroll_bottom: f32,
 6966        line_layouts: &[LineWithInvisibles],
 6967        line_height: Pixels,
 6968        scroll_pixel_position: gpui::Point<Pixels>,
 6969        newest_selection_head: Option<DisplayPoint>,
 6970        editor_width: Pixels,
 6971        style: &EditorStyle,
 6972        window: &mut Window,
 6973        cx: &mut App,
 6974    ) -> Option<(AnyElement, gpui::Point<Pixels>)> {
 6975        let active_inline_completion = self.active_inline_completion.as_ref()?;
 6976
 6977        if self.edit_prediction_visible_in_cursor_popover(true) {
 6978            return None;
 6979        }
 6980
 6981        match &active_inline_completion.completion {
 6982            InlineCompletion::Move { target, .. } => {
 6983                let target_display_point = target.to_display_point(editor_snapshot);
 6984
 6985                if self.edit_prediction_requires_modifier() {
 6986                    if !self.edit_prediction_preview_is_active() {
 6987                        return None;
 6988                    }
 6989
 6990                    self.render_edit_prediction_modifier_jump_popover(
 6991                        text_bounds,
 6992                        content_origin,
 6993                        visible_row_range,
 6994                        line_layouts,
 6995                        line_height,
 6996                        scroll_pixel_position,
 6997                        newest_selection_head,
 6998                        target_display_point,
 6999                        window,
 7000                        cx,
 7001                    )
 7002                } else {
 7003                    self.render_edit_prediction_eager_jump_popover(
 7004                        text_bounds,
 7005                        content_origin,
 7006                        editor_snapshot,
 7007                        visible_row_range,
 7008                        scroll_top,
 7009                        scroll_bottom,
 7010                        line_height,
 7011                        scroll_pixel_position,
 7012                        target_display_point,
 7013                        editor_width,
 7014                        window,
 7015                        cx,
 7016                    )
 7017                }
 7018            }
 7019            InlineCompletion::Edit {
 7020                display_mode: EditDisplayMode::Inline,
 7021                ..
 7022            } => None,
 7023            InlineCompletion::Edit {
 7024                display_mode: EditDisplayMode::TabAccept,
 7025                edits,
 7026                ..
 7027            } => {
 7028                let range = &edits.first()?.0;
 7029                let target_display_point = range.end.to_display_point(editor_snapshot);
 7030
 7031                self.render_edit_prediction_end_of_line_popover(
 7032                    "Accept",
 7033                    editor_snapshot,
 7034                    visible_row_range,
 7035                    target_display_point,
 7036                    line_height,
 7037                    scroll_pixel_position,
 7038                    content_origin,
 7039                    editor_width,
 7040                    window,
 7041                    cx,
 7042                )
 7043            }
 7044            InlineCompletion::Edit {
 7045                edits,
 7046                edit_preview,
 7047                display_mode: EditDisplayMode::DiffPopover,
 7048                snapshot,
 7049            } => self.render_edit_prediction_diff_popover(
 7050                text_bounds,
 7051                content_origin,
 7052                editor_snapshot,
 7053                visible_row_range,
 7054                line_layouts,
 7055                line_height,
 7056                scroll_pixel_position,
 7057                newest_selection_head,
 7058                editor_width,
 7059                style,
 7060                edits,
 7061                edit_preview,
 7062                snapshot,
 7063                window,
 7064                cx,
 7065            ),
 7066        }
 7067    }
 7068
 7069    fn render_edit_prediction_modifier_jump_popover(
 7070        &mut self,
 7071        text_bounds: &Bounds<Pixels>,
 7072        content_origin: gpui::Point<Pixels>,
 7073        visible_row_range: Range<DisplayRow>,
 7074        line_layouts: &[LineWithInvisibles],
 7075        line_height: Pixels,
 7076        scroll_pixel_position: gpui::Point<Pixels>,
 7077        newest_selection_head: Option<DisplayPoint>,
 7078        target_display_point: DisplayPoint,
 7079        window: &mut Window,
 7080        cx: &mut App,
 7081    ) -> Option<(AnyElement, gpui::Point<Pixels>)> {
 7082        let scrolled_content_origin =
 7083            content_origin - gpui::Point::new(scroll_pixel_position.x, Pixels(0.0));
 7084
 7085        const SCROLL_PADDING_Y: Pixels = px(12.);
 7086
 7087        if target_display_point.row() < visible_row_range.start {
 7088            return self.render_edit_prediction_scroll_popover(
 7089                |_| SCROLL_PADDING_Y,
 7090                IconName::ArrowUp,
 7091                visible_row_range,
 7092                line_layouts,
 7093                newest_selection_head,
 7094                scrolled_content_origin,
 7095                window,
 7096                cx,
 7097            );
 7098        } else if target_display_point.row() >= visible_row_range.end {
 7099            return self.render_edit_prediction_scroll_popover(
 7100                |size| text_bounds.size.height - size.height - SCROLL_PADDING_Y,
 7101                IconName::ArrowDown,
 7102                visible_row_range,
 7103                line_layouts,
 7104                newest_selection_head,
 7105                scrolled_content_origin,
 7106                window,
 7107                cx,
 7108            );
 7109        }
 7110
 7111        const POLE_WIDTH: Pixels = px(2.);
 7112
 7113        let line_layout =
 7114            line_layouts.get(target_display_point.row().minus(visible_row_range.start) as usize)?;
 7115        let target_column = target_display_point.column() as usize;
 7116
 7117        let target_x = line_layout.x_for_index(target_column);
 7118        let target_y =
 7119            (target_display_point.row().as_f32() * line_height) - scroll_pixel_position.y;
 7120
 7121        let flag_on_right = target_x < text_bounds.size.width / 2.;
 7122
 7123        let mut border_color = Self::edit_prediction_callout_popover_border_color(cx);
 7124        border_color.l += 0.001;
 7125
 7126        let mut element = v_flex()
 7127            .items_end()
 7128            .when(flag_on_right, |el| el.items_start())
 7129            .child(if flag_on_right {
 7130                self.render_edit_prediction_line_popover("Jump", None, window, cx)?
 7131                    .rounded_bl(px(0.))
 7132                    .rounded_tl(px(0.))
 7133                    .border_l_2()
 7134                    .border_color(border_color)
 7135            } else {
 7136                self.render_edit_prediction_line_popover("Jump", None, window, cx)?
 7137                    .rounded_br(px(0.))
 7138                    .rounded_tr(px(0.))
 7139                    .border_r_2()
 7140                    .border_color(border_color)
 7141            })
 7142            .child(div().w(POLE_WIDTH).bg(border_color).h(line_height))
 7143            .into_any();
 7144
 7145        let size = element.layout_as_root(AvailableSpace::min_size(), window, cx);
 7146
 7147        let mut origin = scrolled_content_origin + point(target_x, target_y)
 7148            - point(
 7149                if flag_on_right {
 7150                    POLE_WIDTH
 7151                } else {
 7152                    size.width - POLE_WIDTH
 7153                },
 7154                size.height - line_height,
 7155            );
 7156
 7157        origin.x = origin.x.max(content_origin.x);
 7158
 7159        element.prepaint_at(origin, window, cx);
 7160
 7161        Some((element, origin))
 7162    }
 7163
 7164    fn render_edit_prediction_scroll_popover(
 7165        &mut self,
 7166        to_y: impl Fn(Size<Pixels>) -> Pixels,
 7167        scroll_icon: IconName,
 7168        visible_row_range: Range<DisplayRow>,
 7169        line_layouts: &[LineWithInvisibles],
 7170        newest_selection_head: Option<DisplayPoint>,
 7171        scrolled_content_origin: gpui::Point<Pixels>,
 7172        window: &mut Window,
 7173        cx: &mut App,
 7174    ) -> Option<(AnyElement, gpui::Point<Pixels>)> {
 7175        let mut element = self
 7176            .render_edit_prediction_line_popover("Scroll", Some(scroll_icon), window, cx)?
 7177            .into_any();
 7178
 7179        let size = element.layout_as_root(AvailableSpace::min_size(), window, cx);
 7180
 7181        let cursor = newest_selection_head?;
 7182        let cursor_row_layout =
 7183            line_layouts.get(cursor.row().minus(visible_row_range.start) as usize)?;
 7184        let cursor_column = cursor.column() as usize;
 7185
 7186        let cursor_character_x = cursor_row_layout.x_for_index(cursor_column);
 7187
 7188        let origin = scrolled_content_origin + point(cursor_character_x, to_y(size));
 7189
 7190        element.prepaint_at(origin, window, cx);
 7191        Some((element, origin))
 7192    }
 7193
 7194    fn render_edit_prediction_eager_jump_popover(
 7195        &mut self,
 7196        text_bounds: &Bounds<Pixels>,
 7197        content_origin: gpui::Point<Pixels>,
 7198        editor_snapshot: &EditorSnapshot,
 7199        visible_row_range: Range<DisplayRow>,
 7200        scroll_top: f32,
 7201        scroll_bottom: f32,
 7202        line_height: Pixels,
 7203        scroll_pixel_position: gpui::Point<Pixels>,
 7204        target_display_point: DisplayPoint,
 7205        editor_width: Pixels,
 7206        window: &mut Window,
 7207        cx: &mut App,
 7208    ) -> Option<(AnyElement, gpui::Point<Pixels>)> {
 7209        if target_display_point.row().as_f32() < scroll_top {
 7210            let mut element = self
 7211                .render_edit_prediction_line_popover(
 7212                    "Jump to Edit",
 7213                    Some(IconName::ArrowUp),
 7214                    window,
 7215                    cx,
 7216                )?
 7217                .into_any();
 7218
 7219            let size = element.layout_as_root(AvailableSpace::min_size(), window, cx);
 7220            let offset = point(
 7221                (text_bounds.size.width - size.width) / 2.,
 7222                Self::EDIT_PREDICTION_POPOVER_PADDING_Y,
 7223            );
 7224
 7225            let origin = text_bounds.origin + offset;
 7226            element.prepaint_at(origin, window, cx);
 7227            Some((element, origin))
 7228        } else if (target_display_point.row().as_f32() + 1.) > scroll_bottom {
 7229            let mut element = self
 7230                .render_edit_prediction_line_popover(
 7231                    "Jump to Edit",
 7232                    Some(IconName::ArrowDown),
 7233                    window,
 7234                    cx,
 7235                )?
 7236                .into_any();
 7237
 7238            let size = element.layout_as_root(AvailableSpace::min_size(), window, cx);
 7239            let offset = point(
 7240                (text_bounds.size.width - size.width) / 2.,
 7241                text_bounds.size.height - size.height - Self::EDIT_PREDICTION_POPOVER_PADDING_Y,
 7242            );
 7243
 7244            let origin = text_bounds.origin + offset;
 7245            element.prepaint_at(origin, window, cx);
 7246            Some((element, origin))
 7247        } else {
 7248            self.render_edit_prediction_end_of_line_popover(
 7249                "Jump to Edit",
 7250                editor_snapshot,
 7251                visible_row_range,
 7252                target_display_point,
 7253                line_height,
 7254                scroll_pixel_position,
 7255                content_origin,
 7256                editor_width,
 7257                window,
 7258                cx,
 7259            )
 7260        }
 7261    }
 7262
 7263    fn render_edit_prediction_end_of_line_popover(
 7264        self: &mut Editor,
 7265        label: &'static str,
 7266        editor_snapshot: &EditorSnapshot,
 7267        visible_row_range: Range<DisplayRow>,
 7268        target_display_point: DisplayPoint,
 7269        line_height: Pixels,
 7270        scroll_pixel_position: gpui::Point<Pixels>,
 7271        content_origin: gpui::Point<Pixels>,
 7272        editor_width: Pixels,
 7273        window: &mut Window,
 7274        cx: &mut App,
 7275    ) -> Option<(AnyElement, gpui::Point<Pixels>)> {
 7276        let target_line_end = DisplayPoint::new(
 7277            target_display_point.row(),
 7278            editor_snapshot.line_len(target_display_point.row()),
 7279        );
 7280
 7281        let mut element = self
 7282            .render_edit_prediction_line_popover(label, None, window, cx)?
 7283            .into_any();
 7284
 7285        let size = element.layout_as_root(AvailableSpace::min_size(), window, cx);
 7286
 7287        let line_origin = self.display_to_pixel_point(target_line_end, editor_snapshot, window)?;
 7288
 7289        let start_point = content_origin - point(scroll_pixel_position.x, Pixels::ZERO);
 7290        let mut origin = start_point
 7291            + line_origin
 7292            + point(Self::EDIT_PREDICTION_POPOVER_PADDING_X, Pixels::ZERO);
 7293        origin.x = origin.x.max(content_origin.x);
 7294
 7295        let max_x = content_origin.x + editor_width - size.width;
 7296
 7297        if origin.x > max_x {
 7298            let offset = line_height + Self::EDIT_PREDICTION_POPOVER_PADDING_Y;
 7299
 7300            let icon = if visible_row_range.contains(&(target_display_point.row() + 2)) {
 7301                origin.y += offset;
 7302                IconName::ArrowUp
 7303            } else {
 7304                origin.y -= offset;
 7305                IconName::ArrowDown
 7306            };
 7307
 7308            element = self
 7309                .render_edit_prediction_line_popover(label, Some(icon), window, cx)?
 7310                .into_any();
 7311
 7312            let size = element.layout_as_root(AvailableSpace::min_size(), window, cx);
 7313
 7314            origin.x = content_origin.x + editor_width - size.width - px(2.);
 7315        }
 7316
 7317        element.prepaint_at(origin, window, cx);
 7318        Some((element, origin))
 7319    }
 7320
 7321    fn render_edit_prediction_diff_popover(
 7322        self: &Editor,
 7323        text_bounds: &Bounds<Pixels>,
 7324        content_origin: gpui::Point<Pixels>,
 7325        editor_snapshot: &EditorSnapshot,
 7326        visible_row_range: Range<DisplayRow>,
 7327        line_layouts: &[LineWithInvisibles],
 7328        line_height: Pixels,
 7329        scroll_pixel_position: gpui::Point<Pixels>,
 7330        newest_selection_head: Option<DisplayPoint>,
 7331        editor_width: Pixels,
 7332        style: &EditorStyle,
 7333        edits: &Vec<(Range<Anchor>, String)>,
 7334        edit_preview: &Option<language::EditPreview>,
 7335        snapshot: &language::BufferSnapshot,
 7336        window: &mut Window,
 7337        cx: &mut App,
 7338    ) -> Option<(AnyElement, gpui::Point<Pixels>)> {
 7339        let edit_start = edits
 7340            .first()
 7341            .unwrap()
 7342            .0
 7343            .start
 7344            .to_display_point(editor_snapshot);
 7345        let edit_end = edits
 7346            .last()
 7347            .unwrap()
 7348            .0
 7349            .end
 7350            .to_display_point(editor_snapshot);
 7351
 7352        let is_visible = visible_row_range.contains(&edit_start.row())
 7353            || visible_row_range.contains(&edit_end.row());
 7354        if !is_visible {
 7355            return None;
 7356        }
 7357
 7358        let highlighted_edits =
 7359            crate::inline_completion_edit_text(&snapshot, edits, edit_preview.as_ref()?, false, cx);
 7360
 7361        let styled_text = highlighted_edits.to_styled_text(&style.text);
 7362        let line_count = highlighted_edits.text.lines().count();
 7363
 7364        const BORDER_WIDTH: Pixels = px(1.);
 7365
 7366        let keybind = self.render_edit_prediction_accept_keybind(window, cx);
 7367        let has_keybind = keybind.is_some();
 7368
 7369        let mut element = h_flex()
 7370            .items_start()
 7371            .child(
 7372                h_flex()
 7373                    .bg(cx.theme().colors().editor_background)
 7374                    .border(BORDER_WIDTH)
 7375                    .shadow_sm()
 7376                    .border_color(cx.theme().colors().border)
 7377                    .rounded_l_lg()
 7378                    .when(line_count > 1, |el| el.rounded_br_lg())
 7379                    .pr_1()
 7380                    .child(styled_text),
 7381            )
 7382            .child(
 7383                h_flex()
 7384                    .h(line_height + BORDER_WIDTH * 2.)
 7385                    .px_1p5()
 7386                    .gap_1()
 7387                    // Workaround: For some reason, there's a gap if we don't do this
 7388                    .ml(-BORDER_WIDTH)
 7389                    .shadow(smallvec![gpui::BoxShadow {
 7390                        color: gpui::black().opacity(0.05),
 7391                        offset: point(px(1.), px(1.)),
 7392                        blur_radius: px(2.),
 7393                        spread_radius: px(0.),
 7394                    }])
 7395                    .bg(Editor::edit_prediction_line_popover_bg_color(cx))
 7396                    .border(BORDER_WIDTH)
 7397                    .border_color(cx.theme().colors().border)
 7398                    .rounded_r_lg()
 7399                    .id("edit_prediction_diff_popover_keybind")
 7400                    .when(!has_keybind, |el| {
 7401                        let status_colors = cx.theme().status();
 7402
 7403                        el.bg(status_colors.error_background)
 7404                            .border_color(status_colors.error.opacity(0.6))
 7405                            .child(Icon::new(IconName::Info).color(Color::Error))
 7406                            .cursor_default()
 7407                            .hoverable_tooltip(move |_window, cx| {
 7408                                cx.new(|_| MissingEditPredictionKeybindingTooltip).into()
 7409                            })
 7410                    })
 7411                    .children(keybind),
 7412            )
 7413            .into_any();
 7414
 7415        let longest_row =
 7416            editor_snapshot.longest_row_in_range(edit_start.row()..edit_end.row() + 1);
 7417        let longest_line_width = if visible_row_range.contains(&longest_row) {
 7418            line_layouts[(longest_row.0 - visible_row_range.start.0) as usize].width
 7419        } else {
 7420            layout_line(
 7421                longest_row,
 7422                editor_snapshot,
 7423                style,
 7424                editor_width,
 7425                |_| false,
 7426                window,
 7427                cx,
 7428            )
 7429            .width
 7430        };
 7431
 7432        let viewport_bounds =
 7433            Bounds::new(Default::default(), window.viewport_size()).extend(Edges {
 7434                right: -EditorElement::SCROLLBAR_WIDTH,
 7435                ..Default::default()
 7436            });
 7437
 7438        let x_after_longest =
 7439            text_bounds.origin.x + longest_line_width + Self::EDIT_PREDICTION_POPOVER_PADDING_X
 7440                - scroll_pixel_position.x;
 7441
 7442        let element_bounds = element.layout_as_root(AvailableSpace::min_size(), window, cx);
 7443
 7444        // Fully visible if it can be displayed within the window (allow overlapping other
 7445        // panes). However, this is only allowed if the popover starts within text_bounds.
 7446        let can_position_to_the_right = x_after_longest < text_bounds.right()
 7447            && x_after_longest + element_bounds.width < viewport_bounds.right();
 7448
 7449        let mut origin = if can_position_to_the_right {
 7450            point(
 7451                x_after_longest,
 7452                text_bounds.origin.y + edit_start.row().as_f32() * line_height
 7453                    - scroll_pixel_position.y,
 7454            )
 7455        } else {
 7456            let cursor_row = newest_selection_head.map(|head| head.row());
 7457            let above_edit = edit_start
 7458                .row()
 7459                .0
 7460                .checked_sub(line_count as u32)
 7461                .map(DisplayRow);
 7462            let below_edit = Some(edit_end.row() + 1);
 7463            let above_cursor =
 7464                cursor_row.and_then(|row| row.0.checked_sub(line_count as u32).map(DisplayRow));
 7465            let below_cursor = cursor_row.map(|cursor_row| cursor_row + 1);
 7466
 7467            // Place the edit popover adjacent to the edit if there is a location
 7468            // available that is onscreen and does not obscure the cursor. Otherwise,
 7469            // place it adjacent to the cursor.
 7470            let row_target = [above_edit, below_edit, above_cursor, below_cursor]
 7471                .into_iter()
 7472                .flatten()
 7473                .find(|&start_row| {
 7474                    let end_row = start_row + line_count as u32;
 7475                    visible_row_range.contains(&start_row)
 7476                        && visible_row_range.contains(&end_row)
 7477                        && cursor_row.map_or(true, |cursor_row| {
 7478                            !((start_row..end_row).contains(&cursor_row))
 7479                        })
 7480                })?;
 7481
 7482            content_origin
 7483                + point(
 7484                    -scroll_pixel_position.x,
 7485                    row_target.as_f32() * line_height - scroll_pixel_position.y,
 7486                )
 7487        };
 7488
 7489        origin.x -= BORDER_WIDTH;
 7490
 7491        window.defer_draw(element, origin, 1);
 7492
 7493        // Do not return an element, since it will already be drawn due to defer_draw.
 7494        None
 7495    }
 7496
 7497    fn edit_prediction_cursor_popover_height(&self) -> Pixels {
 7498        px(30.)
 7499    }
 7500
 7501    fn current_user_player_color(&self, cx: &mut App) -> PlayerColor {
 7502        if self.read_only(cx) {
 7503            cx.theme().players().read_only()
 7504        } else {
 7505            self.style.as_ref().unwrap().local_player
 7506        }
 7507    }
 7508
 7509    fn render_edit_prediction_accept_keybind(
 7510        &self,
 7511        window: &mut Window,
 7512        cx: &App,
 7513    ) -> Option<AnyElement> {
 7514        let accept_binding = self.accept_edit_prediction_keybind(window, cx);
 7515        let accept_keystroke = accept_binding.keystroke()?;
 7516
 7517        let is_platform_style_mac = PlatformStyle::platform() == PlatformStyle::Mac;
 7518
 7519        let modifiers_color = if accept_keystroke.modifiers == window.modifiers() {
 7520            Color::Accent
 7521        } else {
 7522            Color::Muted
 7523        };
 7524
 7525        h_flex()
 7526            .px_0p5()
 7527            .when(is_platform_style_mac, |parent| parent.gap_0p5())
 7528            .font(theme::ThemeSettings::get_global(cx).buffer_font.clone())
 7529            .text_size(TextSize::XSmall.rems(cx))
 7530            .child(h_flex().children(ui::render_modifiers(
 7531                &accept_keystroke.modifiers,
 7532                PlatformStyle::platform(),
 7533                Some(modifiers_color),
 7534                Some(IconSize::XSmall.rems().into()),
 7535                true,
 7536            )))
 7537            .when(is_platform_style_mac, |parent| {
 7538                parent.child(accept_keystroke.key.clone())
 7539            })
 7540            .when(!is_platform_style_mac, |parent| {
 7541                parent.child(
 7542                    Key::new(
 7543                        util::capitalize(&accept_keystroke.key),
 7544                        Some(Color::Default),
 7545                    )
 7546                    .size(Some(IconSize::XSmall.rems().into())),
 7547                )
 7548            })
 7549            .into_any()
 7550            .into()
 7551    }
 7552
 7553    fn render_edit_prediction_line_popover(
 7554        &self,
 7555        label: impl Into<SharedString>,
 7556        icon: Option<IconName>,
 7557        window: &mut Window,
 7558        cx: &App,
 7559    ) -> Option<Stateful<Div>> {
 7560        let padding_right = if icon.is_some() { px(4.) } else { px(8.) };
 7561
 7562        let keybind = self.render_edit_prediction_accept_keybind(window, cx);
 7563        let has_keybind = keybind.is_some();
 7564
 7565        let result = h_flex()
 7566            .id("ep-line-popover")
 7567            .py_0p5()
 7568            .pl_1()
 7569            .pr(padding_right)
 7570            .gap_1()
 7571            .rounded_md()
 7572            .border_1()
 7573            .bg(Self::edit_prediction_line_popover_bg_color(cx))
 7574            .border_color(Self::edit_prediction_callout_popover_border_color(cx))
 7575            .shadow_sm()
 7576            .when(!has_keybind, |el| {
 7577                let status_colors = cx.theme().status();
 7578
 7579                el.bg(status_colors.error_background)
 7580                    .border_color(status_colors.error.opacity(0.6))
 7581                    .pl_2()
 7582                    .child(Icon::new(IconName::ZedPredictError).color(Color::Error))
 7583                    .cursor_default()
 7584                    .hoverable_tooltip(move |_window, cx| {
 7585                        cx.new(|_| MissingEditPredictionKeybindingTooltip).into()
 7586                    })
 7587            })
 7588            .children(keybind)
 7589            .child(
 7590                Label::new(label)
 7591                    .size(LabelSize::Small)
 7592                    .when(!has_keybind, |el| {
 7593                        el.color(cx.theme().status().error.into()).strikethrough()
 7594                    }),
 7595            )
 7596            .when(!has_keybind, |el| {
 7597                el.child(
 7598                    h_flex().ml_1().child(
 7599                        Icon::new(IconName::Info)
 7600                            .size(IconSize::Small)
 7601                            .color(cx.theme().status().error.into()),
 7602                    ),
 7603                )
 7604            })
 7605            .when_some(icon, |element, icon| {
 7606                element.child(
 7607                    div()
 7608                        .mt(px(1.5))
 7609                        .child(Icon::new(icon).size(IconSize::Small)),
 7610                )
 7611            });
 7612
 7613        Some(result)
 7614    }
 7615
 7616    fn edit_prediction_line_popover_bg_color(cx: &App) -> Hsla {
 7617        let accent_color = cx.theme().colors().text_accent;
 7618        let editor_bg_color = cx.theme().colors().editor_background;
 7619        editor_bg_color.blend(accent_color.opacity(0.1))
 7620    }
 7621
 7622    fn edit_prediction_callout_popover_border_color(cx: &App) -> Hsla {
 7623        let accent_color = cx.theme().colors().text_accent;
 7624        let editor_bg_color = cx.theme().colors().editor_background;
 7625        editor_bg_color.blend(accent_color.opacity(0.6))
 7626    }
 7627
 7628    fn render_edit_prediction_cursor_popover(
 7629        &self,
 7630        min_width: Pixels,
 7631        max_width: Pixels,
 7632        cursor_point: Point,
 7633        style: &EditorStyle,
 7634        accept_keystroke: Option<&gpui::Keystroke>,
 7635        _window: &Window,
 7636        cx: &mut Context<Editor>,
 7637    ) -> Option<AnyElement> {
 7638        let provider = self.edit_prediction_provider.as_ref()?;
 7639
 7640        if provider.provider.needs_terms_acceptance(cx) {
 7641            return Some(
 7642                h_flex()
 7643                    .min_w(min_width)
 7644                    .flex_1()
 7645                    .px_2()
 7646                    .py_1()
 7647                    .gap_3()
 7648                    .elevation_2(cx)
 7649                    .hover(|style| style.bg(cx.theme().colors().element_hover))
 7650                    .id("accept-terms")
 7651                    .cursor_pointer()
 7652                    .on_mouse_down(MouseButton::Left, |_, window, _| window.prevent_default())
 7653                    .on_click(cx.listener(|this, _event, window, cx| {
 7654                        cx.stop_propagation();
 7655                        this.report_editor_event("Edit Prediction Provider ToS Clicked", None, cx);
 7656                        window.dispatch_action(
 7657                            zed_actions::OpenZedPredictOnboarding.boxed_clone(),
 7658                            cx,
 7659                        );
 7660                    }))
 7661                    .child(
 7662                        h_flex()
 7663                            .flex_1()
 7664                            .gap_2()
 7665                            .child(Icon::new(IconName::ZedPredict))
 7666                            .child(Label::new("Accept Terms of Service"))
 7667                            .child(div().w_full())
 7668                            .child(
 7669                                Icon::new(IconName::ArrowUpRight)
 7670                                    .color(Color::Muted)
 7671                                    .size(IconSize::Small),
 7672                            )
 7673                            .into_any_element(),
 7674                    )
 7675                    .into_any(),
 7676            );
 7677        }
 7678
 7679        let is_refreshing = provider.provider.is_refreshing(cx);
 7680
 7681        fn pending_completion_container() -> Div {
 7682            h_flex()
 7683                .h_full()
 7684                .flex_1()
 7685                .gap_2()
 7686                .child(Icon::new(IconName::ZedPredict))
 7687        }
 7688
 7689        let completion = match &self.active_inline_completion {
 7690            Some(prediction) => {
 7691                if !self.has_visible_completions_menu() {
 7692                    const RADIUS: Pixels = px(6.);
 7693                    const BORDER_WIDTH: Pixels = px(1.);
 7694
 7695                    return Some(
 7696                        h_flex()
 7697                            .elevation_2(cx)
 7698                            .border(BORDER_WIDTH)
 7699                            .border_color(cx.theme().colors().border)
 7700                            .when(accept_keystroke.is_none(), |el| {
 7701                                el.border_color(cx.theme().status().error)
 7702                            })
 7703                            .rounded(RADIUS)
 7704                            .rounded_tl(px(0.))
 7705                            .overflow_hidden()
 7706                            .child(div().px_1p5().child(match &prediction.completion {
 7707                                InlineCompletion::Move { target, snapshot } => {
 7708                                    use text::ToPoint as _;
 7709                                    if target.text_anchor.to_point(&snapshot).row > cursor_point.row
 7710                                    {
 7711                                        Icon::new(IconName::ZedPredictDown)
 7712                                    } else {
 7713                                        Icon::new(IconName::ZedPredictUp)
 7714                                    }
 7715                                }
 7716                                InlineCompletion::Edit { .. } => Icon::new(IconName::ZedPredict),
 7717                            }))
 7718                            .child(
 7719                                h_flex()
 7720                                    .gap_1()
 7721                                    .py_1()
 7722                                    .px_2()
 7723                                    .rounded_r(RADIUS - BORDER_WIDTH)
 7724                                    .border_l_1()
 7725                                    .border_color(cx.theme().colors().border)
 7726                                    .bg(Self::edit_prediction_line_popover_bg_color(cx))
 7727                                    .when(self.edit_prediction_preview.released_too_fast(), |el| {
 7728                                        el.child(
 7729                                            Label::new("Hold")
 7730                                                .size(LabelSize::Small)
 7731                                                .when(accept_keystroke.is_none(), |el| {
 7732                                                    el.strikethrough()
 7733                                                })
 7734                                                .line_height_style(LineHeightStyle::UiLabel),
 7735                                        )
 7736                                    })
 7737                                    .id("edit_prediction_cursor_popover_keybind")
 7738                                    .when(accept_keystroke.is_none(), |el| {
 7739                                        let status_colors = cx.theme().status();
 7740
 7741                                        el.bg(status_colors.error_background)
 7742                                            .border_color(status_colors.error.opacity(0.6))
 7743                                            .child(Icon::new(IconName::Info).color(Color::Error))
 7744                                            .cursor_default()
 7745                                            .hoverable_tooltip(move |_window, cx| {
 7746                                                cx.new(|_| MissingEditPredictionKeybindingTooltip)
 7747                                                    .into()
 7748                                            })
 7749                                    })
 7750                                    .when_some(
 7751                                        accept_keystroke.as_ref(),
 7752                                        |el, accept_keystroke| {
 7753                                            el.child(h_flex().children(ui::render_modifiers(
 7754                                                &accept_keystroke.modifiers,
 7755                                                PlatformStyle::platform(),
 7756                                                Some(Color::Default),
 7757                                                Some(IconSize::XSmall.rems().into()),
 7758                                                false,
 7759                                            )))
 7760                                        },
 7761                                    ),
 7762                            )
 7763                            .into_any(),
 7764                    );
 7765                }
 7766
 7767                self.render_edit_prediction_cursor_popover_preview(
 7768                    prediction,
 7769                    cursor_point,
 7770                    style,
 7771                    cx,
 7772                )?
 7773            }
 7774
 7775            None if is_refreshing => match &self.stale_inline_completion_in_menu {
 7776                Some(stale_completion) => self.render_edit_prediction_cursor_popover_preview(
 7777                    stale_completion,
 7778                    cursor_point,
 7779                    style,
 7780                    cx,
 7781                )?,
 7782
 7783                None => {
 7784                    pending_completion_container().child(Label::new("...").size(LabelSize::Small))
 7785                }
 7786            },
 7787
 7788            None => pending_completion_container().child(Label::new("No Prediction")),
 7789        };
 7790
 7791        let completion = if is_refreshing {
 7792            completion
 7793                .with_animation(
 7794                    "loading-completion",
 7795                    Animation::new(Duration::from_secs(2))
 7796                        .repeat()
 7797                        .with_easing(pulsating_between(0.4, 0.8)),
 7798                    |label, delta| label.opacity(delta),
 7799                )
 7800                .into_any_element()
 7801        } else {
 7802            completion.into_any_element()
 7803        };
 7804
 7805        let has_completion = self.active_inline_completion.is_some();
 7806
 7807        let is_platform_style_mac = PlatformStyle::platform() == PlatformStyle::Mac;
 7808        Some(
 7809            h_flex()
 7810                .min_w(min_width)
 7811                .max_w(max_width)
 7812                .flex_1()
 7813                .elevation_2(cx)
 7814                .border_color(cx.theme().colors().border)
 7815                .child(
 7816                    div()
 7817                        .flex_1()
 7818                        .py_1()
 7819                        .px_2()
 7820                        .overflow_hidden()
 7821                        .child(completion),
 7822                )
 7823                .when_some(accept_keystroke, |el, accept_keystroke| {
 7824                    if !accept_keystroke.modifiers.modified() {
 7825                        return el;
 7826                    }
 7827
 7828                    el.child(
 7829                        h_flex()
 7830                            .h_full()
 7831                            .border_l_1()
 7832                            .rounded_r_lg()
 7833                            .border_color(cx.theme().colors().border)
 7834                            .bg(Self::edit_prediction_line_popover_bg_color(cx))
 7835                            .gap_1()
 7836                            .py_1()
 7837                            .px_2()
 7838                            .child(
 7839                                h_flex()
 7840                                    .font(theme::ThemeSettings::get_global(cx).buffer_font.clone())
 7841                                    .when(is_platform_style_mac, |parent| parent.gap_1())
 7842                                    .child(h_flex().children(ui::render_modifiers(
 7843                                        &accept_keystroke.modifiers,
 7844                                        PlatformStyle::platform(),
 7845                                        Some(if !has_completion {
 7846                                            Color::Muted
 7847                                        } else {
 7848                                            Color::Default
 7849                                        }),
 7850                                        None,
 7851                                        false,
 7852                                    ))),
 7853                            )
 7854                            .child(Label::new("Preview").into_any_element())
 7855                            .opacity(if has_completion { 1.0 } else { 0.4 }),
 7856                    )
 7857                })
 7858                .into_any(),
 7859        )
 7860    }
 7861
 7862    fn render_edit_prediction_cursor_popover_preview(
 7863        &self,
 7864        completion: &InlineCompletionState,
 7865        cursor_point: Point,
 7866        style: &EditorStyle,
 7867        cx: &mut Context<Editor>,
 7868    ) -> Option<Div> {
 7869        use text::ToPoint as _;
 7870
 7871        fn render_relative_row_jump(
 7872            prefix: impl Into<String>,
 7873            current_row: u32,
 7874            target_row: u32,
 7875        ) -> Div {
 7876            let (row_diff, arrow) = if target_row < current_row {
 7877                (current_row - target_row, IconName::ArrowUp)
 7878            } else {
 7879                (target_row - current_row, IconName::ArrowDown)
 7880            };
 7881
 7882            h_flex()
 7883                .child(
 7884                    Label::new(format!("{}{}", prefix.into(), row_diff))
 7885                        .color(Color::Muted)
 7886                        .size(LabelSize::Small),
 7887                )
 7888                .child(Icon::new(arrow).color(Color::Muted).size(IconSize::Small))
 7889        }
 7890
 7891        match &completion.completion {
 7892            InlineCompletion::Move {
 7893                target, snapshot, ..
 7894            } => Some(
 7895                h_flex()
 7896                    .px_2()
 7897                    .gap_2()
 7898                    .flex_1()
 7899                    .child(
 7900                        if target.text_anchor.to_point(&snapshot).row > cursor_point.row {
 7901                            Icon::new(IconName::ZedPredictDown)
 7902                        } else {
 7903                            Icon::new(IconName::ZedPredictUp)
 7904                        },
 7905                    )
 7906                    .child(Label::new("Jump to Edit")),
 7907            ),
 7908
 7909            InlineCompletion::Edit {
 7910                edits,
 7911                edit_preview,
 7912                snapshot,
 7913                display_mode: _,
 7914            } => {
 7915                let first_edit_row = edits.first()?.0.start.text_anchor.to_point(&snapshot).row;
 7916
 7917                let (highlighted_edits, has_more_lines) = crate::inline_completion_edit_text(
 7918                    &snapshot,
 7919                    &edits,
 7920                    edit_preview.as_ref()?,
 7921                    true,
 7922                    cx,
 7923                )
 7924                .first_line_preview();
 7925
 7926                let styled_text = gpui::StyledText::new(highlighted_edits.text)
 7927                    .with_default_highlights(&style.text, highlighted_edits.highlights);
 7928
 7929                let preview = h_flex()
 7930                    .gap_1()
 7931                    .min_w_16()
 7932                    .child(styled_text)
 7933                    .when(has_more_lines, |parent| parent.child(""));
 7934
 7935                let left = if first_edit_row != cursor_point.row {
 7936                    render_relative_row_jump("", cursor_point.row, first_edit_row)
 7937                        .into_any_element()
 7938                } else {
 7939                    Icon::new(IconName::ZedPredict).into_any_element()
 7940                };
 7941
 7942                Some(
 7943                    h_flex()
 7944                        .h_full()
 7945                        .flex_1()
 7946                        .gap_2()
 7947                        .pr_1()
 7948                        .overflow_x_hidden()
 7949                        .font(theme::ThemeSettings::get_global(cx).buffer_font.clone())
 7950                        .child(left)
 7951                        .child(preview),
 7952                )
 7953            }
 7954        }
 7955    }
 7956
 7957    fn render_context_menu(
 7958        &self,
 7959        style: &EditorStyle,
 7960        max_height_in_lines: u32,
 7961        window: &mut Window,
 7962        cx: &mut Context<Editor>,
 7963    ) -> Option<AnyElement> {
 7964        let menu = self.context_menu.borrow();
 7965        let menu = menu.as_ref()?;
 7966        if !menu.visible() {
 7967            return None;
 7968        };
 7969        Some(menu.render(style, max_height_in_lines, window, cx))
 7970    }
 7971
 7972    fn render_context_menu_aside(
 7973        &mut self,
 7974        max_size: Size<Pixels>,
 7975        window: &mut Window,
 7976        cx: &mut Context<Editor>,
 7977    ) -> Option<AnyElement> {
 7978        self.context_menu.borrow_mut().as_mut().and_then(|menu| {
 7979            if menu.visible() {
 7980                menu.render_aside(self, max_size, window, cx)
 7981            } else {
 7982                None
 7983            }
 7984        })
 7985    }
 7986
 7987    fn hide_context_menu(
 7988        &mut self,
 7989        window: &mut Window,
 7990        cx: &mut Context<Self>,
 7991    ) -> Option<CodeContextMenu> {
 7992        cx.notify();
 7993        self.completion_tasks.clear();
 7994        let context_menu = self.context_menu.borrow_mut().take();
 7995        self.stale_inline_completion_in_menu.take();
 7996        self.update_visible_inline_completion(window, cx);
 7997        context_menu
 7998    }
 7999
 8000    fn show_snippet_choices(
 8001        &mut self,
 8002        choices: &Vec<String>,
 8003        selection: Range<Anchor>,
 8004        cx: &mut Context<Self>,
 8005    ) {
 8006        if selection.start.buffer_id.is_none() {
 8007            return;
 8008        }
 8009        let buffer_id = selection.start.buffer_id.unwrap();
 8010        let buffer = self.buffer().read(cx).buffer(buffer_id);
 8011        let id = post_inc(&mut self.next_completion_id);
 8012
 8013        if let Some(buffer) = buffer {
 8014            *self.context_menu.borrow_mut() = Some(CodeContextMenu::Completions(
 8015                CompletionsMenu::new_snippet_choices(id, true, choices, selection, buffer),
 8016            ));
 8017        }
 8018    }
 8019
 8020    pub fn insert_snippet(
 8021        &mut self,
 8022        insertion_ranges: &[Range<usize>],
 8023        snippet: Snippet,
 8024        window: &mut Window,
 8025        cx: &mut Context<Self>,
 8026    ) -> Result<()> {
 8027        struct Tabstop<T> {
 8028            is_end_tabstop: bool,
 8029            ranges: Vec<Range<T>>,
 8030            choices: Option<Vec<String>>,
 8031        }
 8032
 8033        let tabstops = self.buffer.update(cx, |buffer, cx| {
 8034            let snippet_text: Arc<str> = snippet.text.clone().into();
 8035            let edits = insertion_ranges
 8036                .iter()
 8037                .cloned()
 8038                .map(|range| (range, snippet_text.clone()));
 8039            buffer.edit(edits, Some(AutoindentMode::EachLine), cx);
 8040
 8041            let snapshot = &*buffer.read(cx);
 8042            let snippet = &snippet;
 8043            snippet
 8044                .tabstops
 8045                .iter()
 8046                .map(|tabstop| {
 8047                    let is_end_tabstop = tabstop.ranges.first().map_or(false, |tabstop| {
 8048                        tabstop.is_empty() && tabstop.start == snippet.text.len() as isize
 8049                    });
 8050                    let mut tabstop_ranges = tabstop
 8051                        .ranges
 8052                        .iter()
 8053                        .flat_map(|tabstop_range| {
 8054                            let mut delta = 0_isize;
 8055                            insertion_ranges.iter().map(move |insertion_range| {
 8056                                let insertion_start = insertion_range.start as isize + delta;
 8057                                delta +=
 8058                                    snippet.text.len() as isize - insertion_range.len() as isize;
 8059
 8060                                let start = ((insertion_start + tabstop_range.start) as usize)
 8061                                    .min(snapshot.len());
 8062                                let end = ((insertion_start + tabstop_range.end) as usize)
 8063                                    .min(snapshot.len());
 8064                                snapshot.anchor_before(start)..snapshot.anchor_after(end)
 8065                            })
 8066                        })
 8067                        .collect::<Vec<_>>();
 8068                    tabstop_ranges.sort_unstable_by(|a, b| a.start.cmp(&b.start, snapshot));
 8069
 8070                    Tabstop {
 8071                        is_end_tabstop,
 8072                        ranges: tabstop_ranges,
 8073                        choices: tabstop.choices.clone(),
 8074                    }
 8075                })
 8076                .collect::<Vec<_>>()
 8077        });
 8078        if let Some(tabstop) = tabstops.first() {
 8079            self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8080                s.select_ranges(tabstop.ranges.iter().cloned());
 8081            });
 8082
 8083            if let Some(choices) = &tabstop.choices {
 8084                if let Some(selection) = tabstop.ranges.first() {
 8085                    self.show_snippet_choices(choices, selection.clone(), cx)
 8086                }
 8087            }
 8088
 8089            // If we're already at the last tabstop and it's at the end of the snippet,
 8090            // we're done, we don't need to keep the state around.
 8091            if !tabstop.is_end_tabstop {
 8092                let choices = tabstops
 8093                    .iter()
 8094                    .map(|tabstop| tabstop.choices.clone())
 8095                    .collect();
 8096
 8097                let ranges = tabstops
 8098                    .into_iter()
 8099                    .map(|tabstop| tabstop.ranges)
 8100                    .collect::<Vec<_>>();
 8101
 8102                self.snippet_stack.push(SnippetState {
 8103                    active_index: 0,
 8104                    ranges,
 8105                    choices,
 8106                });
 8107            }
 8108
 8109            // Check whether the just-entered snippet ends with an auto-closable bracket.
 8110            if self.autoclose_regions.is_empty() {
 8111                let snapshot = self.buffer.read(cx).snapshot(cx);
 8112                for selection in &mut self.selections.all::<Point>(cx) {
 8113                    let selection_head = selection.head();
 8114                    let Some(scope) = snapshot.language_scope_at(selection_head) else {
 8115                        continue;
 8116                    };
 8117
 8118                    let mut bracket_pair = None;
 8119                    let next_chars = snapshot.chars_at(selection_head).collect::<String>();
 8120                    let prev_chars = snapshot
 8121                        .reversed_chars_at(selection_head)
 8122                        .collect::<String>();
 8123                    for (pair, enabled) in scope.brackets() {
 8124                        if enabled
 8125                            && pair.close
 8126                            && prev_chars.starts_with(pair.start.as_str())
 8127                            && next_chars.starts_with(pair.end.as_str())
 8128                        {
 8129                            bracket_pair = Some(pair.clone());
 8130                            break;
 8131                        }
 8132                    }
 8133                    if let Some(pair) = bracket_pair {
 8134                        let snapshot_settings = snapshot.language_settings_at(selection_head, cx);
 8135                        let autoclose_enabled =
 8136                            self.use_autoclose && snapshot_settings.use_autoclose;
 8137                        if autoclose_enabled {
 8138                            let start = snapshot.anchor_after(selection_head);
 8139                            let end = snapshot.anchor_after(selection_head);
 8140                            self.autoclose_regions.push(AutocloseRegion {
 8141                                selection_id: selection.id,
 8142                                range: start..end,
 8143                                pair,
 8144                            });
 8145                        }
 8146                    }
 8147                }
 8148            }
 8149        }
 8150        Ok(())
 8151    }
 8152
 8153    pub fn move_to_next_snippet_tabstop(
 8154        &mut self,
 8155        window: &mut Window,
 8156        cx: &mut Context<Self>,
 8157    ) -> bool {
 8158        self.move_to_snippet_tabstop(Bias::Right, window, cx)
 8159    }
 8160
 8161    pub fn move_to_prev_snippet_tabstop(
 8162        &mut self,
 8163        window: &mut Window,
 8164        cx: &mut Context<Self>,
 8165    ) -> bool {
 8166        self.move_to_snippet_tabstop(Bias::Left, window, cx)
 8167    }
 8168
 8169    pub fn move_to_snippet_tabstop(
 8170        &mut self,
 8171        bias: Bias,
 8172        window: &mut Window,
 8173        cx: &mut Context<Self>,
 8174    ) -> bool {
 8175        if let Some(mut snippet) = self.snippet_stack.pop() {
 8176            match bias {
 8177                Bias::Left => {
 8178                    if snippet.active_index > 0 {
 8179                        snippet.active_index -= 1;
 8180                    } else {
 8181                        self.snippet_stack.push(snippet);
 8182                        return false;
 8183                    }
 8184                }
 8185                Bias::Right => {
 8186                    if snippet.active_index + 1 < snippet.ranges.len() {
 8187                        snippet.active_index += 1;
 8188                    } else {
 8189                        self.snippet_stack.push(snippet);
 8190                        return false;
 8191                    }
 8192                }
 8193            }
 8194            if let Some(current_ranges) = snippet.ranges.get(snippet.active_index) {
 8195                self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8196                    s.select_anchor_ranges(current_ranges.iter().cloned())
 8197                });
 8198
 8199                if let Some(choices) = &snippet.choices[snippet.active_index] {
 8200                    if let Some(selection) = current_ranges.first() {
 8201                        self.show_snippet_choices(&choices, selection.clone(), cx);
 8202                    }
 8203                }
 8204
 8205                // If snippet state is not at the last tabstop, push it back on the stack
 8206                if snippet.active_index + 1 < snippet.ranges.len() {
 8207                    self.snippet_stack.push(snippet);
 8208                }
 8209                return true;
 8210            }
 8211        }
 8212
 8213        false
 8214    }
 8215
 8216    pub fn clear(&mut self, window: &mut Window, cx: &mut Context<Self>) {
 8217        self.transact(window, cx, |this, window, cx| {
 8218            this.select_all(&SelectAll, window, cx);
 8219            this.insert("", window, cx);
 8220        });
 8221    }
 8222
 8223    pub fn backspace(&mut self, _: &Backspace, window: &mut Window, cx: &mut Context<Self>) {
 8224        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
 8225        self.transact(window, cx, |this, window, cx| {
 8226            this.select_autoclose_pair(window, cx);
 8227            let mut linked_ranges = HashMap::<_, Vec<_>>::default();
 8228            if !this.linked_edit_ranges.is_empty() {
 8229                let selections = this.selections.all::<MultiBufferPoint>(cx);
 8230                let snapshot = this.buffer.read(cx).snapshot(cx);
 8231
 8232                for selection in selections.iter() {
 8233                    let selection_start = snapshot.anchor_before(selection.start).text_anchor;
 8234                    let selection_end = snapshot.anchor_after(selection.end).text_anchor;
 8235                    if selection_start.buffer_id != selection_end.buffer_id {
 8236                        continue;
 8237                    }
 8238                    if let Some(ranges) =
 8239                        this.linked_editing_ranges_for(selection_start..selection_end, cx)
 8240                    {
 8241                        for (buffer, entries) in ranges {
 8242                            linked_ranges.entry(buffer).or_default().extend(entries);
 8243                        }
 8244                    }
 8245                }
 8246            }
 8247
 8248            let mut selections = this.selections.all::<MultiBufferPoint>(cx);
 8249            let display_map = this.display_map.update(cx, |map, cx| map.snapshot(cx));
 8250            for selection in &mut selections {
 8251                if selection.is_empty() {
 8252                    let old_head = selection.head();
 8253                    let mut new_head =
 8254                        movement::left(&display_map, old_head.to_display_point(&display_map))
 8255                            .to_point(&display_map);
 8256                    if let Some((buffer, line_buffer_range)) = display_map
 8257                        .buffer_snapshot
 8258                        .buffer_line_for_row(MultiBufferRow(old_head.row))
 8259                    {
 8260                        let indent_size = buffer.indent_size_for_line(line_buffer_range.start.row);
 8261                        let indent_len = match indent_size.kind {
 8262                            IndentKind::Space => {
 8263                                buffer.settings_at(line_buffer_range.start, cx).tab_size
 8264                            }
 8265                            IndentKind::Tab => NonZeroU32::new(1).unwrap(),
 8266                        };
 8267                        if old_head.column <= indent_size.len && old_head.column > 0 {
 8268                            let indent_len = indent_len.get();
 8269                            new_head = cmp::min(
 8270                                new_head,
 8271                                MultiBufferPoint::new(
 8272                                    old_head.row,
 8273                                    ((old_head.column - 1) / indent_len) * indent_len,
 8274                                ),
 8275                            );
 8276                        }
 8277                    }
 8278
 8279                    selection.set_head(new_head, SelectionGoal::None);
 8280                }
 8281            }
 8282
 8283            this.signature_help_state.set_backspace_pressed(true);
 8284            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8285                s.select(selections)
 8286            });
 8287            this.insert("", window, cx);
 8288            let empty_str: Arc<str> = Arc::from("");
 8289            for (buffer, edits) in linked_ranges {
 8290                let snapshot = buffer.read(cx).snapshot();
 8291                use text::ToPoint as TP;
 8292
 8293                let edits = edits
 8294                    .into_iter()
 8295                    .map(|range| {
 8296                        let end_point = TP::to_point(&range.end, &snapshot);
 8297                        let mut start_point = TP::to_point(&range.start, &snapshot);
 8298
 8299                        if end_point == start_point {
 8300                            let offset = text::ToOffset::to_offset(&range.start, &snapshot)
 8301                                .saturating_sub(1);
 8302                            start_point =
 8303                                snapshot.clip_point(TP::to_point(&offset, &snapshot), Bias::Left);
 8304                        };
 8305
 8306                        (start_point..end_point, empty_str.clone())
 8307                    })
 8308                    .sorted_by_key(|(range, _)| range.start)
 8309                    .collect::<Vec<_>>();
 8310                buffer.update(cx, |this, cx| {
 8311                    this.edit(edits, None, cx);
 8312                })
 8313            }
 8314            this.refresh_inline_completion(true, false, window, cx);
 8315            linked_editing_ranges::refresh_linked_ranges(this, window, cx);
 8316        });
 8317    }
 8318
 8319    pub fn delete(&mut self, _: &Delete, window: &mut Window, cx: &mut Context<Self>) {
 8320        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
 8321        self.transact(window, cx, |this, window, cx| {
 8322            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8323                s.move_with(|map, selection| {
 8324                    if selection.is_empty() {
 8325                        let cursor = movement::right(map, selection.head());
 8326                        selection.end = cursor;
 8327                        selection.reversed = true;
 8328                        selection.goal = SelectionGoal::None;
 8329                    }
 8330                })
 8331            });
 8332            this.insert("", window, cx);
 8333            this.refresh_inline_completion(true, false, window, cx);
 8334        });
 8335    }
 8336
 8337    pub fn backtab(&mut self, _: &Backtab, window: &mut Window, cx: &mut Context<Self>) {
 8338        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
 8339        if self.move_to_prev_snippet_tabstop(window, cx) {
 8340            return;
 8341        }
 8342        self.outdent(&Outdent, window, cx);
 8343    }
 8344
 8345    pub fn tab(&mut self, _: &Tab, window: &mut Window, cx: &mut Context<Self>) {
 8346        if self.move_to_next_snippet_tabstop(window, cx) {
 8347            self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
 8348            return;
 8349        }
 8350        if self.read_only(cx) {
 8351            return;
 8352        }
 8353        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
 8354        let mut selections = self.selections.all_adjusted(cx);
 8355        let buffer = self.buffer.read(cx);
 8356        let snapshot = buffer.snapshot(cx);
 8357        let rows_iter = selections.iter().map(|s| s.head().row);
 8358        let suggested_indents = snapshot.suggested_indents(rows_iter, cx);
 8359
 8360        let mut edits = Vec::new();
 8361        let mut prev_edited_row = 0;
 8362        let mut row_delta = 0;
 8363        for selection in &mut selections {
 8364            if selection.start.row != prev_edited_row {
 8365                row_delta = 0;
 8366            }
 8367            prev_edited_row = selection.end.row;
 8368
 8369            // If the selection is non-empty, then increase the indentation of the selected lines.
 8370            if !selection.is_empty() {
 8371                row_delta =
 8372                    Self::indent_selection(buffer, &snapshot, selection, &mut edits, row_delta, cx);
 8373                continue;
 8374            }
 8375
 8376            // If the selection is empty and the cursor is in the leading whitespace before the
 8377            // suggested indentation, then auto-indent the line.
 8378            let cursor = selection.head();
 8379            let current_indent = snapshot.indent_size_for_line(MultiBufferRow(cursor.row));
 8380            if let Some(suggested_indent) =
 8381                suggested_indents.get(&MultiBufferRow(cursor.row)).copied()
 8382            {
 8383                if cursor.column < suggested_indent.len
 8384                    && cursor.column <= current_indent.len
 8385                    && current_indent.len <= suggested_indent.len
 8386                {
 8387                    selection.start = Point::new(cursor.row, suggested_indent.len);
 8388                    selection.end = selection.start;
 8389                    if row_delta == 0 {
 8390                        edits.extend(Buffer::edit_for_indent_size_adjustment(
 8391                            cursor.row,
 8392                            current_indent,
 8393                            suggested_indent,
 8394                        ));
 8395                        row_delta = suggested_indent.len - current_indent.len;
 8396                    }
 8397                    continue;
 8398                }
 8399            }
 8400
 8401            // Otherwise, insert a hard or soft tab.
 8402            let settings = buffer.language_settings_at(cursor, cx);
 8403            let tab_size = if settings.hard_tabs {
 8404                IndentSize::tab()
 8405            } else {
 8406                let tab_size = settings.tab_size.get();
 8407                let indent_remainder = snapshot
 8408                    .text_for_range(Point::new(cursor.row, 0)..cursor)
 8409                    .flat_map(str::chars)
 8410                    .fold(row_delta % tab_size, |counter: u32, c| {
 8411                        if c == '\t' {
 8412                            0
 8413                        } else {
 8414                            (counter + 1) % tab_size
 8415                        }
 8416                    });
 8417
 8418                let chars_to_next_tab_stop = tab_size - indent_remainder;
 8419                IndentSize::spaces(chars_to_next_tab_stop)
 8420            };
 8421            selection.start = Point::new(cursor.row, cursor.column + row_delta + tab_size.len);
 8422            selection.end = selection.start;
 8423            edits.push((cursor..cursor, tab_size.chars().collect::<String>()));
 8424            row_delta += tab_size.len;
 8425        }
 8426
 8427        self.transact(window, cx, |this, window, cx| {
 8428            this.buffer.update(cx, |b, cx| b.edit(edits, None, cx));
 8429            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8430                s.select(selections)
 8431            });
 8432            this.refresh_inline_completion(true, false, window, cx);
 8433        });
 8434    }
 8435
 8436    pub fn indent(&mut self, _: &Indent, window: &mut Window, cx: &mut Context<Self>) {
 8437        if self.read_only(cx) {
 8438            return;
 8439        }
 8440        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
 8441        let mut selections = self.selections.all::<Point>(cx);
 8442        let mut prev_edited_row = 0;
 8443        let mut row_delta = 0;
 8444        let mut edits = Vec::new();
 8445        let buffer = self.buffer.read(cx);
 8446        let snapshot = buffer.snapshot(cx);
 8447        for selection in &mut selections {
 8448            if selection.start.row != prev_edited_row {
 8449                row_delta = 0;
 8450            }
 8451            prev_edited_row = selection.end.row;
 8452
 8453            row_delta =
 8454                Self::indent_selection(buffer, &snapshot, selection, &mut edits, row_delta, cx);
 8455        }
 8456
 8457        self.transact(window, cx, |this, window, cx| {
 8458            this.buffer.update(cx, |b, cx| b.edit(edits, None, cx));
 8459            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8460                s.select(selections)
 8461            });
 8462        });
 8463    }
 8464
 8465    fn indent_selection(
 8466        buffer: &MultiBuffer,
 8467        snapshot: &MultiBufferSnapshot,
 8468        selection: &mut Selection<Point>,
 8469        edits: &mut Vec<(Range<Point>, String)>,
 8470        delta_for_start_row: u32,
 8471        cx: &App,
 8472    ) -> u32 {
 8473        let settings = buffer.language_settings_at(selection.start, cx);
 8474        let tab_size = settings.tab_size.get();
 8475        let indent_kind = if settings.hard_tabs {
 8476            IndentKind::Tab
 8477        } else {
 8478            IndentKind::Space
 8479        };
 8480        let mut start_row = selection.start.row;
 8481        let mut end_row = selection.end.row + 1;
 8482
 8483        // If a selection ends at the beginning of a line, don't indent
 8484        // that last line.
 8485        if selection.end.column == 0 && selection.end.row > selection.start.row {
 8486            end_row -= 1;
 8487        }
 8488
 8489        // Avoid re-indenting a row that has already been indented by a
 8490        // previous selection, but still update this selection's column
 8491        // to reflect that indentation.
 8492        if delta_for_start_row > 0 {
 8493            start_row += 1;
 8494            selection.start.column += delta_for_start_row;
 8495            if selection.end.row == selection.start.row {
 8496                selection.end.column += delta_for_start_row;
 8497            }
 8498        }
 8499
 8500        let mut delta_for_end_row = 0;
 8501        let has_multiple_rows = start_row + 1 != end_row;
 8502        for row in start_row..end_row {
 8503            let current_indent = snapshot.indent_size_for_line(MultiBufferRow(row));
 8504            let indent_delta = match (current_indent.kind, indent_kind) {
 8505                (IndentKind::Space, IndentKind::Space) => {
 8506                    let columns_to_next_tab_stop = tab_size - (current_indent.len % tab_size);
 8507                    IndentSize::spaces(columns_to_next_tab_stop)
 8508                }
 8509                (IndentKind::Tab, IndentKind::Space) => IndentSize::spaces(tab_size),
 8510                (_, IndentKind::Tab) => IndentSize::tab(),
 8511            };
 8512
 8513            let start = if has_multiple_rows || current_indent.len < selection.start.column {
 8514                0
 8515            } else {
 8516                selection.start.column
 8517            };
 8518            let row_start = Point::new(row, start);
 8519            edits.push((
 8520                row_start..row_start,
 8521                indent_delta.chars().collect::<String>(),
 8522            ));
 8523
 8524            // Update this selection's endpoints to reflect the indentation.
 8525            if row == selection.start.row {
 8526                selection.start.column += indent_delta.len;
 8527            }
 8528            if row == selection.end.row {
 8529                selection.end.column += indent_delta.len;
 8530                delta_for_end_row = indent_delta.len;
 8531            }
 8532        }
 8533
 8534        if selection.start.row == selection.end.row {
 8535            delta_for_start_row + delta_for_end_row
 8536        } else {
 8537            delta_for_end_row
 8538        }
 8539    }
 8540
 8541    pub fn outdent(&mut self, _: &Outdent, window: &mut Window, cx: &mut Context<Self>) {
 8542        if self.read_only(cx) {
 8543            return;
 8544        }
 8545        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
 8546        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 8547        let selections = self.selections.all::<Point>(cx);
 8548        let mut deletion_ranges = Vec::new();
 8549        let mut last_outdent = None;
 8550        {
 8551            let buffer = self.buffer.read(cx);
 8552            let snapshot = buffer.snapshot(cx);
 8553            for selection in &selections {
 8554                let settings = buffer.language_settings_at(selection.start, cx);
 8555                let tab_size = settings.tab_size.get();
 8556                let mut rows = selection.spanned_rows(false, &display_map);
 8557
 8558                // Avoid re-outdenting a row that has already been outdented by a
 8559                // previous selection.
 8560                if let Some(last_row) = last_outdent {
 8561                    if last_row == rows.start {
 8562                        rows.start = rows.start.next_row();
 8563                    }
 8564                }
 8565                let has_multiple_rows = rows.len() > 1;
 8566                for row in rows.iter_rows() {
 8567                    let indent_size = snapshot.indent_size_for_line(row);
 8568                    if indent_size.len > 0 {
 8569                        let deletion_len = match indent_size.kind {
 8570                            IndentKind::Space => {
 8571                                let columns_to_prev_tab_stop = indent_size.len % tab_size;
 8572                                if columns_to_prev_tab_stop == 0 {
 8573                                    tab_size
 8574                                } else {
 8575                                    columns_to_prev_tab_stop
 8576                                }
 8577                            }
 8578                            IndentKind::Tab => 1,
 8579                        };
 8580                        let start = if has_multiple_rows
 8581                            || deletion_len > selection.start.column
 8582                            || indent_size.len < selection.start.column
 8583                        {
 8584                            0
 8585                        } else {
 8586                            selection.start.column - deletion_len
 8587                        };
 8588                        deletion_ranges.push(
 8589                            Point::new(row.0, start)..Point::new(row.0, start + deletion_len),
 8590                        );
 8591                        last_outdent = Some(row);
 8592                    }
 8593                }
 8594            }
 8595        }
 8596
 8597        self.transact(window, cx, |this, window, cx| {
 8598            this.buffer.update(cx, |buffer, cx| {
 8599                let empty_str: Arc<str> = Arc::default();
 8600                buffer.edit(
 8601                    deletion_ranges
 8602                        .into_iter()
 8603                        .map(|range| (range, empty_str.clone())),
 8604                    None,
 8605                    cx,
 8606                );
 8607            });
 8608            let selections = this.selections.all::<usize>(cx);
 8609            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8610                s.select(selections)
 8611            });
 8612        });
 8613    }
 8614
 8615    pub fn autoindent(&mut self, _: &AutoIndent, window: &mut Window, cx: &mut Context<Self>) {
 8616        if self.read_only(cx) {
 8617            return;
 8618        }
 8619        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
 8620        let selections = self
 8621            .selections
 8622            .all::<usize>(cx)
 8623            .into_iter()
 8624            .map(|s| s.range());
 8625
 8626        self.transact(window, cx, |this, window, cx| {
 8627            this.buffer.update(cx, |buffer, cx| {
 8628                buffer.autoindent_ranges(selections, cx);
 8629            });
 8630            let selections = this.selections.all::<usize>(cx);
 8631            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8632                s.select(selections)
 8633            });
 8634        });
 8635    }
 8636
 8637    pub fn delete_line(&mut self, _: &DeleteLine, window: &mut Window, cx: &mut Context<Self>) {
 8638        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
 8639        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 8640        let selections = self.selections.all::<Point>(cx);
 8641
 8642        let mut new_cursors = Vec::new();
 8643        let mut edit_ranges = Vec::new();
 8644        let mut selections = selections.iter().peekable();
 8645        while let Some(selection) = selections.next() {
 8646            let mut rows = selection.spanned_rows(false, &display_map);
 8647            let goal_display_column = selection.head().to_display_point(&display_map).column();
 8648
 8649            // Accumulate contiguous regions of rows that we want to delete.
 8650            while let Some(next_selection) = selections.peek() {
 8651                let next_rows = next_selection.spanned_rows(false, &display_map);
 8652                if next_rows.start <= rows.end {
 8653                    rows.end = next_rows.end;
 8654                    selections.next().unwrap();
 8655                } else {
 8656                    break;
 8657                }
 8658            }
 8659
 8660            let buffer = &display_map.buffer_snapshot;
 8661            let mut edit_start = Point::new(rows.start.0, 0).to_offset(buffer);
 8662            let edit_end;
 8663            let cursor_buffer_row;
 8664            if buffer.max_point().row >= rows.end.0 {
 8665                // If there's a line after the range, delete the \n from the end of the row range
 8666                // and position the cursor on the next line.
 8667                edit_end = Point::new(rows.end.0, 0).to_offset(buffer);
 8668                cursor_buffer_row = rows.end;
 8669            } else {
 8670                // If there isn't a line after the range, delete the \n from the line before the
 8671                // start of the row range and position the cursor there.
 8672                edit_start = edit_start.saturating_sub(1);
 8673                edit_end = buffer.len();
 8674                cursor_buffer_row = rows.start.previous_row();
 8675            }
 8676
 8677            let mut cursor = Point::new(cursor_buffer_row.0, 0).to_display_point(&display_map);
 8678            *cursor.column_mut() =
 8679                cmp::min(goal_display_column, display_map.line_len(cursor.row()));
 8680
 8681            new_cursors.push((
 8682                selection.id,
 8683                buffer.anchor_after(cursor.to_point(&display_map)),
 8684            ));
 8685            edit_ranges.push(edit_start..edit_end);
 8686        }
 8687
 8688        self.transact(window, cx, |this, window, cx| {
 8689            let buffer = this.buffer.update(cx, |buffer, cx| {
 8690                let empty_str: Arc<str> = Arc::default();
 8691                buffer.edit(
 8692                    edit_ranges
 8693                        .into_iter()
 8694                        .map(|range| (range, empty_str.clone())),
 8695                    None,
 8696                    cx,
 8697                );
 8698                buffer.snapshot(cx)
 8699            });
 8700            let new_selections = new_cursors
 8701                .into_iter()
 8702                .map(|(id, cursor)| {
 8703                    let cursor = cursor.to_point(&buffer);
 8704                    Selection {
 8705                        id,
 8706                        start: cursor,
 8707                        end: cursor,
 8708                        reversed: false,
 8709                        goal: SelectionGoal::None,
 8710                    }
 8711                })
 8712                .collect();
 8713
 8714            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8715                s.select(new_selections);
 8716            });
 8717        });
 8718    }
 8719
 8720    pub fn join_lines_impl(
 8721        &mut self,
 8722        insert_whitespace: bool,
 8723        window: &mut Window,
 8724        cx: &mut Context<Self>,
 8725    ) {
 8726        if self.read_only(cx) {
 8727            return;
 8728        }
 8729        let mut row_ranges = Vec::<Range<MultiBufferRow>>::new();
 8730        for selection in self.selections.all::<Point>(cx) {
 8731            let start = MultiBufferRow(selection.start.row);
 8732            // Treat single line selections as if they include the next line. Otherwise this action
 8733            // would do nothing for single line selections individual cursors.
 8734            let end = if selection.start.row == selection.end.row {
 8735                MultiBufferRow(selection.start.row + 1)
 8736            } else {
 8737                MultiBufferRow(selection.end.row)
 8738            };
 8739
 8740            if let Some(last_row_range) = row_ranges.last_mut() {
 8741                if start <= last_row_range.end {
 8742                    last_row_range.end = end;
 8743                    continue;
 8744                }
 8745            }
 8746            row_ranges.push(start..end);
 8747        }
 8748
 8749        let snapshot = self.buffer.read(cx).snapshot(cx);
 8750        let mut cursor_positions = Vec::new();
 8751        for row_range in &row_ranges {
 8752            let anchor = snapshot.anchor_before(Point::new(
 8753                row_range.end.previous_row().0,
 8754                snapshot.line_len(row_range.end.previous_row()),
 8755            ));
 8756            cursor_positions.push(anchor..anchor);
 8757        }
 8758
 8759        self.transact(window, cx, |this, window, cx| {
 8760            for row_range in row_ranges.into_iter().rev() {
 8761                for row in row_range.iter_rows().rev() {
 8762                    let end_of_line = Point::new(row.0, snapshot.line_len(row));
 8763                    let next_line_row = row.next_row();
 8764                    let indent = snapshot.indent_size_for_line(next_line_row);
 8765                    let start_of_next_line = Point::new(next_line_row.0, indent.len);
 8766
 8767                    let replace =
 8768                        if snapshot.line_len(next_line_row) > indent.len && insert_whitespace {
 8769                            " "
 8770                        } else {
 8771                            ""
 8772                        };
 8773
 8774                    this.buffer.update(cx, |buffer, cx| {
 8775                        buffer.edit([(end_of_line..start_of_next_line, replace)], None, cx)
 8776                    });
 8777                }
 8778            }
 8779
 8780            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8781                s.select_anchor_ranges(cursor_positions)
 8782            });
 8783        });
 8784    }
 8785
 8786    pub fn join_lines(&mut self, _: &JoinLines, window: &mut Window, cx: &mut Context<Self>) {
 8787        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
 8788        self.join_lines_impl(true, window, cx);
 8789    }
 8790
 8791    pub fn sort_lines_case_sensitive(
 8792        &mut self,
 8793        _: &SortLinesCaseSensitive,
 8794        window: &mut Window,
 8795        cx: &mut Context<Self>,
 8796    ) {
 8797        self.manipulate_lines(window, cx, |lines| lines.sort())
 8798    }
 8799
 8800    pub fn sort_lines_case_insensitive(
 8801        &mut self,
 8802        _: &SortLinesCaseInsensitive,
 8803        window: &mut Window,
 8804        cx: &mut Context<Self>,
 8805    ) {
 8806        self.manipulate_lines(window, cx, |lines| {
 8807            lines.sort_by_key(|line| line.to_lowercase())
 8808        })
 8809    }
 8810
 8811    pub fn unique_lines_case_insensitive(
 8812        &mut self,
 8813        _: &UniqueLinesCaseInsensitive,
 8814        window: &mut Window,
 8815        cx: &mut Context<Self>,
 8816    ) {
 8817        self.manipulate_lines(window, cx, |lines| {
 8818            let mut seen = HashSet::default();
 8819            lines.retain(|line| seen.insert(line.to_lowercase()));
 8820        })
 8821    }
 8822
 8823    pub fn unique_lines_case_sensitive(
 8824        &mut self,
 8825        _: &UniqueLinesCaseSensitive,
 8826        window: &mut Window,
 8827        cx: &mut Context<Self>,
 8828    ) {
 8829        self.manipulate_lines(window, cx, |lines| {
 8830            let mut seen = HashSet::default();
 8831            lines.retain(|line| seen.insert(*line));
 8832        })
 8833    }
 8834
 8835    pub fn reload_file(&mut self, _: &ReloadFile, window: &mut Window, cx: &mut Context<Self>) {
 8836        let Some(project) = self.project.clone() else {
 8837            return;
 8838        };
 8839        self.reload(project, window, cx)
 8840            .detach_and_notify_err(window, cx);
 8841    }
 8842
 8843    pub fn restore_file(
 8844        &mut self,
 8845        _: &::git::RestoreFile,
 8846        window: &mut Window,
 8847        cx: &mut Context<Self>,
 8848    ) {
 8849        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
 8850        let mut buffer_ids = HashSet::default();
 8851        let snapshot = self.buffer().read(cx).snapshot(cx);
 8852        for selection in self.selections.all::<usize>(cx) {
 8853            buffer_ids.extend(snapshot.buffer_ids_for_range(selection.range()))
 8854        }
 8855
 8856        let buffer = self.buffer().read(cx);
 8857        let ranges = buffer_ids
 8858            .into_iter()
 8859            .flat_map(|buffer_id| buffer.excerpt_ranges_for_buffer(buffer_id, cx))
 8860            .collect::<Vec<_>>();
 8861
 8862        self.restore_hunks_in_ranges(ranges, window, cx);
 8863    }
 8864
 8865    pub fn git_restore(&mut self, _: &Restore, window: &mut Window, cx: &mut Context<Self>) {
 8866        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
 8867        let selections = self
 8868            .selections
 8869            .all(cx)
 8870            .into_iter()
 8871            .map(|s| s.range())
 8872            .collect();
 8873        self.restore_hunks_in_ranges(selections, window, cx);
 8874    }
 8875
 8876    pub fn restore_hunks_in_ranges(
 8877        &mut self,
 8878        ranges: Vec<Range<Point>>,
 8879        window: &mut Window,
 8880        cx: &mut Context<Editor>,
 8881    ) {
 8882        let mut revert_changes = HashMap::default();
 8883        let chunk_by = self
 8884            .snapshot(window, cx)
 8885            .hunks_for_ranges(ranges)
 8886            .into_iter()
 8887            .chunk_by(|hunk| hunk.buffer_id);
 8888        for (buffer_id, hunks) in &chunk_by {
 8889            let hunks = hunks.collect::<Vec<_>>();
 8890            for hunk in &hunks {
 8891                self.prepare_restore_change(&mut revert_changes, hunk, cx);
 8892            }
 8893            self.do_stage_or_unstage(false, buffer_id, hunks.into_iter(), cx);
 8894        }
 8895        drop(chunk_by);
 8896        if !revert_changes.is_empty() {
 8897            self.transact(window, cx, |editor, window, cx| {
 8898                editor.restore(revert_changes, window, cx);
 8899            });
 8900        }
 8901    }
 8902
 8903    pub fn open_active_item_in_terminal(
 8904        &mut self,
 8905        _: &OpenInTerminal,
 8906        window: &mut Window,
 8907        cx: &mut Context<Self>,
 8908    ) {
 8909        if let Some(working_directory) = self.active_excerpt(cx).and_then(|(_, buffer, _)| {
 8910            let project_path = buffer.read(cx).project_path(cx)?;
 8911            let project = self.project.as_ref()?.read(cx);
 8912            let entry = project.entry_for_path(&project_path, cx)?;
 8913            let parent = match &entry.canonical_path {
 8914                Some(canonical_path) => canonical_path.to_path_buf(),
 8915                None => project.absolute_path(&project_path, cx)?,
 8916            }
 8917            .parent()?
 8918            .to_path_buf();
 8919            Some(parent)
 8920        }) {
 8921            window.dispatch_action(OpenTerminal { working_directory }.boxed_clone(), cx);
 8922        }
 8923    }
 8924
 8925    fn set_breakpoint_context_menu(
 8926        &mut self,
 8927        display_row: DisplayRow,
 8928        position: Option<Anchor>,
 8929        clicked_point: gpui::Point<Pixels>,
 8930        window: &mut Window,
 8931        cx: &mut Context<Self>,
 8932    ) {
 8933        if !cx.has_flag::<Debugger>() {
 8934            return;
 8935        }
 8936        let source = self
 8937            .buffer
 8938            .read(cx)
 8939            .snapshot(cx)
 8940            .anchor_before(Point::new(display_row.0, 0u32));
 8941
 8942        let context_menu = self.breakpoint_context_menu(position.unwrap_or(source), window, cx);
 8943
 8944        self.mouse_context_menu = MouseContextMenu::pinned_to_editor(
 8945            self,
 8946            source,
 8947            clicked_point,
 8948            context_menu,
 8949            window,
 8950            cx,
 8951        );
 8952    }
 8953
 8954    fn add_edit_breakpoint_block(
 8955        &mut self,
 8956        anchor: Anchor,
 8957        breakpoint: &Breakpoint,
 8958        edit_action: BreakpointPromptEditAction,
 8959        window: &mut Window,
 8960        cx: &mut Context<Self>,
 8961    ) {
 8962        let weak_editor = cx.weak_entity();
 8963        let bp_prompt = cx.new(|cx| {
 8964            BreakpointPromptEditor::new(
 8965                weak_editor,
 8966                anchor,
 8967                breakpoint.clone(),
 8968                edit_action,
 8969                window,
 8970                cx,
 8971            )
 8972        });
 8973
 8974        let height = bp_prompt.update(cx, |this, cx| {
 8975            this.prompt
 8976                .update(cx, |prompt, cx| prompt.max_point(cx).row().0 + 1 + 2)
 8977        });
 8978        let cloned_prompt = bp_prompt.clone();
 8979        let blocks = vec![BlockProperties {
 8980            style: BlockStyle::Sticky,
 8981            placement: BlockPlacement::Above(anchor),
 8982            height: Some(height),
 8983            render: Arc::new(move |cx| {
 8984                *cloned_prompt.read(cx).gutter_dimensions.lock() = *cx.gutter_dimensions;
 8985                cloned_prompt.clone().into_any_element()
 8986            }),
 8987            priority: 0,
 8988        }];
 8989
 8990        let focus_handle = bp_prompt.focus_handle(cx);
 8991        window.focus(&focus_handle);
 8992
 8993        let block_ids = self.insert_blocks(blocks, None, cx);
 8994        bp_prompt.update(cx, |prompt, _| {
 8995            prompt.add_block_ids(block_ids);
 8996        });
 8997    }
 8998
 8999    pub(crate) fn breakpoint_at_row(
 9000        &self,
 9001        row: u32,
 9002        window: &mut Window,
 9003        cx: &mut Context<Self>,
 9004    ) -> Option<(Anchor, Breakpoint)> {
 9005        let snapshot = self.snapshot(window, cx);
 9006        let breakpoint_position = snapshot.buffer_snapshot.anchor_before(Point::new(row, 0));
 9007
 9008        self.breakpoint_at_anchor(breakpoint_position, &snapshot, cx)
 9009    }
 9010
 9011    pub(crate) fn breakpoint_at_anchor(
 9012        &self,
 9013        breakpoint_position: Anchor,
 9014        snapshot: &EditorSnapshot,
 9015        cx: &mut Context<Self>,
 9016    ) -> Option<(Anchor, Breakpoint)> {
 9017        let project = self.project.clone()?;
 9018
 9019        let buffer_id = breakpoint_position.buffer_id.or_else(|| {
 9020            snapshot
 9021                .buffer_snapshot
 9022                .buffer_id_for_excerpt(breakpoint_position.excerpt_id)
 9023        })?;
 9024
 9025        let enclosing_excerpt = breakpoint_position.excerpt_id;
 9026        let buffer = project.read_with(cx, |project, cx| project.buffer_for_id(buffer_id, cx))?;
 9027        let buffer_snapshot = buffer.read(cx).snapshot();
 9028
 9029        let row = buffer_snapshot
 9030            .summary_for_anchor::<text::PointUtf16>(&breakpoint_position.text_anchor)
 9031            .row;
 9032
 9033        let line_len = snapshot.buffer_snapshot.line_len(MultiBufferRow(row));
 9034        let anchor_end = snapshot
 9035            .buffer_snapshot
 9036            .anchor_after(Point::new(row, line_len));
 9037
 9038        let bp = self
 9039            .breakpoint_store
 9040            .as_ref()?
 9041            .read_with(cx, |breakpoint_store, cx| {
 9042                breakpoint_store
 9043                    .breakpoints(
 9044                        &buffer,
 9045                        Some(breakpoint_position.text_anchor..anchor_end.text_anchor),
 9046                        &buffer_snapshot,
 9047                        cx,
 9048                    )
 9049                    .next()
 9050                    .and_then(|(anchor, bp)| {
 9051                        let breakpoint_row = buffer_snapshot
 9052                            .summary_for_anchor::<text::PointUtf16>(anchor)
 9053                            .row;
 9054
 9055                        if breakpoint_row == row {
 9056                            snapshot
 9057                                .buffer_snapshot
 9058                                .anchor_in_excerpt(enclosing_excerpt, *anchor)
 9059                                .map(|anchor| (anchor, bp.clone()))
 9060                        } else {
 9061                            None
 9062                        }
 9063                    })
 9064            });
 9065        bp
 9066    }
 9067
 9068    pub fn edit_log_breakpoint(
 9069        &mut self,
 9070        _: &EditLogBreakpoint,
 9071        window: &mut Window,
 9072        cx: &mut Context<Self>,
 9073    ) {
 9074        for (anchor, breakpoint) in self.breakpoints_at_cursors(window, cx) {
 9075            let breakpoint = breakpoint.unwrap_or_else(|| Breakpoint {
 9076                message: None,
 9077                state: BreakpointState::Enabled,
 9078                condition: None,
 9079                hit_condition: None,
 9080            });
 9081
 9082            self.add_edit_breakpoint_block(
 9083                anchor,
 9084                &breakpoint,
 9085                BreakpointPromptEditAction::Log,
 9086                window,
 9087                cx,
 9088            );
 9089        }
 9090    }
 9091
 9092    fn breakpoints_at_cursors(
 9093        &self,
 9094        window: &mut Window,
 9095        cx: &mut Context<Self>,
 9096    ) -> Vec<(Anchor, Option<Breakpoint>)> {
 9097        let snapshot = self.snapshot(window, cx);
 9098        let cursors = self
 9099            .selections
 9100            .disjoint_anchors()
 9101            .into_iter()
 9102            .map(|selection| {
 9103                let cursor_position: Point = selection.head().to_point(&snapshot.buffer_snapshot);
 9104
 9105                let breakpoint_position = self
 9106                    .breakpoint_at_row(cursor_position.row, window, cx)
 9107                    .map(|bp| bp.0)
 9108                    .unwrap_or_else(|| {
 9109                        snapshot
 9110                            .display_snapshot
 9111                            .buffer_snapshot
 9112                            .anchor_after(Point::new(cursor_position.row, 0))
 9113                    });
 9114
 9115                let breakpoint = self
 9116                    .breakpoint_at_anchor(breakpoint_position, &snapshot, cx)
 9117                    .map(|(anchor, breakpoint)| (anchor, Some(breakpoint)));
 9118
 9119                breakpoint.unwrap_or_else(|| (breakpoint_position, None))
 9120            })
 9121            // 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.
 9122            .collect::<HashMap<Anchor, _>>();
 9123
 9124        cursors.into_iter().collect()
 9125    }
 9126
 9127    pub fn enable_breakpoint(
 9128        &mut self,
 9129        _: &crate::actions::EnableBreakpoint,
 9130        window: &mut Window,
 9131        cx: &mut Context<Self>,
 9132    ) {
 9133        for (anchor, breakpoint) in self.breakpoints_at_cursors(window, cx) {
 9134            let Some(breakpoint) = breakpoint.filter(|breakpoint| breakpoint.is_disabled()) else {
 9135                continue;
 9136            };
 9137            self.edit_breakpoint_at_anchor(
 9138                anchor,
 9139                breakpoint,
 9140                BreakpointEditAction::InvertState,
 9141                cx,
 9142            );
 9143        }
 9144    }
 9145
 9146    pub fn disable_breakpoint(
 9147        &mut self,
 9148        _: &crate::actions::DisableBreakpoint,
 9149        window: &mut Window,
 9150        cx: &mut Context<Self>,
 9151    ) {
 9152        for (anchor, breakpoint) in self.breakpoints_at_cursors(window, cx) {
 9153            let Some(breakpoint) = breakpoint.filter(|breakpoint| breakpoint.is_enabled()) else {
 9154                continue;
 9155            };
 9156            self.edit_breakpoint_at_anchor(
 9157                anchor,
 9158                breakpoint,
 9159                BreakpointEditAction::InvertState,
 9160                cx,
 9161            );
 9162        }
 9163    }
 9164
 9165    pub fn toggle_breakpoint(
 9166        &mut self,
 9167        _: &crate::actions::ToggleBreakpoint,
 9168        window: &mut Window,
 9169        cx: &mut Context<Self>,
 9170    ) {
 9171        for (anchor, breakpoint) in self.breakpoints_at_cursors(window, cx) {
 9172            if let Some(breakpoint) = breakpoint {
 9173                self.edit_breakpoint_at_anchor(
 9174                    anchor,
 9175                    breakpoint,
 9176                    BreakpointEditAction::Toggle,
 9177                    cx,
 9178                );
 9179            } else {
 9180                self.edit_breakpoint_at_anchor(
 9181                    anchor,
 9182                    Breakpoint::new_standard(),
 9183                    BreakpointEditAction::Toggle,
 9184                    cx,
 9185                );
 9186            }
 9187        }
 9188    }
 9189
 9190    pub fn edit_breakpoint_at_anchor(
 9191        &mut self,
 9192        breakpoint_position: Anchor,
 9193        breakpoint: Breakpoint,
 9194        edit_action: BreakpointEditAction,
 9195        cx: &mut Context<Self>,
 9196    ) {
 9197        let Some(breakpoint_store) = &self.breakpoint_store else {
 9198            return;
 9199        };
 9200
 9201        let Some(buffer_id) = breakpoint_position.buffer_id.or_else(|| {
 9202            if breakpoint_position == Anchor::min() {
 9203                self.buffer()
 9204                    .read(cx)
 9205                    .excerpt_buffer_ids()
 9206                    .into_iter()
 9207                    .next()
 9208            } else {
 9209                None
 9210            }
 9211        }) else {
 9212            return;
 9213        };
 9214
 9215        let Some(buffer) = self.buffer().read(cx).buffer(buffer_id) else {
 9216            return;
 9217        };
 9218
 9219        breakpoint_store.update(cx, |breakpoint_store, cx| {
 9220            breakpoint_store.toggle_breakpoint(
 9221                buffer,
 9222                (breakpoint_position.text_anchor, breakpoint),
 9223                edit_action,
 9224                cx,
 9225            );
 9226        });
 9227
 9228        cx.notify();
 9229    }
 9230
 9231    #[cfg(any(test, feature = "test-support"))]
 9232    pub fn breakpoint_store(&self) -> Option<Entity<BreakpointStore>> {
 9233        self.breakpoint_store.clone()
 9234    }
 9235
 9236    pub fn prepare_restore_change(
 9237        &self,
 9238        revert_changes: &mut HashMap<BufferId, Vec<(Range<text::Anchor>, Rope)>>,
 9239        hunk: &MultiBufferDiffHunk,
 9240        cx: &mut App,
 9241    ) -> Option<()> {
 9242        if hunk.is_created_file() {
 9243            return None;
 9244        }
 9245        let buffer = self.buffer.read(cx);
 9246        let diff = buffer.diff_for(hunk.buffer_id)?;
 9247        let buffer = buffer.buffer(hunk.buffer_id)?;
 9248        let buffer = buffer.read(cx);
 9249        let original_text = diff
 9250            .read(cx)
 9251            .base_text()
 9252            .as_rope()
 9253            .slice(hunk.diff_base_byte_range.clone());
 9254        let buffer_snapshot = buffer.snapshot();
 9255        let buffer_revert_changes = revert_changes.entry(buffer.remote_id()).or_default();
 9256        if let Err(i) = buffer_revert_changes.binary_search_by(|probe| {
 9257            probe
 9258                .0
 9259                .start
 9260                .cmp(&hunk.buffer_range.start, &buffer_snapshot)
 9261                .then(probe.0.end.cmp(&hunk.buffer_range.end, &buffer_snapshot))
 9262        }) {
 9263            buffer_revert_changes.insert(i, (hunk.buffer_range.clone(), original_text));
 9264            Some(())
 9265        } else {
 9266            None
 9267        }
 9268    }
 9269
 9270    pub fn reverse_lines(&mut self, _: &ReverseLines, window: &mut Window, cx: &mut Context<Self>) {
 9271        self.manipulate_lines(window, cx, |lines| lines.reverse())
 9272    }
 9273
 9274    pub fn shuffle_lines(&mut self, _: &ShuffleLines, window: &mut Window, cx: &mut Context<Self>) {
 9275        self.manipulate_lines(window, cx, |lines| lines.shuffle(&mut thread_rng()))
 9276    }
 9277
 9278    fn manipulate_lines<Fn>(
 9279        &mut self,
 9280        window: &mut Window,
 9281        cx: &mut Context<Self>,
 9282        mut callback: Fn,
 9283    ) where
 9284        Fn: FnMut(&mut Vec<&str>),
 9285    {
 9286        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
 9287
 9288        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 9289        let buffer = self.buffer.read(cx).snapshot(cx);
 9290
 9291        let mut edits = Vec::new();
 9292
 9293        let selections = self.selections.all::<Point>(cx);
 9294        let mut selections = selections.iter().peekable();
 9295        let mut contiguous_row_selections = Vec::new();
 9296        let mut new_selections = Vec::new();
 9297        let mut added_lines = 0;
 9298        let mut removed_lines = 0;
 9299
 9300        while let Some(selection) = selections.next() {
 9301            let (start_row, end_row) = consume_contiguous_rows(
 9302                &mut contiguous_row_selections,
 9303                selection,
 9304                &display_map,
 9305                &mut selections,
 9306            );
 9307
 9308            let start_point = Point::new(start_row.0, 0);
 9309            let end_point = Point::new(
 9310                end_row.previous_row().0,
 9311                buffer.line_len(end_row.previous_row()),
 9312            );
 9313            let text = buffer
 9314                .text_for_range(start_point..end_point)
 9315                .collect::<String>();
 9316
 9317            let mut lines = text.split('\n').collect_vec();
 9318
 9319            let lines_before = lines.len();
 9320            callback(&mut lines);
 9321            let lines_after = lines.len();
 9322
 9323            edits.push((start_point..end_point, lines.join("\n")));
 9324
 9325            // Selections must change based on added and removed line count
 9326            let start_row =
 9327                MultiBufferRow(start_point.row + added_lines as u32 - removed_lines as u32);
 9328            let end_row = MultiBufferRow(start_row.0 + lines_after.saturating_sub(1) as u32);
 9329            new_selections.push(Selection {
 9330                id: selection.id,
 9331                start: start_row,
 9332                end: end_row,
 9333                goal: SelectionGoal::None,
 9334                reversed: selection.reversed,
 9335            });
 9336
 9337            if lines_after > lines_before {
 9338                added_lines += lines_after - lines_before;
 9339            } else if lines_before > lines_after {
 9340                removed_lines += lines_before - lines_after;
 9341            }
 9342        }
 9343
 9344        self.transact(window, cx, |this, window, cx| {
 9345            let buffer = this.buffer.update(cx, |buffer, cx| {
 9346                buffer.edit(edits, None, cx);
 9347                buffer.snapshot(cx)
 9348            });
 9349
 9350            // Recalculate offsets on newly edited buffer
 9351            let new_selections = new_selections
 9352                .iter()
 9353                .map(|s| {
 9354                    let start_point = Point::new(s.start.0, 0);
 9355                    let end_point = Point::new(s.end.0, buffer.line_len(s.end));
 9356                    Selection {
 9357                        id: s.id,
 9358                        start: buffer.point_to_offset(start_point),
 9359                        end: buffer.point_to_offset(end_point),
 9360                        goal: s.goal,
 9361                        reversed: s.reversed,
 9362                    }
 9363                })
 9364                .collect();
 9365
 9366            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9367                s.select(new_selections);
 9368            });
 9369
 9370            this.request_autoscroll(Autoscroll::fit(), cx);
 9371        });
 9372    }
 9373
 9374    pub fn toggle_case(&mut self, _: &ToggleCase, window: &mut Window, cx: &mut Context<Self>) {
 9375        self.manipulate_text(window, cx, |text| {
 9376            let has_upper_case_characters = text.chars().any(|c| c.is_uppercase());
 9377            if has_upper_case_characters {
 9378                text.to_lowercase()
 9379            } else {
 9380                text.to_uppercase()
 9381            }
 9382        })
 9383    }
 9384
 9385    pub fn convert_to_upper_case(
 9386        &mut self,
 9387        _: &ConvertToUpperCase,
 9388        window: &mut Window,
 9389        cx: &mut Context<Self>,
 9390    ) {
 9391        self.manipulate_text(window, cx, |text| text.to_uppercase())
 9392    }
 9393
 9394    pub fn convert_to_lower_case(
 9395        &mut self,
 9396        _: &ConvertToLowerCase,
 9397        window: &mut Window,
 9398        cx: &mut Context<Self>,
 9399    ) {
 9400        self.manipulate_text(window, cx, |text| text.to_lowercase())
 9401    }
 9402
 9403    pub fn convert_to_title_case(
 9404        &mut self,
 9405        _: &ConvertToTitleCase,
 9406        window: &mut Window,
 9407        cx: &mut Context<Self>,
 9408    ) {
 9409        self.manipulate_text(window, cx, |text| {
 9410            text.split('\n')
 9411                .map(|line| line.to_case(Case::Title))
 9412                .join("\n")
 9413        })
 9414    }
 9415
 9416    pub fn convert_to_snake_case(
 9417        &mut self,
 9418        _: &ConvertToSnakeCase,
 9419        window: &mut Window,
 9420        cx: &mut Context<Self>,
 9421    ) {
 9422        self.manipulate_text(window, cx, |text| text.to_case(Case::Snake))
 9423    }
 9424
 9425    pub fn convert_to_kebab_case(
 9426        &mut self,
 9427        _: &ConvertToKebabCase,
 9428        window: &mut Window,
 9429        cx: &mut Context<Self>,
 9430    ) {
 9431        self.manipulate_text(window, cx, |text| text.to_case(Case::Kebab))
 9432    }
 9433
 9434    pub fn convert_to_upper_camel_case(
 9435        &mut self,
 9436        _: &ConvertToUpperCamelCase,
 9437        window: &mut Window,
 9438        cx: &mut Context<Self>,
 9439    ) {
 9440        self.manipulate_text(window, cx, |text| {
 9441            text.split('\n')
 9442                .map(|line| line.to_case(Case::UpperCamel))
 9443                .join("\n")
 9444        })
 9445    }
 9446
 9447    pub fn convert_to_lower_camel_case(
 9448        &mut self,
 9449        _: &ConvertToLowerCamelCase,
 9450        window: &mut Window,
 9451        cx: &mut Context<Self>,
 9452    ) {
 9453        self.manipulate_text(window, cx, |text| text.to_case(Case::Camel))
 9454    }
 9455
 9456    pub fn convert_to_opposite_case(
 9457        &mut self,
 9458        _: &ConvertToOppositeCase,
 9459        window: &mut Window,
 9460        cx: &mut Context<Self>,
 9461    ) {
 9462        self.manipulate_text(window, cx, |text| {
 9463            text.chars()
 9464                .fold(String::with_capacity(text.len()), |mut t, c| {
 9465                    if c.is_uppercase() {
 9466                        t.extend(c.to_lowercase());
 9467                    } else {
 9468                        t.extend(c.to_uppercase());
 9469                    }
 9470                    t
 9471                })
 9472        })
 9473    }
 9474
 9475    pub fn convert_to_rot13(
 9476        &mut self,
 9477        _: &ConvertToRot13,
 9478        window: &mut Window,
 9479        cx: &mut Context<Self>,
 9480    ) {
 9481        self.manipulate_text(window, cx, |text| {
 9482            text.chars()
 9483                .map(|c| match c {
 9484                    'A'..='M' | 'a'..='m' => ((c as u8) + 13) as char,
 9485                    'N'..='Z' | 'n'..='z' => ((c as u8) - 13) as char,
 9486                    _ => c,
 9487                })
 9488                .collect()
 9489        })
 9490    }
 9491
 9492    pub fn convert_to_rot47(
 9493        &mut self,
 9494        _: &ConvertToRot47,
 9495        window: &mut Window,
 9496        cx: &mut Context<Self>,
 9497    ) {
 9498        self.manipulate_text(window, cx, |text| {
 9499            text.chars()
 9500                .map(|c| {
 9501                    let code_point = c as u32;
 9502                    if code_point >= 33 && code_point <= 126 {
 9503                        return char::from_u32(33 + ((code_point + 14) % 94)).unwrap();
 9504                    }
 9505                    c
 9506                })
 9507                .collect()
 9508        })
 9509    }
 9510
 9511    fn manipulate_text<Fn>(&mut self, window: &mut Window, cx: &mut Context<Self>, mut callback: Fn)
 9512    where
 9513        Fn: FnMut(&str) -> String,
 9514    {
 9515        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 9516        let buffer = self.buffer.read(cx).snapshot(cx);
 9517
 9518        let mut new_selections = Vec::new();
 9519        let mut edits = Vec::new();
 9520        let mut selection_adjustment = 0i32;
 9521
 9522        for selection in self.selections.all::<usize>(cx) {
 9523            let selection_is_empty = selection.is_empty();
 9524
 9525            let (start, end) = if selection_is_empty {
 9526                let word_range = movement::surrounding_word(
 9527                    &display_map,
 9528                    selection.start.to_display_point(&display_map),
 9529                );
 9530                let start = word_range.start.to_offset(&display_map, Bias::Left);
 9531                let end = word_range.end.to_offset(&display_map, Bias::Left);
 9532                (start, end)
 9533            } else {
 9534                (selection.start, selection.end)
 9535            };
 9536
 9537            let text = buffer.text_for_range(start..end).collect::<String>();
 9538            let old_length = text.len() as i32;
 9539            let text = callback(&text);
 9540
 9541            new_selections.push(Selection {
 9542                start: (start as i32 - selection_adjustment) as usize,
 9543                end: ((start + text.len()) as i32 - selection_adjustment) as usize,
 9544                goal: SelectionGoal::None,
 9545                ..selection
 9546            });
 9547
 9548            selection_adjustment += old_length - text.len() as i32;
 9549
 9550            edits.push((start..end, text));
 9551        }
 9552
 9553        self.transact(window, cx, |this, window, cx| {
 9554            this.buffer.update(cx, |buffer, cx| {
 9555                buffer.edit(edits, None, cx);
 9556            });
 9557
 9558            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9559                s.select(new_selections);
 9560            });
 9561
 9562            this.request_autoscroll(Autoscroll::fit(), cx);
 9563        });
 9564    }
 9565
 9566    pub fn duplicate(
 9567        &mut self,
 9568        upwards: bool,
 9569        whole_lines: bool,
 9570        window: &mut Window,
 9571        cx: &mut Context<Self>,
 9572    ) {
 9573        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
 9574
 9575        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 9576        let buffer = &display_map.buffer_snapshot;
 9577        let selections = self.selections.all::<Point>(cx);
 9578
 9579        let mut edits = Vec::new();
 9580        let mut selections_iter = selections.iter().peekable();
 9581        while let Some(selection) = selections_iter.next() {
 9582            let mut rows = selection.spanned_rows(false, &display_map);
 9583            // duplicate line-wise
 9584            if whole_lines || selection.start == selection.end {
 9585                // Avoid duplicating the same lines twice.
 9586                while let Some(next_selection) = selections_iter.peek() {
 9587                    let next_rows = next_selection.spanned_rows(false, &display_map);
 9588                    if next_rows.start < rows.end {
 9589                        rows.end = next_rows.end;
 9590                        selections_iter.next().unwrap();
 9591                    } else {
 9592                        break;
 9593                    }
 9594                }
 9595
 9596                // Copy the text from the selected row region and splice it either at the start
 9597                // or end of the region.
 9598                let start = Point::new(rows.start.0, 0);
 9599                let end = Point::new(
 9600                    rows.end.previous_row().0,
 9601                    buffer.line_len(rows.end.previous_row()),
 9602                );
 9603                let text = buffer
 9604                    .text_for_range(start..end)
 9605                    .chain(Some("\n"))
 9606                    .collect::<String>();
 9607                let insert_location = if upwards {
 9608                    Point::new(rows.end.0, 0)
 9609                } else {
 9610                    start
 9611                };
 9612                edits.push((insert_location..insert_location, text));
 9613            } else {
 9614                // duplicate character-wise
 9615                let start = selection.start;
 9616                let end = selection.end;
 9617                let text = buffer.text_for_range(start..end).collect::<String>();
 9618                edits.push((selection.end..selection.end, text));
 9619            }
 9620        }
 9621
 9622        self.transact(window, cx, |this, _, cx| {
 9623            this.buffer.update(cx, |buffer, cx| {
 9624                buffer.edit(edits, None, cx);
 9625            });
 9626
 9627            this.request_autoscroll(Autoscroll::fit(), cx);
 9628        });
 9629    }
 9630
 9631    pub fn duplicate_line_up(
 9632        &mut self,
 9633        _: &DuplicateLineUp,
 9634        window: &mut Window,
 9635        cx: &mut Context<Self>,
 9636    ) {
 9637        self.duplicate(true, true, window, cx);
 9638    }
 9639
 9640    pub fn duplicate_line_down(
 9641        &mut self,
 9642        _: &DuplicateLineDown,
 9643        window: &mut Window,
 9644        cx: &mut Context<Self>,
 9645    ) {
 9646        self.duplicate(false, true, window, cx);
 9647    }
 9648
 9649    pub fn duplicate_selection(
 9650        &mut self,
 9651        _: &DuplicateSelection,
 9652        window: &mut Window,
 9653        cx: &mut Context<Self>,
 9654    ) {
 9655        self.duplicate(false, false, window, cx);
 9656    }
 9657
 9658    pub fn move_line_up(&mut self, _: &MoveLineUp, window: &mut Window, cx: &mut Context<Self>) {
 9659        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
 9660
 9661        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 9662        let buffer = self.buffer.read(cx).snapshot(cx);
 9663
 9664        let mut edits = Vec::new();
 9665        let mut unfold_ranges = Vec::new();
 9666        let mut refold_creases = Vec::new();
 9667
 9668        let selections = self.selections.all::<Point>(cx);
 9669        let mut selections = selections.iter().peekable();
 9670        let mut contiguous_row_selections = Vec::new();
 9671        let mut new_selections = Vec::new();
 9672
 9673        while let Some(selection) = selections.next() {
 9674            // Find all the selections that span a contiguous row range
 9675            let (start_row, end_row) = consume_contiguous_rows(
 9676                &mut contiguous_row_selections,
 9677                selection,
 9678                &display_map,
 9679                &mut selections,
 9680            );
 9681
 9682            // Move the text spanned by the row range to be before the line preceding the row range
 9683            if start_row.0 > 0 {
 9684                let range_to_move = Point::new(
 9685                    start_row.previous_row().0,
 9686                    buffer.line_len(start_row.previous_row()),
 9687                )
 9688                    ..Point::new(
 9689                        end_row.previous_row().0,
 9690                        buffer.line_len(end_row.previous_row()),
 9691                    );
 9692                let insertion_point = display_map
 9693                    .prev_line_boundary(Point::new(start_row.previous_row().0, 0))
 9694                    .0;
 9695
 9696                // Don't move lines across excerpts
 9697                if buffer
 9698                    .excerpt_containing(insertion_point..range_to_move.end)
 9699                    .is_some()
 9700                {
 9701                    let text = buffer
 9702                        .text_for_range(range_to_move.clone())
 9703                        .flat_map(|s| s.chars())
 9704                        .skip(1)
 9705                        .chain(['\n'])
 9706                        .collect::<String>();
 9707
 9708                    edits.push((
 9709                        buffer.anchor_after(range_to_move.start)
 9710                            ..buffer.anchor_before(range_to_move.end),
 9711                        String::new(),
 9712                    ));
 9713                    let insertion_anchor = buffer.anchor_after(insertion_point);
 9714                    edits.push((insertion_anchor..insertion_anchor, text));
 9715
 9716                    let row_delta = range_to_move.start.row - insertion_point.row + 1;
 9717
 9718                    // Move selections up
 9719                    new_selections.extend(contiguous_row_selections.drain(..).map(
 9720                        |mut selection| {
 9721                            selection.start.row -= row_delta;
 9722                            selection.end.row -= row_delta;
 9723                            selection
 9724                        },
 9725                    ));
 9726
 9727                    // Move folds up
 9728                    unfold_ranges.push(range_to_move.clone());
 9729                    for fold in display_map.folds_in_range(
 9730                        buffer.anchor_before(range_to_move.start)
 9731                            ..buffer.anchor_after(range_to_move.end),
 9732                    ) {
 9733                        let mut start = fold.range.start.to_point(&buffer);
 9734                        let mut end = fold.range.end.to_point(&buffer);
 9735                        start.row -= row_delta;
 9736                        end.row -= row_delta;
 9737                        refold_creases.push(Crease::simple(start..end, fold.placeholder.clone()));
 9738                    }
 9739                }
 9740            }
 9741
 9742            // If we didn't move line(s), preserve the existing selections
 9743            new_selections.append(&mut contiguous_row_selections);
 9744        }
 9745
 9746        self.transact(window, cx, |this, window, cx| {
 9747            this.unfold_ranges(&unfold_ranges, true, true, cx);
 9748            this.buffer.update(cx, |buffer, cx| {
 9749                for (range, text) in edits {
 9750                    buffer.edit([(range, text)], None, cx);
 9751                }
 9752            });
 9753            this.fold_creases(refold_creases, true, window, cx);
 9754            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9755                s.select(new_selections);
 9756            })
 9757        });
 9758    }
 9759
 9760    pub fn move_line_down(
 9761        &mut self,
 9762        _: &MoveLineDown,
 9763        window: &mut Window,
 9764        cx: &mut Context<Self>,
 9765    ) {
 9766        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
 9767
 9768        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 9769        let buffer = self.buffer.read(cx).snapshot(cx);
 9770
 9771        let mut edits = Vec::new();
 9772        let mut unfold_ranges = Vec::new();
 9773        let mut refold_creases = Vec::new();
 9774
 9775        let selections = self.selections.all::<Point>(cx);
 9776        let mut selections = selections.iter().peekable();
 9777        let mut contiguous_row_selections = Vec::new();
 9778        let mut new_selections = Vec::new();
 9779
 9780        while let Some(selection) = selections.next() {
 9781            // Find all the selections that span a contiguous row range
 9782            let (start_row, end_row) = consume_contiguous_rows(
 9783                &mut contiguous_row_selections,
 9784                selection,
 9785                &display_map,
 9786                &mut selections,
 9787            );
 9788
 9789            // Move the text spanned by the row range to be after the last line of the row range
 9790            if end_row.0 <= buffer.max_point().row {
 9791                let range_to_move =
 9792                    MultiBufferPoint::new(start_row.0, 0)..MultiBufferPoint::new(end_row.0, 0);
 9793                let insertion_point = display_map
 9794                    .next_line_boundary(MultiBufferPoint::new(end_row.0, 0))
 9795                    .0;
 9796
 9797                // Don't move lines across excerpt boundaries
 9798                if buffer
 9799                    .excerpt_containing(range_to_move.start..insertion_point)
 9800                    .is_some()
 9801                {
 9802                    let mut text = String::from("\n");
 9803                    text.extend(buffer.text_for_range(range_to_move.clone()));
 9804                    text.pop(); // Drop trailing newline
 9805                    edits.push((
 9806                        buffer.anchor_after(range_to_move.start)
 9807                            ..buffer.anchor_before(range_to_move.end),
 9808                        String::new(),
 9809                    ));
 9810                    let insertion_anchor = buffer.anchor_after(insertion_point);
 9811                    edits.push((insertion_anchor..insertion_anchor, text));
 9812
 9813                    let row_delta = insertion_point.row - range_to_move.end.row + 1;
 9814
 9815                    // Move selections down
 9816                    new_selections.extend(contiguous_row_selections.drain(..).map(
 9817                        |mut selection| {
 9818                            selection.start.row += row_delta;
 9819                            selection.end.row += row_delta;
 9820                            selection
 9821                        },
 9822                    ));
 9823
 9824                    // Move folds down
 9825                    unfold_ranges.push(range_to_move.clone());
 9826                    for fold in display_map.folds_in_range(
 9827                        buffer.anchor_before(range_to_move.start)
 9828                            ..buffer.anchor_after(range_to_move.end),
 9829                    ) {
 9830                        let mut start = fold.range.start.to_point(&buffer);
 9831                        let mut end = fold.range.end.to_point(&buffer);
 9832                        start.row += row_delta;
 9833                        end.row += row_delta;
 9834                        refold_creases.push(Crease::simple(start..end, fold.placeholder.clone()));
 9835                    }
 9836                }
 9837            }
 9838
 9839            // If we didn't move line(s), preserve the existing selections
 9840            new_selections.append(&mut contiguous_row_selections);
 9841        }
 9842
 9843        self.transact(window, cx, |this, window, cx| {
 9844            this.unfold_ranges(&unfold_ranges, true, true, cx);
 9845            this.buffer.update(cx, |buffer, cx| {
 9846                for (range, text) in edits {
 9847                    buffer.edit([(range, text)], None, cx);
 9848                }
 9849            });
 9850            this.fold_creases(refold_creases, true, window, cx);
 9851            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9852                s.select(new_selections)
 9853            });
 9854        });
 9855    }
 9856
 9857    pub fn transpose(&mut self, _: &Transpose, window: &mut Window, cx: &mut Context<Self>) {
 9858        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
 9859        let text_layout_details = &self.text_layout_details(window);
 9860        self.transact(window, cx, |this, window, cx| {
 9861            let edits = this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9862                let mut edits: Vec<(Range<usize>, String)> = Default::default();
 9863                s.move_with(|display_map, selection| {
 9864                    if !selection.is_empty() {
 9865                        return;
 9866                    }
 9867
 9868                    let mut head = selection.head();
 9869                    let mut transpose_offset = head.to_offset(display_map, Bias::Right);
 9870                    if head.column() == display_map.line_len(head.row()) {
 9871                        transpose_offset = display_map
 9872                            .buffer_snapshot
 9873                            .clip_offset(transpose_offset.saturating_sub(1), Bias::Left);
 9874                    }
 9875
 9876                    if transpose_offset == 0 {
 9877                        return;
 9878                    }
 9879
 9880                    *head.column_mut() += 1;
 9881                    head = display_map.clip_point(head, Bias::Right);
 9882                    let goal = SelectionGoal::HorizontalPosition(
 9883                        display_map
 9884                            .x_for_display_point(head, text_layout_details)
 9885                            .into(),
 9886                    );
 9887                    selection.collapse_to(head, goal);
 9888
 9889                    let transpose_start = display_map
 9890                        .buffer_snapshot
 9891                        .clip_offset(transpose_offset.saturating_sub(1), Bias::Left);
 9892                    if edits.last().map_or(true, |e| e.0.end <= transpose_start) {
 9893                        let transpose_end = display_map
 9894                            .buffer_snapshot
 9895                            .clip_offset(transpose_offset + 1, Bias::Right);
 9896                        if let Some(ch) =
 9897                            display_map.buffer_snapshot.chars_at(transpose_start).next()
 9898                        {
 9899                            edits.push((transpose_start..transpose_offset, String::new()));
 9900                            edits.push((transpose_end..transpose_end, ch.to_string()));
 9901                        }
 9902                    }
 9903                });
 9904                edits
 9905            });
 9906            this.buffer
 9907                .update(cx, |buffer, cx| buffer.edit(edits, None, cx));
 9908            let selections = this.selections.all::<usize>(cx);
 9909            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9910                s.select(selections);
 9911            });
 9912        });
 9913    }
 9914
 9915    pub fn rewrap(&mut self, _: &Rewrap, _: &mut Window, cx: &mut Context<Self>) {
 9916        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
 9917        self.rewrap_impl(RewrapOptions::default(), cx)
 9918    }
 9919
 9920    pub fn rewrap_impl(&mut self, options: RewrapOptions, cx: &mut Context<Self>) {
 9921        let buffer = self.buffer.read(cx).snapshot(cx);
 9922        let selections = self.selections.all::<Point>(cx);
 9923        let mut selections = selections.iter().peekable();
 9924
 9925        let mut edits = Vec::new();
 9926        let mut rewrapped_row_ranges = Vec::<RangeInclusive<u32>>::new();
 9927
 9928        while let Some(selection) = selections.next() {
 9929            let mut start_row = selection.start.row;
 9930            let mut end_row = selection.end.row;
 9931
 9932            // Skip selections that overlap with a range that has already been rewrapped.
 9933            let selection_range = start_row..end_row;
 9934            if rewrapped_row_ranges
 9935                .iter()
 9936                .any(|range| range.overlaps(&selection_range))
 9937            {
 9938                continue;
 9939            }
 9940
 9941            let tab_size = buffer.language_settings_at(selection.head(), cx).tab_size;
 9942
 9943            // Since not all lines in the selection may be at the same indent
 9944            // level, choose the indent size that is the most common between all
 9945            // of the lines.
 9946            //
 9947            // If there is a tie, we use the deepest indent.
 9948            let (indent_size, indent_end) = {
 9949                let mut indent_size_occurrences = HashMap::default();
 9950                let mut rows_by_indent_size = HashMap::<IndentSize, Vec<u32>>::default();
 9951
 9952                for row in start_row..=end_row {
 9953                    let indent = buffer.indent_size_for_line(MultiBufferRow(row));
 9954                    rows_by_indent_size.entry(indent).or_default().push(row);
 9955                    *indent_size_occurrences.entry(indent).or_insert(0) += 1;
 9956                }
 9957
 9958                let indent_size = indent_size_occurrences
 9959                    .into_iter()
 9960                    .max_by_key(|(indent, count)| (*count, indent.len_with_expanded_tabs(tab_size)))
 9961                    .map(|(indent, _)| indent)
 9962                    .unwrap_or_default();
 9963                let row = rows_by_indent_size[&indent_size][0];
 9964                let indent_end = Point::new(row, indent_size.len);
 9965
 9966                (indent_size, indent_end)
 9967            };
 9968
 9969            let mut line_prefix = indent_size.chars().collect::<String>();
 9970
 9971            let mut inside_comment = false;
 9972            if let Some(comment_prefix) =
 9973                buffer
 9974                    .language_scope_at(selection.head())
 9975                    .and_then(|language| {
 9976                        language
 9977                            .line_comment_prefixes()
 9978                            .iter()
 9979                            .find(|prefix| buffer.contains_str_at(indent_end, prefix))
 9980                            .cloned()
 9981                    })
 9982            {
 9983                line_prefix.push_str(&comment_prefix);
 9984                inside_comment = true;
 9985            }
 9986
 9987            let language_settings = buffer.language_settings_at(selection.head(), cx);
 9988            let allow_rewrap_based_on_language = match language_settings.allow_rewrap {
 9989                RewrapBehavior::InComments => inside_comment,
 9990                RewrapBehavior::InSelections => !selection.is_empty(),
 9991                RewrapBehavior::Anywhere => true,
 9992            };
 9993
 9994            let should_rewrap = options.override_language_settings
 9995                || allow_rewrap_based_on_language
 9996                || self.hard_wrap.is_some();
 9997            if !should_rewrap {
 9998                continue;
 9999            }
10000
10001            if selection.is_empty() {
10002                'expand_upwards: while start_row > 0 {
10003                    let prev_row = start_row - 1;
10004                    if buffer.contains_str_at(Point::new(prev_row, 0), &line_prefix)
10005                        && buffer.line_len(MultiBufferRow(prev_row)) as usize > line_prefix.len()
10006                    {
10007                        start_row = prev_row;
10008                    } else {
10009                        break 'expand_upwards;
10010                    }
10011                }
10012
10013                'expand_downwards: while end_row < buffer.max_point().row {
10014                    let next_row = end_row + 1;
10015                    if buffer.contains_str_at(Point::new(next_row, 0), &line_prefix)
10016                        && buffer.line_len(MultiBufferRow(next_row)) as usize > line_prefix.len()
10017                    {
10018                        end_row = next_row;
10019                    } else {
10020                        break 'expand_downwards;
10021                    }
10022                }
10023            }
10024
10025            let start = Point::new(start_row, 0);
10026            let start_offset = start.to_offset(&buffer);
10027            let end = Point::new(end_row, buffer.line_len(MultiBufferRow(end_row)));
10028            let selection_text = buffer.text_for_range(start..end).collect::<String>();
10029            let Some(lines_without_prefixes) = selection_text
10030                .lines()
10031                .map(|line| {
10032                    line.strip_prefix(&line_prefix)
10033                        .or_else(|| line.trim_start().strip_prefix(&line_prefix.trim_start()))
10034                        .ok_or_else(|| {
10035                            anyhow!("line did not start with prefix {line_prefix:?}: {line:?}")
10036                        })
10037                })
10038                .collect::<Result<Vec<_>, _>>()
10039                .log_err()
10040            else {
10041                continue;
10042            };
10043
10044            let wrap_column = self.hard_wrap.unwrap_or_else(|| {
10045                buffer
10046                    .language_settings_at(Point::new(start_row, 0), cx)
10047                    .preferred_line_length as usize
10048            });
10049            let wrapped_text = wrap_with_prefix(
10050                line_prefix,
10051                lines_without_prefixes.join("\n"),
10052                wrap_column,
10053                tab_size,
10054                options.preserve_existing_whitespace,
10055            );
10056
10057            // TODO: should always use char-based diff while still supporting cursor behavior that
10058            // matches vim.
10059            let mut diff_options = DiffOptions::default();
10060            if options.override_language_settings {
10061                diff_options.max_word_diff_len = 0;
10062                diff_options.max_word_diff_line_count = 0;
10063            } else {
10064                diff_options.max_word_diff_len = usize::MAX;
10065                diff_options.max_word_diff_line_count = usize::MAX;
10066            }
10067
10068            for (old_range, new_text) in
10069                text_diff_with_options(&selection_text, &wrapped_text, diff_options)
10070            {
10071                let edit_start = buffer.anchor_after(start_offset + old_range.start);
10072                let edit_end = buffer.anchor_after(start_offset + old_range.end);
10073                edits.push((edit_start..edit_end, new_text));
10074            }
10075
10076            rewrapped_row_ranges.push(start_row..=end_row);
10077        }
10078
10079        self.buffer
10080            .update(cx, |buffer, cx| buffer.edit(edits, None, cx));
10081    }
10082
10083    pub fn cut_common(&mut self, window: &mut Window, cx: &mut Context<Self>) -> ClipboardItem {
10084        let mut text = String::new();
10085        let buffer = self.buffer.read(cx).snapshot(cx);
10086        let mut selections = self.selections.all::<Point>(cx);
10087        let mut clipboard_selections = Vec::with_capacity(selections.len());
10088        {
10089            let max_point = buffer.max_point();
10090            let mut is_first = true;
10091            for selection in &mut selections {
10092                let is_entire_line = selection.is_empty() || self.selections.line_mode;
10093                if is_entire_line {
10094                    selection.start = Point::new(selection.start.row, 0);
10095                    if !selection.is_empty() && selection.end.column == 0 {
10096                        selection.end = cmp::min(max_point, selection.end);
10097                    } else {
10098                        selection.end = cmp::min(max_point, Point::new(selection.end.row + 1, 0));
10099                    }
10100                    selection.goal = SelectionGoal::None;
10101                }
10102                if is_first {
10103                    is_first = false;
10104                } else {
10105                    text += "\n";
10106                }
10107                let mut len = 0;
10108                for chunk in buffer.text_for_range(selection.start..selection.end) {
10109                    text.push_str(chunk);
10110                    len += chunk.len();
10111                }
10112                clipboard_selections.push(ClipboardSelection {
10113                    len,
10114                    is_entire_line,
10115                    first_line_indent: buffer
10116                        .indent_size_for_line(MultiBufferRow(selection.start.row))
10117                        .len,
10118                });
10119            }
10120        }
10121
10122        self.transact(window, cx, |this, window, cx| {
10123            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10124                s.select(selections);
10125            });
10126            this.insert("", window, cx);
10127        });
10128        ClipboardItem::new_string_with_json_metadata(text, clipboard_selections)
10129    }
10130
10131    pub fn cut(&mut self, _: &Cut, window: &mut Window, cx: &mut Context<Self>) {
10132        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
10133        let item = self.cut_common(window, cx);
10134        cx.write_to_clipboard(item);
10135    }
10136
10137    pub fn kill_ring_cut(&mut self, _: &KillRingCut, window: &mut Window, cx: &mut Context<Self>) {
10138        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
10139        self.change_selections(None, window, cx, |s| {
10140            s.move_with(|snapshot, sel| {
10141                if sel.is_empty() {
10142                    sel.end = DisplayPoint::new(sel.end.row(), snapshot.line_len(sel.end.row()))
10143                }
10144            });
10145        });
10146        let item = self.cut_common(window, cx);
10147        cx.set_global(KillRing(item))
10148    }
10149
10150    pub fn kill_ring_yank(
10151        &mut self,
10152        _: &KillRingYank,
10153        window: &mut Window,
10154        cx: &mut Context<Self>,
10155    ) {
10156        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
10157        let (text, metadata) = if let Some(KillRing(item)) = cx.try_global() {
10158            if let Some(ClipboardEntry::String(kill_ring)) = item.entries().first() {
10159                (kill_ring.text().to_string(), kill_ring.metadata_json())
10160            } else {
10161                return;
10162            }
10163        } else {
10164            return;
10165        };
10166        self.do_paste(&text, metadata, false, window, cx);
10167    }
10168
10169    pub fn copy_and_trim(&mut self, _: &CopyAndTrim, _: &mut Window, cx: &mut Context<Self>) {
10170        self.do_copy(true, cx);
10171    }
10172
10173    pub fn copy(&mut self, _: &Copy, _: &mut Window, cx: &mut Context<Self>) {
10174        self.do_copy(false, cx);
10175    }
10176
10177    fn do_copy(&self, strip_leading_indents: bool, cx: &mut Context<Self>) {
10178        let selections = self.selections.all::<Point>(cx);
10179        let buffer = self.buffer.read(cx).read(cx);
10180        let mut text = String::new();
10181
10182        let mut clipboard_selections = Vec::with_capacity(selections.len());
10183        {
10184            let max_point = buffer.max_point();
10185            let mut is_first = true;
10186            for selection in &selections {
10187                let mut start = selection.start;
10188                let mut end = selection.end;
10189                let is_entire_line = selection.is_empty() || self.selections.line_mode;
10190                if is_entire_line {
10191                    start = Point::new(start.row, 0);
10192                    end = cmp::min(max_point, Point::new(end.row + 1, 0));
10193                }
10194
10195                let mut trimmed_selections = Vec::new();
10196                if strip_leading_indents && end.row.saturating_sub(start.row) > 0 {
10197                    let row = MultiBufferRow(start.row);
10198                    let first_indent = buffer.indent_size_for_line(row);
10199                    if first_indent.len == 0 || start.column > first_indent.len {
10200                        trimmed_selections.push(start..end);
10201                    } else {
10202                        trimmed_selections.push(
10203                            Point::new(row.0, first_indent.len)
10204                                ..Point::new(row.0, buffer.line_len(row)),
10205                        );
10206                        for row in start.row + 1..=end.row {
10207                            let mut line_len = buffer.line_len(MultiBufferRow(row));
10208                            if row == end.row {
10209                                line_len = end.column;
10210                            }
10211                            if line_len == 0 {
10212                                trimmed_selections
10213                                    .push(Point::new(row, 0)..Point::new(row, line_len));
10214                                continue;
10215                            }
10216                            let row_indent_size = buffer.indent_size_for_line(MultiBufferRow(row));
10217                            if row_indent_size.len >= first_indent.len {
10218                                trimmed_selections.push(
10219                                    Point::new(row, first_indent.len)..Point::new(row, line_len),
10220                                );
10221                            } else {
10222                                trimmed_selections.clear();
10223                                trimmed_selections.push(start..end);
10224                                break;
10225                            }
10226                        }
10227                    }
10228                } else {
10229                    trimmed_selections.push(start..end);
10230                }
10231
10232                for trimmed_range in trimmed_selections {
10233                    if is_first {
10234                        is_first = false;
10235                    } else {
10236                        text += "\n";
10237                    }
10238                    let mut len = 0;
10239                    for chunk in buffer.text_for_range(trimmed_range.start..trimmed_range.end) {
10240                        text.push_str(chunk);
10241                        len += chunk.len();
10242                    }
10243                    clipboard_selections.push(ClipboardSelection {
10244                        len,
10245                        is_entire_line,
10246                        first_line_indent: buffer
10247                            .indent_size_for_line(MultiBufferRow(trimmed_range.start.row))
10248                            .len,
10249                    });
10250                }
10251            }
10252        }
10253
10254        cx.write_to_clipboard(ClipboardItem::new_string_with_json_metadata(
10255            text,
10256            clipboard_selections,
10257        ));
10258    }
10259
10260    pub fn do_paste(
10261        &mut self,
10262        text: &String,
10263        clipboard_selections: Option<Vec<ClipboardSelection>>,
10264        handle_entire_lines: bool,
10265        window: &mut Window,
10266        cx: &mut Context<Self>,
10267    ) {
10268        if self.read_only(cx) {
10269            return;
10270        }
10271
10272        let clipboard_text = Cow::Borrowed(text);
10273
10274        self.transact(window, cx, |this, window, cx| {
10275            if let Some(mut clipboard_selections) = clipboard_selections {
10276                let old_selections = this.selections.all::<usize>(cx);
10277                let all_selections_were_entire_line =
10278                    clipboard_selections.iter().all(|s| s.is_entire_line);
10279                let first_selection_indent_column =
10280                    clipboard_selections.first().map(|s| s.first_line_indent);
10281                if clipboard_selections.len() != old_selections.len() {
10282                    clipboard_selections.drain(..);
10283                }
10284                let cursor_offset = this.selections.last::<usize>(cx).head();
10285                let mut auto_indent_on_paste = true;
10286
10287                this.buffer.update(cx, |buffer, cx| {
10288                    let snapshot = buffer.read(cx);
10289                    auto_indent_on_paste = snapshot
10290                        .language_settings_at(cursor_offset, cx)
10291                        .auto_indent_on_paste;
10292
10293                    let mut start_offset = 0;
10294                    let mut edits = Vec::new();
10295                    let mut original_indent_columns = Vec::new();
10296                    for (ix, selection) in old_selections.iter().enumerate() {
10297                        let to_insert;
10298                        let entire_line;
10299                        let original_indent_column;
10300                        if let Some(clipboard_selection) = clipboard_selections.get(ix) {
10301                            let end_offset = start_offset + clipboard_selection.len;
10302                            to_insert = &clipboard_text[start_offset..end_offset];
10303                            entire_line = clipboard_selection.is_entire_line;
10304                            start_offset = end_offset + 1;
10305                            original_indent_column = Some(clipboard_selection.first_line_indent);
10306                        } else {
10307                            to_insert = clipboard_text.as_str();
10308                            entire_line = all_selections_were_entire_line;
10309                            original_indent_column = first_selection_indent_column
10310                        }
10311
10312                        // If the corresponding selection was empty when this slice of the
10313                        // clipboard text was written, then the entire line containing the
10314                        // selection was copied. If this selection is also currently empty,
10315                        // then paste the line before the current line of the buffer.
10316                        let range = if selection.is_empty() && handle_entire_lines && entire_line {
10317                            let column = selection.start.to_point(&snapshot).column as usize;
10318                            let line_start = selection.start - column;
10319                            line_start..line_start
10320                        } else {
10321                            selection.range()
10322                        };
10323
10324                        edits.push((range, to_insert));
10325                        original_indent_columns.push(original_indent_column);
10326                    }
10327                    drop(snapshot);
10328
10329                    buffer.edit(
10330                        edits,
10331                        if auto_indent_on_paste {
10332                            Some(AutoindentMode::Block {
10333                                original_indent_columns,
10334                            })
10335                        } else {
10336                            None
10337                        },
10338                        cx,
10339                    );
10340                });
10341
10342                let selections = this.selections.all::<usize>(cx);
10343                this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10344                    s.select(selections)
10345                });
10346            } else {
10347                this.insert(&clipboard_text, window, cx);
10348            }
10349        });
10350    }
10351
10352    pub fn paste(&mut self, _: &Paste, window: &mut Window, cx: &mut Context<Self>) {
10353        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
10354        if let Some(item) = cx.read_from_clipboard() {
10355            let entries = item.entries();
10356
10357            match entries.first() {
10358                // For now, we only support applying metadata if there's one string. In the future, we can incorporate all the selections
10359                // of all the pasted entries.
10360                Some(ClipboardEntry::String(clipboard_string)) if entries.len() == 1 => self
10361                    .do_paste(
10362                        clipboard_string.text(),
10363                        clipboard_string.metadata_json::<Vec<ClipboardSelection>>(),
10364                        true,
10365                        window,
10366                        cx,
10367                    ),
10368                _ => self.do_paste(&item.text().unwrap_or_default(), None, true, window, cx),
10369            }
10370        }
10371    }
10372
10373    pub fn undo(&mut self, _: &Undo, window: &mut Window, cx: &mut Context<Self>) {
10374        if self.read_only(cx) {
10375            return;
10376        }
10377
10378        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
10379
10380        if let Some(transaction_id) = self.buffer.update(cx, |buffer, cx| buffer.undo(cx)) {
10381            if let Some((selections, _)) =
10382                self.selection_history.transaction(transaction_id).cloned()
10383            {
10384                self.change_selections(None, window, cx, |s| {
10385                    s.select_anchors(selections.to_vec());
10386                });
10387            } else {
10388                log::error!(
10389                    "No entry in selection_history found for undo. \
10390                     This may correspond to a bug where undo does not update the selection. \
10391                     If this is occurring, please add details to \
10392                     https://github.com/zed-industries/zed/issues/22692"
10393                );
10394            }
10395            self.request_autoscroll(Autoscroll::fit(), cx);
10396            self.unmark_text(window, cx);
10397            self.refresh_inline_completion(true, false, window, cx);
10398            cx.emit(EditorEvent::Edited { transaction_id });
10399            cx.emit(EditorEvent::TransactionUndone { transaction_id });
10400        }
10401    }
10402
10403    pub fn redo(&mut self, _: &Redo, window: &mut Window, cx: &mut Context<Self>) {
10404        if self.read_only(cx) {
10405            return;
10406        }
10407
10408        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
10409
10410        if let Some(transaction_id) = self.buffer.update(cx, |buffer, cx| buffer.redo(cx)) {
10411            if let Some((_, Some(selections))) =
10412                self.selection_history.transaction(transaction_id).cloned()
10413            {
10414                self.change_selections(None, window, cx, |s| {
10415                    s.select_anchors(selections.to_vec());
10416                });
10417            } else {
10418                log::error!(
10419                    "No entry in selection_history found for redo. \
10420                     This may correspond to a bug where undo does not update the selection. \
10421                     If this is occurring, please add details to \
10422                     https://github.com/zed-industries/zed/issues/22692"
10423                );
10424            }
10425            self.request_autoscroll(Autoscroll::fit(), cx);
10426            self.unmark_text(window, cx);
10427            self.refresh_inline_completion(true, false, window, cx);
10428            cx.emit(EditorEvent::Edited { transaction_id });
10429        }
10430    }
10431
10432    pub fn finalize_last_transaction(&mut self, cx: &mut Context<Self>) {
10433        self.buffer
10434            .update(cx, |buffer, cx| buffer.finalize_last_transaction(cx));
10435    }
10436
10437    pub fn group_until_transaction(&mut self, tx_id: TransactionId, cx: &mut Context<Self>) {
10438        self.buffer
10439            .update(cx, |buffer, cx| buffer.group_until_transaction(tx_id, cx));
10440    }
10441
10442    pub fn move_left(&mut self, _: &MoveLeft, window: &mut Window, cx: &mut Context<Self>) {
10443        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
10444        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10445            s.move_with(|map, selection| {
10446                let cursor = if selection.is_empty() {
10447                    movement::left(map, selection.start)
10448                } else {
10449                    selection.start
10450                };
10451                selection.collapse_to(cursor, SelectionGoal::None);
10452            });
10453        })
10454    }
10455
10456    pub fn select_left(&mut self, _: &SelectLeft, window: &mut Window, cx: &mut Context<Self>) {
10457        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
10458        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10459            s.move_heads_with(|map, head, _| (movement::left(map, head), SelectionGoal::None));
10460        })
10461    }
10462
10463    pub fn move_right(&mut self, _: &MoveRight, window: &mut Window, cx: &mut Context<Self>) {
10464        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
10465        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10466            s.move_with(|map, selection| {
10467                let cursor = if selection.is_empty() {
10468                    movement::right(map, selection.end)
10469                } else {
10470                    selection.end
10471                };
10472                selection.collapse_to(cursor, SelectionGoal::None)
10473            });
10474        })
10475    }
10476
10477    pub fn select_right(&mut self, _: &SelectRight, window: &mut Window, cx: &mut Context<Self>) {
10478        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
10479        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10480            s.move_heads_with(|map, head, _| (movement::right(map, head), SelectionGoal::None));
10481        })
10482    }
10483
10484    pub fn move_up(&mut self, _: &MoveUp, window: &mut Window, cx: &mut Context<Self>) {
10485        if self.take_rename(true, window, cx).is_some() {
10486            return;
10487        }
10488
10489        if matches!(self.mode, EditorMode::SingleLine { .. }) {
10490            cx.propagate();
10491            return;
10492        }
10493
10494        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
10495
10496        let text_layout_details = &self.text_layout_details(window);
10497        let selection_count = self.selections.count();
10498        let first_selection = self.selections.first_anchor();
10499
10500        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10501            s.move_with(|map, selection| {
10502                if !selection.is_empty() {
10503                    selection.goal = SelectionGoal::None;
10504                }
10505                let (cursor, goal) = movement::up(
10506                    map,
10507                    selection.start,
10508                    selection.goal,
10509                    false,
10510                    text_layout_details,
10511                );
10512                selection.collapse_to(cursor, goal);
10513            });
10514        });
10515
10516        if selection_count == 1 && first_selection.range() == self.selections.first_anchor().range()
10517        {
10518            cx.propagate();
10519        }
10520    }
10521
10522    pub fn move_up_by_lines(
10523        &mut self,
10524        action: &MoveUpByLines,
10525        window: &mut Window,
10526        cx: &mut Context<Self>,
10527    ) {
10528        if self.take_rename(true, window, cx).is_some() {
10529            return;
10530        }
10531
10532        if matches!(self.mode, EditorMode::SingleLine { .. }) {
10533            cx.propagate();
10534            return;
10535        }
10536
10537        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
10538
10539        let text_layout_details = &self.text_layout_details(window);
10540
10541        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10542            s.move_with(|map, selection| {
10543                if !selection.is_empty() {
10544                    selection.goal = SelectionGoal::None;
10545                }
10546                let (cursor, goal) = movement::up_by_rows(
10547                    map,
10548                    selection.start,
10549                    action.lines,
10550                    selection.goal,
10551                    false,
10552                    text_layout_details,
10553                );
10554                selection.collapse_to(cursor, goal);
10555            });
10556        })
10557    }
10558
10559    pub fn move_down_by_lines(
10560        &mut self,
10561        action: &MoveDownByLines,
10562        window: &mut Window,
10563        cx: &mut Context<Self>,
10564    ) {
10565        if self.take_rename(true, window, cx).is_some() {
10566            return;
10567        }
10568
10569        if matches!(self.mode, EditorMode::SingleLine { .. }) {
10570            cx.propagate();
10571            return;
10572        }
10573
10574        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
10575
10576        let text_layout_details = &self.text_layout_details(window);
10577
10578        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10579            s.move_with(|map, selection| {
10580                if !selection.is_empty() {
10581                    selection.goal = SelectionGoal::None;
10582                }
10583                let (cursor, goal) = movement::down_by_rows(
10584                    map,
10585                    selection.start,
10586                    action.lines,
10587                    selection.goal,
10588                    false,
10589                    text_layout_details,
10590                );
10591                selection.collapse_to(cursor, goal);
10592            });
10593        })
10594    }
10595
10596    pub fn select_down_by_lines(
10597        &mut self,
10598        action: &SelectDownByLines,
10599        window: &mut Window,
10600        cx: &mut Context<Self>,
10601    ) {
10602        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
10603        let text_layout_details = &self.text_layout_details(window);
10604        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10605            s.move_heads_with(|map, head, goal| {
10606                movement::down_by_rows(map, head, action.lines, goal, false, text_layout_details)
10607            })
10608        })
10609    }
10610
10611    pub fn select_up_by_lines(
10612        &mut self,
10613        action: &SelectUpByLines,
10614        window: &mut Window,
10615        cx: &mut Context<Self>,
10616    ) {
10617        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
10618        let text_layout_details = &self.text_layout_details(window);
10619        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10620            s.move_heads_with(|map, head, goal| {
10621                movement::up_by_rows(map, head, action.lines, goal, false, text_layout_details)
10622            })
10623        })
10624    }
10625
10626    pub fn select_page_up(
10627        &mut self,
10628        _: &SelectPageUp,
10629        window: &mut Window,
10630        cx: &mut Context<Self>,
10631    ) {
10632        let Some(row_count) = self.visible_row_count() else {
10633            return;
10634        };
10635
10636        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
10637
10638        let text_layout_details = &self.text_layout_details(window);
10639
10640        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10641            s.move_heads_with(|map, head, goal| {
10642                movement::up_by_rows(map, head, row_count, goal, false, text_layout_details)
10643            })
10644        })
10645    }
10646
10647    pub fn move_page_up(
10648        &mut self,
10649        action: &MovePageUp,
10650        window: &mut Window,
10651        cx: &mut Context<Self>,
10652    ) {
10653        if self.take_rename(true, window, cx).is_some() {
10654            return;
10655        }
10656
10657        if self
10658            .context_menu
10659            .borrow_mut()
10660            .as_mut()
10661            .map(|menu| menu.select_first(self.completion_provider.as_deref(), cx))
10662            .unwrap_or(false)
10663        {
10664            return;
10665        }
10666
10667        if matches!(self.mode, EditorMode::SingleLine { .. }) {
10668            cx.propagate();
10669            return;
10670        }
10671
10672        let Some(row_count) = self.visible_row_count() else {
10673            return;
10674        };
10675
10676        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
10677
10678        let autoscroll = if action.center_cursor {
10679            Autoscroll::center()
10680        } else {
10681            Autoscroll::fit()
10682        };
10683
10684        let text_layout_details = &self.text_layout_details(window);
10685
10686        self.change_selections(Some(autoscroll), window, cx, |s| {
10687            s.move_with(|map, selection| {
10688                if !selection.is_empty() {
10689                    selection.goal = SelectionGoal::None;
10690                }
10691                let (cursor, goal) = movement::up_by_rows(
10692                    map,
10693                    selection.end,
10694                    row_count,
10695                    selection.goal,
10696                    false,
10697                    text_layout_details,
10698                );
10699                selection.collapse_to(cursor, goal);
10700            });
10701        });
10702    }
10703
10704    pub fn select_up(&mut self, _: &SelectUp, window: &mut Window, cx: &mut Context<Self>) {
10705        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
10706        let text_layout_details = &self.text_layout_details(window);
10707        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10708            s.move_heads_with(|map, head, goal| {
10709                movement::up(map, head, goal, false, text_layout_details)
10710            })
10711        })
10712    }
10713
10714    pub fn move_down(&mut self, _: &MoveDown, window: &mut Window, cx: &mut Context<Self>) {
10715        self.take_rename(true, window, cx);
10716
10717        if matches!(self.mode, EditorMode::SingleLine { .. }) {
10718            cx.propagate();
10719            return;
10720        }
10721
10722        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
10723
10724        let text_layout_details = &self.text_layout_details(window);
10725        let selection_count = self.selections.count();
10726        let first_selection = self.selections.first_anchor();
10727
10728        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10729            s.move_with(|map, selection| {
10730                if !selection.is_empty() {
10731                    selection.goal = SelectionGoal::None;
10732                }
10733                let (cursor, goal) = movement::down(
10734                    map,
10735                    selection.end,
10736                    selection.goal,
10737                    false,
10738                    text_layout_details,
10739                );
10740                selection.collapse_to(cursor, goal);
10741            });
10742        });
10743
10744        if selection_count == 1 && first_selection.range() == self.selections.first_anchor().range()
10745        {
10746            cx.propagate();
10747        }
10748    }
10749
10750    pub fn select_page_down(
10751        &mut self,
10752        _: &SelectPageDown,
10753        window: &mut Window,
10754        cx: &mut Context<Self>,
10755    ) {
10756        let Some(row_count) = self.visible_row_count() else {
10757            return;
10758        };
10759
10760        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
10761
10762        let text_layout_details = &self.text_layout_details(window);
10763
10764        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10765            s.move_heads_with(|map, head, goal| {
10766                movement::down_by_rows(map, head, row_count, goal, false, text_layout_details)
10767            })
10768        })
10769    }
10770
10771    pub fn move_page_down(
10772        &mut self,
10773        action: &MovePageDown,
10774        window: &mut Window,
10775        cx: &mut Context<Self>,
10776    ) {
10777        if self.take_rename(true, window, cx).is_some() {
10778            return;
10779        }
10780
10781        if self
10782            .context_menu
10783            .borrow_mut()
10784            .as_mut()
10785            .map(|menu| menu.select_last(self.completion_provider.as_deref(), cx))
10786            .unwrap_or(false)
10787        {
10788            return;
10789        }
10790
10791        if matches!(self.mode, EditorMode::SingleLine { .. }) {
10792            cx.propagate();
10793            return;
10794        }
10795
10796        let Some(row_count) = self.visible_row_count() else {
10797            return;
10798        };
10799
10800        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
10801
10802        let autoscroll = if action.center_cursor {
10803            Autoscroll::center()
10804        } else {
10805            Autoscroll::fit()
10806        };
10807
10808        let text_layout_details = &self.text_layout_details(window);
10809        self.change_selections(Some(autoscroll), window, cx, |s| {
10810            s.move_with(|map, selection| {
10811                if !selection.is_empty() {
10812                    selection.goal = SelectionGoal::None;
10813                }
10814                let (cursor, goal) = movement::down_by_rows(
10815                    map,
10816                    selection.end,
10817                    row_count,
10818                    selection.goal,
10819                    false,
10820                    text_layout_details,
10821                );
10822                selection.collapse_to(cursor, goal);
10823            });
10824        });
10825    }
10826
10827    pub fn select_down(&mut self, _: &SelectDown, window: &mut Window, cx: &mut Context<Self>) {
10828        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
10829        let text_layout_details = &self.text_layout_details(window);
10830        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10831            s.move_heads_with(|map, head, goal| {
10832                movement::down(map, head, goal, false, text_layout_details)
10833            })
10834        });
10835    }
10836
10837    pub fn context_menu_first(
10838        &mut self,
10839        _: &ContextMenuFirst,
10840        _window: &mut Window,
10841        cx: &mut Context<Self>,
10842    ) {
10843        if let Some(context_menu) = self.context_menu.borrow_mut().as_mut() {
10844            context_menu.select_first(self.completion_provider.as_deref(), cx);
10845        }
10846    }
10847
10848    pub fn context_menu_prev(
10849        &mut self,
10850        _: &ContextMenuPrevious,
10851        _window: &mut Window,
10852        cx: &mut Context<Self>,
10853    ) {
10854        if let Some(context_menu) = self.context_menu.borrow_mut().as_mut() {
10855            context_menu.select_prev(self.completion_provider.as_deref(), cx);
10856        }
10857    }
10858
10859    pub fn context_menu_next(
10860        &mut self,
10861        _: &ContextMenuNext,
10862        _window: &mut Window,
10863        cx: &mut Context<Self>,
10864    ) {
10865        if let Some(context_menu) = self.context_menu.borrow_mut().as_mut() {
10866            context_menu.select_next(self.completion_provider.as_deref(), cx);
10867        }
10868    }
10869
10870    pub fn context_menu_last(
10871        &mut self,
10872        _: &ContextMenuLast,
10873        _window: &mut Window,
10874        cx: &mut Context<Self>,
10875    ) {
10876        if let Some(context_menu) = self.context_menu.borrow_mut().as_mut() {
10877            context_menu.select_last(self.completion_provider.as_deref(), cx);
10878        }
10879    }
10880
10881    pub fn move_to_previous_word_start(
10882        &mut self,
10883        _: &MoveToPreviousWordStart,
10884        window: &mut Window,
10885        cx: &mut Context<Self>,
10886    ) {
10887        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
10888        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10889            s.move_cursors_with(|map, head, _| {
10890                (
10891                    movement::previous_word_start(map, head),
10892                    SelectionGoal::None,
10893                )
10894            });
10895        })
10896    }
10897
10898    pub fn move_to_previous_subword_start(
10899        &mut self,
10900        _: &MoveToPreviousSubwordStart,
10901        window: &mut Window,
10902        cx: &mut Context<Self>,
10903    ) {
10904        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
10905        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10906            s.move_cursors_with(|map, head, _| {
10907                (
10908                    movement::previous_subword_start(map, head),
10909                    SelectionGoal::None,
10910                )
10911            });
10912        })
10913    }
10914
10915    pub fn select_to_previous_word_start(
10916        &mut self,
10917        _: &SelectToPreviousWordStart,
10918        window: &mut Window,
10919        cx: &mut Context<Self>,
10920    ) {
10921        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
10922        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10923            s.move_heads_with(|map, head, _| {
10924                (
10925                    movement::previous_word_start(map, head),
10926                    SelectionGoal::None,
10927                )
10928            });
10929        })
10930    }
10931
10932    pub fn select_to_previous_subword_start(
10933        &mut self,
10934        _: &SelectToPreviousSubwordStart,
10935        window: &mut Window,
10936        cx: &mut Context<Self>,
10937    ) {
10938        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
10939        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10940            s.move_heads_with(|map, head, _| {
10941                (
10942                    movement::previous_subword_start(map, head),
10943                    SelectionGoal::None,
10944                )
10945            });
10946        })
10947    }
10948
10949    pub fn delete_to_previous_word_start(
10950        &mut self,
10951        action: &DeleteToPreviousWordStart,
10952        window: &mut Window,
10953        cx: &mut Context<Self>,
10954    ) {
10955        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
10956        self.transact(window, cx, |this, window, cx| {
10957            this.select_autoclose_pair(window, cx);
10958            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10959                s.move_with(|map, selection| {
10960                    if selection.is_empty() {
10961                        let cursor = if action.ignore_newlines {
10962                            movement::previous_word_start(map, selection.head())
10963                        } else {
10964                            movement::previous_word_start_or_newline(map, selection.head())
10965                        };
10966                        selection.set_head(cursor, SelectionGoal::None);
10967                    }
10968                });
10969            });
10970            this.insert("", window, cx);
10971        });
10972    }
10973
10974    pub fn delete_to_previous_subword_start(
10975        &mut self,
10976        _: &DeleteToPreviousSubwordStart,
10977        window: &mut Window,
10978        cx: &mut Context<Self>,
10979    ) {
10980        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
10981        self.transact(window, cx, |this, window, cx| {
10982            this.select_autoclose_pair(window, cx);
10983            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10984                s.move_with(|map, selection| {
10985                    if selection.is_empty() {
10986                        let cursor = movement::previous_subword_start(map, selection.head());
10987                        selection.set_head(cursor, SelectionGoal::None);
10988                    }
10989                });
10990            });
10991            this.insert("", window, cx);
10992        });
10993    }
10994
10995    pub fn move_to_next_word_end(
10996        &mut self,
10997        _: &MoveToNextWordEnd,
10998        window: &mut Window,
10999        cx: &mut Context<Self>,
11000    ) {
11001        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11002        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11003            s.move_cursors_with(|map, head, _| {
11004                (movement::next_word_end(map, head), SelectionGoal::None)
11005            });
11006        })
11007    }
11008
11009    pub fn move_to_next_subword_end(
11010        &mut self,
11011        _: &MoveToNextSubwordEnd,
11012        window: &mut Window,
11013        cx: &mut Context<Self>,
11014    ) {
11015        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11016        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11017            s.move_cursors_with(|map, head, _| {
11018                (movement::next_subword_end(map, head), SelectionGoal::None)
11019            });
11020        })
11021    }
11022
11023    pub fn select_to_next_word_end(
11024        &mut self,
11025        _: &SelectToNextWordEnd,
11026        window: &mut Window,
11027        cx: &mut Context<Self>,
11028    ) {
11029        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11030        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11031            s.move_heads_with(|map, head, _| {
11032                (movement::next_word_end(map, head), SelectionGoal::None)
11033            });
11034        })
11035    }
11036
11037    pub fn select_to_next_subword_end(
11038        &mut self,
11039        _: &SelectToNextSubwordEnd,
11040        window: &mut Window,
11041        cx: &mut Context<Self>,
11042    ) {
11043        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11044        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11045            s.move_heads_with(|map, head, _| {
11046                (movement::next_subword_end(map, head), SelectionGoal::None)
11047            });
11048        })
11049    }
11050
11051    pub fn delete_to_next_word_end(
11052        &mut self,
11053        action: &DeleteToNextWordEnd,
11054        window: &mut Window,
11055        cx: &mut Context<Self>,
11056    ) {
11057        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
11058        self.transact(window, cx, |this, window, cx| {
11059            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11060                s.move_with(|map, selection| {
11061                    if selection.is_empty() {
11062                        let cursor = if action.ignore_newlines {
11063                            movement::next_word_end(map, selection.head())
11064                        } else {
11065                            movement::next_word_end_or_newline(map, selection.head())
11066                        };
11067                        selection.set_head(cursor, SelectionGoal::None);
11068                    }
11069                });
11070            });
11071            this.insert("", window, cx);
11072        });
11073    }
11074
11075    pub fn delete_to_next_subword_end(
11076        &mut self,
11077        _: &DeleteToNextSubwordEnd,
11078        window: &mut Window,
11079        cx: &mut Context<Self>,
11080    ) {
11081        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
11082        self.transact(window, cx, |this, window, cx| {
11083            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11084                s.move_with(|map, selection| {
11085                    if selection.is_empty() {
11086                        let cursor = movement::next_subword_end(map, selection.head());
11087                        selection.set_head(cursor, SelectionGoal::None);
11088                    }
11089                });
11090            });
11091            this.insert("", window, cx);
11092        });
11093    }
11094
11095    pub fn move_to_beginning_of_line(
11096        &mut self,
11097        action: &MoveToBeginningOfLine,
11098        window: &mut Window,
11099        cx: &mut Context<Self>,
11100    ) {
11101        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11102        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11103            s.move_cursors_with(|map, head, _| {
11104                (
11105                    movement::indented_line_beginning(
11106                        map,
11107                        head,
11108                        action.stop_at_soft_wraps,
11109                        action.stop_at_indent,
11110                    ),
11111                    SelectionGoal::None,
11112                )
11113            });
11114        })
11115    }
11116
11117    pub fn select_to_beginning_of_line(
11118        &mut self,
11119        action: &SelectToBeginningOfLine,
11120        window: &mut Window,
11121        cx: &mut Context<Self>,
11122    ) {
11123        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11124        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11125            s.move_heads_with(|map, head, _| {
11126                (
11127                    movement::indented_line_beginning(
11128                        map,
11129                        head,
11130                        action.stop_at_soft_wraps,
11131                        action.stop_at_indent,
11132                    ),
11133                    SelectionGoal::None,
11134                )
11135            });
11136        });
11137    }
11138
11139    pub fn delete_to_beginning_of_line(
11140        &mut self,
11141        action: &DeleteToBeginningOfLine,
11142        window: &mut Window,
11143        cx: &mut Context<Self>,
11144    ) {
11145        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
11146        self.transact(window, cx, |this, window, cx| {
11147            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11148                s.move_with(|_, selection| {
11149                    selection.reversed = true;
11150                });
11151            });
11152
11153            this.select_to_beginning_of_line(
11154                &SelectToBeginningOfLine {
11155                    stop_at_soft_wraps: false,
11156                    stop_at_indent: action.stop_at_indent,
11157                },
11158                window,
11159                cx,
11160            );
11161            this.backspace(&Backspace, window, cx);
11162        });
11163    }
11164
11165    pub fn move_to_end_of_line(
11166        &mut self,
11167        action: &MoveToEndOfLine,
11168        window: &mut Window,
11169        cx: &mut Context<Self>,
11170    ) {
11171        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11172        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11173            s.move_cursors_with(|map, head, _| {
11174                (
11175                    movement::line_end(map, head, action.stop_at_soft_wraps),
11176                    SelectionGoal::None,
11177                )
11178            });
11179        })
11180    }
11181
11182    pub fn select_to_end_of_line(
11183        &mut self,
11184        action: &SelectToEndOfLine,
11185        window: &mut Window,
11186        cx: &mut Context<Self>,
11187    ) {
11188        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11189        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11190            s.move_heads_with(|map, head, _| {
11191                (
11192                    movement::line_end(map, head, action.stop_at_soft_wraps),
11193                    SelectionGoal::None,
11194                )
11195            });
11196        })
11197    }
11198
11199    pub fn delete_to_end_of_line(
11200        &mut self,
11201        _: &DeleteToEndOfLine,
11202        window: &mut Window,
11203        cx: &mut Context<Self>,
11204    ) {
11205        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
11206        self.transact(window, cx, |this, window, cx| {
11207            this.select_to_end_of_line(
11208                &SelectToEndOfLine {
11209                    stop_at_soft_wraps: false,
11210                },
11211                window,
11212                cx,
11213            );
11214            this.delete(&Delete, window, cx);
11215        });
11216    }
11217
11218    pub fn cut_to_end_of_line(
11219        &mut self,
11220        _: &CutToEndOfLine,
11221        window: &mut Window,
11222        cx: &mut Context<Self>,
11223    ) {
11224        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
11225        self.transact(window, cx, |this, window, cx| {
11226            this.select_to_end_of_line(
11227                &SelectToEndOfLine {
11228                    stop_at_soft_wraps: false,
11229                },
11230                window,
11231                cx,
11232            );
11233            this.cut(&Cut, window, cx);
11234        });
11235    }
11236
11237    pub fn move_to_start_of_paragraph(
11238        &mut self,
11239        _: &MoveToStartOfParagraph,
11240        window: &mut Window,
11241        cx: &mut Context<Self>,
11242    ) {
11243        if matches!(self.mode, EditorMode::SingleLine { .. }) {
11244            cx.propagate();
11245            return;
11246        }
11247        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11248        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11249            s.move_with(|map, selection| {
11250                selection.collapse_to(
11251                    movement::start_of_paragraph(map, selection.head(), 1),
11252                    SelectionGoal::None,
11253                )
11254            });
11255        })
11256    }
11257
11258    pub fn move_to_end_of_paragraph(
11259        &mut self,
11260        _: &MoveToEndOfParagraph,
11261        window: &mut Window,
11262        cx: &mut Context<Self>,
11263    ) {
11264        if matches!(self.mode, EditorMode::SingleLine { .. }) {
11265            cx.propagate();
11266            return;
11267        }
11268        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11269        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11270            s.move_with(|map, selection| {
11271                selection.collapse_to(
11272                    movement::end_of_paragraph(map, selection.head(), 1),
11273                    SelectionGoal::None,
11274                )
11275            });
11276        })
11277    }
11278
11279    pub fn select_to_start_of_paragraph(
11280        &mut self,
11281        _: &SelectToStartOfParagraph,
11282        window: &mut Window,
11283        cx: &mut Context<Self>,
11284    ) {
11285        if matches!(self.mode, EditorMode::SingleLine { .. }) {
11286            cx.propagate();
11287            return;
11288        }
11289        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11290        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11291            s.move_heads_with(|map, head, _| {
11292                (
11293                    movement::start_of_paragraph(map, head, 1),
11294                    SelectionGoal::None,
11295                )
11296            });
11297        })
11298    }
11299
11300    pub fn select_to_end_of_paragraph(
11301        &mut self,
11302        _: &SelectToEndOfParagraph,
11303        window: &mut Window,
11304        cx: &mut Context<Self>,
11305    ) {
11306        if matches!(self.mode, EditorMode::SingleLine { .. }) {
11307            cx.propagate();
11308            return;
11309        }
11310        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11311        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11312            s.move_heads_with(|map, head, _| {
11313                (
11314                    movement::end_of_paragraph(map, head, 1),
11315                    SelectionGoal::None,
11316                )
11317            });
11318        })
11319    }
11320
11321    pub fn move_to_start_of_excerpt(
11322        &mut self,
11323        _: &MoveToStartOfExcerpt,
11324        window: &mut Window,
11325        cx: &mut Context<Self>,
11326    ) {
11327        if matches!(self.mode, EditorMode::SingleLine { .. }) {
11328            cx.propagate();
11329            return;
11330        }
11331        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11332        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11333            s.move_with(|map, selection| {
11334                selection.collapse_to(
11335                    movement::start_of_excerpt(
11336                        map,
11337                        selection.head(),
11338                        workspace::searchable::Direction::Prev,
11339                    ),
11340                    SelectionGoal::None,
11341                )
11342            });
11343        })
11344    }
11345
11346    pub fn move_to_start_of_next_excerpt(
11347        &mut self,
11348        _: &MoveToStartOfNextExcerpt,
11349        window: &mut Window,
11350        cx: &mut Context<Self>,
11351    ) {
11352        if matches!(self.mode, EditorMode::SingleLine { .. }) {
11353            cx.propagate();
11354            return;
11355        }
11356
11357        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11358            s.move_with(|map, selection| {
11359                selection.collapse_to(
11360                    movement::start_of_excerpt(
11361                        map,
11362                        selection.head(),
11363                        workspace::searchable::Direction::Next,
11364                    ),
11365                    SelectionGoal::None,
11366                )
11367            });
11368        })
11369    }
11370
11371    pub fn move_to_end_of_excerpt(
11372        &mut self,
11373        _: &MoveToEndOfExcerpt,
11374        window: &mut Window,
11375        cx: &mut Context<Self>,
11376    ) {
11377        if matches!(self.mode, EditorMode::SingleLine { .. }) {
11378            cx.propagate();
11379            return;
11380        }
11381        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11382        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11383            s.move_with(|map, selection| {
11384                selection.collapse_to(
11385                    movement::end_of_excerpt(
11386                        map,
11387                        selection.head(),
11388                        workspace::searchable::Direction::Next,
11389                    ),
11390                    SelectionGoal::None,
11391                )
11392            });
11393        })
11394    }
11395
11396    pub fn move_to_end_of_previous_excerpt(
11397        &mut self,
11398        _: &MoveToEndOfPreviousExcerpt,
11399        window: &mut Window,
11400        cx: &mut Context<Self>,
11401    ) {
11402        if matches!(self.mode, EditorMode::SingleLine { .. }) {
11403            cx.propagate();
11404            return;
11405        }
11406        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11407        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11408            s.move_with(|map, selection| {
11409                selection.collapse_to(
11410                    movement::end_of_excerpt(
11411                        map,
11412                        selection.head(),
11413                        workspace::searchable::Direction::Prev,
11414                    ),
11415                    SelectionGoal::None,
11416                )
11417            });
11418        })
11419    }
11420
11421    pub fn select_to_start_of_excerpt(
11422        &mut self,
11423        _: &SelectToStartOfExcerpt,
11424        window: &mut Window,
11425        cx: &mut Context<Self>,
11426    ) {
11427        if matches!(self.mode, EditorMode::SingleLine { .. }) {
11428            cx.propagate();
11429            return;
11430        }
11431        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11432        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11433            s.move_heads_with(|map, head, _| {
11434                (
11435                    movement::start_of_excerpt(map, head, workspace::searchable::Direction::Prev),
11436                    SelectionGoal::None,
11437                )
11438            });
11439        })
11440    }
11441
11442    pub fn select_to_start_of_next_excerpt(
11443        &mut self,
11444        _: &SelectToStartOfNextExcerpt,
11445        window: &mut Window,
11446        cx: &mut Context<Self>,
11447    ) {
11448        if matches!(self.mode, EditorMode::SingleLine { .. }) {
11449            cx.propagate();
11450            return;
11451        }
11452        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11453        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11454            s.move_heads_with(|map, head, _| {
11455                (
11456                    movement::start_of_excerpt(map, head, workspace::searchable::Direction::Next),
11457                    SelectionGoal::None,
11458                )
11459            });
11460        })
11461    }
11462
11463    pub fn select_to_end_of_excerpt(
11464        &mut self,
11465        _: &SelectToEndOfExcerpt,
11466        window: &mut Window,
11467        cx: &mut Context<Self>,
11468    ) {
11469        if matches!(self.mode, EditorMode::SingleLine { .. }) {
11470            cx.propagate();
11471            return;
11472        }
11473        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11474        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11475            s.move_heads_with(|map, head, _| {
11476                (
11477                    movement::end_of_excerpt(map, head, workspace::searchable::Direction::Next),
11478                    SelectionGoal::None,
11479                )
11480            });
11481        })
11482    }
11483
11484    pub fn select_to_end_of_previous_excerpt(
11485        &mut self,
11486        _: &SelectToEndOfPreviousExcerpt,
11487        window: &mut Window,
11488        cx: &mut Context<Self>,
11489    ) {
11490        if matches!(self.mode, EditorMode::SingleLine { .. }) {
11491            cx.propagate();
11492            return;
11493        }
11494        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11495        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11496            s.move_heads_with(|map, head, _| {
11497                (
11498                    movement::end_of_excerpt(map, head, workspace::searchable::Direction::Prev),
11499                    SelectionGoal::None,
11500                )
11501            });
11502        })
11503    }
11504
11505    pub fn move_to_beginning(
11506        &mut self,
11507        _: &MoveToBeginning,
11508        window: &mut Window,
11509        cx: &mut Context<Self>,
11510    ) {
11511        if matches!(self.mode, EditorMode::SingleLine { .. }) {
11512            cx.propagate();
11513            return;
11514        }
11515        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11516        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11517            s.select_ranges(vec![0..0]);
11518        });
11519    }
11520
11521    pub fn select_to_beginning(
11522        &mut self,
11523        _: &SelectToBeginning,
11524        window: &mut Window,
11525        cx: &mut Context<Self>,
11526    ) {
11527        let mut selection = self.selections.last::<Point>(cx);
11528        selection.set_head(Point::zero(), SelectionGoal::None);
11529        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11530        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11531            s.select(vec![selection]);
11532        });
11533    }
11534
11535    pub fn move_to_end(&mut self, _: &MoveToEnd, window: &mut Window, cx: &mut Context<Self>) {
11536        if matches!(self.mode, EditorMode::SingleLine { .. }) {
11537            cx.propagate();
11538            return;
11539        }
11540        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11541        let cursor = self.buffer.read(cx).read(cx).len();
11542        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11543            s.select_ranges(vec![cursor..cursor])
11544        });
11545    }
11546
11547    pub fn set_nav_history(&mut self, nav_history: Option<ItemNavHistory>) {
11548        self.nav_history = nav_history;
11549    }
11550
11551    pub fn nav_history(&self) -> Option<&ItemNavHistory> {
11552        self.nav_history.as_ref()
11553    }
11554
11555    pub fn create_nav_history_entry(&mut self, cx: &mut Context<Self>) {
11556        self.push_to_nav_history(self.selections.newest_anchor().head(), None, false, cx);
11557    }
11558
11559    fn push_to_nav_history(
11560        &mut self,
11561        cursor_anchor: Anchor,
11562        new_position: Option<Point>,
11563        is_deactivate: bool,
11564        cx: &mut Context<Self>,
11565    ) {
11566        if let Some(nav_history) = self.nav_history.as_mut() {
11567            let buffer = self.buffer.read(cx).read(cx);
11568            let cursor_position = cursor_anchor.to_point(&buffer);
11569            let scroll_state = self.scroll_manager.anchor();
11570            let scroll_top_row = scroll_state.top_row(&buffer);
11571            drop(buffer);
11572
11573            if let Some(new_position) = new_position {
11574                let row_delta = (new_position.row as i64 - cursor_position.row as i64).abs();
11575                if row_delta < MIN_NAVIGATION_HISTORY_ROW_DELTA {
11576                    return;
11577                }
11578            }
11579
11580            nav_history.push(
11581                Some(NavigationData {
11582                    cursor_anchor,
11583                    cursor_position,
11584                    scroll_anchor: scroll_state,
11585                    scroll_top_row,
11586                }),
11587                cx,
11588            );
11589            cx.emit(EditorEvent::PushedToNavHistory {
11590                anchor: cursor_anchor,
11591                is_deactivate,
11592            })
11593        }
11594    }
11595
11596    pub fn select_to_end(&mut self, _: &SelectToEnd, window: &mut Window, cx: &mut Context<Self>) {
11597        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11598        let buffer = self.buffer.read(cx).snapshot(cx);
11599        let mut selection = self.selections.first::<usize>(cx);
11600        selection.set_head(buffer.len(), SelectionGoal::None);
11601        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11602            s.select(vec![selection]);
11603        });
11604    }
11605
11606    pub fn select_all(&mut self, _: &SelectAll, window: &mut Window, cx: &mut Context<Self>) {
11607        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11608        let end = self.buffer.read(cx).read(cx).len();
11609        self.change_selections(None, window, cx, |s| {
11610            s.select_ranges(vec![0..end]);
11611        });
11612    }
11613
11614    pub fn select_line(&mut self, _: &SelectLine, window: &mut Window, cx: &mut Context<Self>) {
11615        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11616        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
11617        let mut selections = self.selections.all::<Point>(cx);
11618        let max_point = display_map.buffer_snapshot.max_point();
11619        for selection in &mut selections {
11620            let rows = selection.spanned_rows(true, &display_map);
11621            selection.start = Point::new(rows.start.0, 0);
11622            selection.end = cmp::min(max_point, Point::new(rows.end.0, 0));
11623            selection.reversed = false;
11624        }
11625        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11626            s.select(selections);
11627        });
11628    }
11629
11630    pub fn split_selection_into_lines(
11631        &mut self,
11632        _: &SplitSelectionIntoLines,
11633        window: &mut Window,
11634        cx: &mut Context<Self>,
11635    ) {
11636        let selections = self
11637            .selections
11638            .all::<Point>(cx)
11639            .into_iter()
11640            .map(|selection| selection.start..selection.end)
11641            .collect::<Vec<_>>();
11642        self.unfold_ranges(&selections, true, true, cx);
11643
11644        let mut new_selection_ranges = Vec::new();
11645        {
11646            let buffer = self.buffer.read(cx).read(cx);
11647            for selection in selections {
11648                for row in selection.start.row..selection.end.row {
11649                    let cursor = Point::new(row, buffer.line_len(MultiBufferRow(row)));
11650                    new_selection_ranges.push(cursor..cursor);
11651                }
11652
11653                let is_multiline_selection = selection.start.row != selection.end.row;
11654                // Don't insert last one if it's a multi-line selection ending at the start of a line,
11655                // so this action feels more ergonomic when paired with other selection operations
11656                let should_skip_last = is_multiline_selection && selection.end.column == 0;
11657                if !should_skip_last {
11658                    new_selection_ranges.push(selection.end..selection.end);
11659                }
11660            }
11661        }
11662        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11663            s.select_ranges(new_selection_ranges);
11664        });
11665    }
11666
11667    pub fn add_selection_above(
11668        &mut self,
11669        _: &AddSelectionAbove,
11670        window: &mut Window,
11671        cx: &mut Context<Self>,
11672    ) {
11673        self.add_selection(true, window, cx);
11674    }
11675
11676    pub fn add_selection_below(
11677        &mut self,
11678        _: &AddSelectionBelow,
11679        window: &mut Window,
11680        cx: &mut Context<Self>,
11681    ) {
11682        self.add_selection(false, window, cx);
11683    }
11684
11685    fn add_selection(&mut self, above: bool, window: &mut Window, cx: &mut Context<Self>) {
11686        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11687
11688        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
11689        let mut selections = self.selections.all::<Point>(cx);
11690        let text_layout_details = self.text_layout_details(window);
11691        let mut state = self.add_selections_state.take().unwrap_or_else(|| {
11692            let oldest_selection = selections.iter().min_by_key(|s| s.id).unwrap().clone();
11693            let range = oldest_selection.display_range(&display_map).sorted();
11694
11695            let start_x = display_map.x_for_display_point(range.start, &text_layout_details);
11696            let end_x = display_map.x_for_display_point(range.end, &text_layout_details);
11697            let positions = start_x.min(end_x)..start_x.max(end_x);
11698
11699            selections.clear();
11700            let mut stack = Vec::new();
11701            for row in range.start.row().0..=range.end.row().0 {
11702                if let Some(selection) = self.selections.build_columnar_selection(
11703                    &display_map,
11704                    DisplayRow(row),
11705                    &positions,
11706                    oldest_selection.reversed,
11707                    &text_layout_details,
11708                ) {
11709                    stack.push(selection.id);
11710                    selections.push(selection);
11711                }
11712            }
11713
11714            if above {
11715                stack.reverse();
11716            }
11717
11718            AddSelectionsState { above, stack }
11719        });
11720
11721        let last_added_selection = *state.stack.last().unwrap();
11722        let mut new_selections = Vec::new();
11723        if above == state.above {
11724            let end_row = if above {
11725                DisplayRow(0)
11726            } else {
11727                display_map.max_point().row()
11728            };
11729
11730            'outer: for selection in selections {
11731                if selection.id == last_added_selection {
11732                    let range = selection.display_range(&display_map).sorted();
11733                    debug_assert_eq!(range.start.row(), range.end.row());
11734                    let mut row = range.start.row();
11735                    let positions =
11736                        if let SelectionGoal::HorizontalRange { start, end } = selection.goal {
11737                            px(start)..px(end)
11738                        } else {
11739                            let start_x =
11740                                display_map.x_for_display_point(range.start, &text_layout_details);
11741                            let end_x =
11742                                display_map.x_for_display_point(range.end, &text_layout_details);
11743                            start_x.min(end_x)..start_x.max(end_x)
11744                        };
11745
11746                    while row != end_row {
11747                        if above {
11748                            row.0 -= 1;
11749                        } else {
11750                            row.0 += 1;
11751                        }
11752
11753                        if let Some(new_selection) = self.selections.build_columnar_selection(
11754                            &display_map,
11755                            row,
11756                            &positions,
11757                            selection.reversed,
11758                            &text_layout_details,
11759                        ) {
11760                            state.stack.push(new_selection.id);
11761                            if above {
11762                                new_selections.push(new_selection);
11763                                new_selections.push(selection);
11764                            } else {
11765                                new_selections.push(selection);
11766                                new_selections.push(new_selection);
11767                            }
11768
11769                            continue 'outer;
11770                        }
11771                    }
11772                }
11773
11774                new_selections.push(selection);
11775            }
11776        } else {
11777            new_selections = selections;
11778            new_selections.retain(|s| s.id != last_added_selection);
11779            state.stack.pop();
11780        }
11781
11782        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11783            s.select(new_selections);
11784        });
11785        if state.stack.len() > 1 {
11786            self.add_selections_state = Some(state);
11787        }
11788    }
11789
11790    pub fn select_next_match_internal(
11791        &mut self,
11792        display_map: &DisplaySnapshot,
11793        replace_newest: bool,
11794        autoscroll: Option<Autoscroll>,
11795        window: &mut Window,
11796        cx: &mut Context<Self>,
11797    ) -> Result<()> {
11798        fn select_next_match_ranges(
11799            this: &mut Editor,
11800            range: Range<usize>,
11801            replace_newest: bool,
11802            auto_scroll: Option<Autoscroll>,
11803            window: &mut Window,
11804            cx: &mut Context<Editor>,
11805        ) {
11806            this.unfold_ranges(&[range.clone()], false, auto_scroll.is_some(), cx);
11807            this.change_selections(auto_scroll, window, cx, |s| {
11808                if replace_newest {
11809                    s.delete(s.newest_anchor().id);
11810                }
11811                s.insert_range(range.clone());
11812            });
11813        }
11814
11815        let buffer = &display_map.buffer_snapshot;
11816        let mut selections = self.selections.all::<usize>(cx);
11817        if let Some(mut select_next_state) = self.select_next_state.take() {
11818            let query = &select_next_state.query;
11819            if !select_next_state.done {
11820                let first_selection = selections.iter().min_by_key(|s| s.id).unwrap();
11821                let last_selection = selections.iter().max_by_key(|s| s.id).unwrap();
11822                let mut next_selected_range = None;
11823
11824                let bytes_after_last_selection =
11825                    buffer.bytes_in_range(last_selection.end..buffer.len());
11826                let bytes_before_first_selection = buffer.bytes_in_range(0..first_selection.start);
11827                let query_matches = query
11828                    .stream_find_iter(bytes_after_last_selection)
11829                    .map(|result| (last_selection.end, result))
11830                    .chain(
11831                        query
11832                            .stream_find_iter(bytes_before_first_selection)
11833                            .map(|result| (0, result)),
11834                    );
11835
11836                for (start_offset, query_match) in query_matches {
11837                    let query_match = query_match.unwrap(); // can only fail due to I/O
11838                    let offset_range =
11839                        start_offset + query_match.start()..start_offset + query_match.end();
11840                    let display_range = offset_range.start.to_display_point(display_map)
11841                        ..offset_range.end.to_display_point(display_map);
11842
11843                    if !select_next_state.wordwise
11844                        || (!movement::is_inside_word(display_map, display_range.start)
11845                            && !movement::is_inside_word(display_map, display_range.end))
11846                    {
11847                        // TODO: This is n^2, because we might check all the selections
11848                        if !selections
11849                            .iter()
11850                            .any(|selection| selection.range().overlaps(&offset_range))
11851                        {
11852                            next_selected_range = Some(offset_range);
11853                            break;
11854                        }
11855                    }
11856                }
11857
11858                if let Some(next_selected_range) = next_selected_range {
11859                    select_next_match_ranges(
11860                        self,
11861                        next_selected_range,
11862                        replace_newest,
11863                        autoscroll,
11864                        window,
11865                        cx,
11866                    );
11867                } else {
11868                    select_next_state.done = true;
11869                }
11870            }
11871
11872            self.select_next_state = Some(select_next_state);
11873        } else {
11874            let mut only_carets = true;
11875            let mut same_text_selected = true;
11876            let mut selected_text = None;
11877
11878            let mut selections_iter = selections.iter().peekable();
11879            while let Some(selection) = selections_iter.next() {
11880                if selection.start != selection.end {
11881                    only_carets = false;
11882                }
11883
11884                if same_text_selected {
11885                    if selected_text.is_none() {
11886                        selected_text =
11887                            Some(buffer.text_for_range(selection.range()).collect::<String>());
11888                    }
11889
11890                    if let Some(next_selection) = selections_iter.peek() {
11891                        if next_selection.range().len() == selection.range().len() {
11892                            let next_selected_text = buffer
11893                                .text_for_range(next_selection.range())
11894                                .collect::<String>();
11895                            if Some(next_selected_text) != selected_text {
11896                                same_text_selected = false;
11897                                selected_text = None;
11898                            }
11899                        } else {
11900                            same_text_selected = false;
11901                            selected_text = None;
11902                        }
11903                    }
11904                }
11905            }
11906
11907            if only_carets {
11908                for selection in &mut selections {
11909                    let word_range = movement::surrounding_word(
11910                        display_map,
11911                        selection.start.to_display_point(display_map),
11912                    );
11913                    selection.start = word_range.start.to_offset(display_map, Bias::Left);
11914                    selection.end = word_range.end.to_offset(display_map, Bias::Left);
11915                    selection.goal = SelectionGoal::None;
11916                    selection.reversed = false;
11917                    select_next_match_ranges(
11918                        self,
11919                        selection.start..selection.end,
11920                        replace_newest,
11921                        autoscroll,
11922                        window,
11923                        cx,
11924                    );
11925                }
11926
11927                if selections.len() == 1 {
11928                    let selection = selections
11929                        .last()
11930                        .expect("ensured that there's only one selection");
11931                    let query = buffer
11932                        .text_for_range(selection.start..selection.end)
11933                        .collect::<String>();
11934                    let is_empty = query.is_empty();
11935                    let select_state = SelectNextState {
11936                        query: AhoCorasick::new(&[query])?,
11937                        wordwise: true,
11938                        done: is_empty,
11939                    };
11940                    self.select_next_state = Some(select_state);
11941                } else {
11942                    self.select_next_state = None;
11943                }
11944            } else if let Some(selected_text) = selected_text {
11945                self.select_next_state = Some(SelectNextState {
11946                    query: AhoCorasick::new(&[selected_text])?,
11947                    wordwise: false,
11948                    done: false,
11949                });
11950                self.select_next_match_internal(
11951                    display_map,
11952                    replace_newest,
11953                    autoscroll,
11954                    window,
11955                    cx,
11956                )?;
11957            }
11958        }
11959        Ok(())
11960    }
11961
11962    pub fn select_all_matches(
11963        &mut self,
11964        _action: &SelectAllMatches,
11965        window: &mut Window,
11966        cx: &mut Context<Self>,
11967    ) -> Result<()> {
11968        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11969
11970        self.push_to_selection_history();
11971        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
11972
11973        self.select_next_match_internal(&display_map, false, None, window, cx)?;
11974        let Some(select_next_state) = self.select_next_state.as_mut() else {
11975            return Ok(());
11976        };
11977        if select_next_state.done {
11978            return Ok(());
11979        }
11980
11981        let mut new_selections = Vec::new();
11982
11983        let reversed = self.selections.oldest::<usize>(cx).reversed;
11984        let buffer = &display_map.buffer_snapshot;
11985        let query_matches = select_next_state
11986            .query
11987            .stream_find_iter(buffer.bytes_in_range(0..buffer.len()));
11988
11989        for query_match in query_matches.into_iter() {
11990            let query_match = query_match.context("query match for select all action")?; // can only fail due to I/O
11991            let offset_range = if reversed {
11992                query_match.end()..query_match.start()
11993            } else {
11994                query_match.start()..query_match.end()
11995            };
11996            let display_range = offset_range.start.to_display_point(&display_map)
11997                ..offset_range.end.to_display_point(&display_map);
11998
11999            if !select_next_state.wordwise
12000                || (!movement::is_inside_word(&display_map, display_range.start)
12001                    && !movement::is_inside_word(&display_map, display_range.end))
12002            {
12003                new_selections.push(offset_range.start..offset_range.end);
12004            }
12005        }
12006
12007        select_next_state.done = true;
12008        self.unfold_ranges(&new_selections.clone(), false, false, cx);
12009        self.change_selections(None, window, cx, |selections| {
12010            selections.select_ranges(new_selections)
12011        });
12012
12013        Ok(())
12014    }
12015
12016    pub fn select_next(
12017        &mut self,
12018        action: &SelectNext,
12019        window: &mut Window,
12020        cx: &mut Context<Self>,
12021    ) -> Result<()> {
12022        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
12023        self.push_to_selection_history();
12024        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
12025        self.select_next_match_internal(
12026            &display_map,
12027            action.replace_newest,
12028            Some(Autoscroll::newest()),
12029            window,
12030            cx,
12031        )?;
12032        Ok(())
12033    }
12034
12035    pub fn select_previous(
12036        &mut self,
12037        action: &SelectPrevious,
12038        window: &mut Window,
12039        cx: &mut Context<Self>,
12040    ) -> Result<()> {
12041        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
12042        self.push_to_selection_history();
12043        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
12044        let buffer = &display_map.buffer_snapshot;
12045        let mut selections = self.selections.all::<usize>(cx);
12046        if let Some(mut select_prev_state) = self.select_prev_state.take() {
12047            let query = &select_prev_state.query;
12048            if !select_prev_state.done {
12049                let first_selection = selections.iter().min_by_key(|s| s.id).unwrap();
12050                let last_selection = selections.iter().max_by_key(|s| s.id).unwrap();
12051                let mut next_selected_range = None;
12052                // When we're iterating matches backwards, the oldest match will actually be the furthest one in the buffer.
12053                let bytes_before_last_selection =
12054                    buffer.reversed_bytes_in_range(0..last_selection.start);
12055                let bytes_after_first_selection =
12056                    buffer.reversed_bytes_in_range(first_selection.end..buffer.len());
12057                let query_matches = query
12058                    .stream_find_iter(bytes_before_last_selection)
12059                    .map(|result| (last_selection.start, result))
12060                    .chain(
12061                        query
12062                            .stream_find_iter(bytes_after_first_selection)
12063                            .map(|result| (buffer.len(), result)),
12064                    );
12065                for (end_offset, query_match) in query_matches {
12066                    let query_match = query_match.unwrap(); // can only fail due to I/O
12067                    let offset_range =
12068                        end_offset - query_match.end()..end_offset - query_match.start();
12069                    let display_range = offset_range.start.to_display_point(&display_map)
12070                        ..offset_range.end.to_display_point(&display_map);
12071
12072                    if !select_prev_state.wordwise
12073                        || (!movement::is_inside_word(&display_map, display_range.start)
12074                            && !movement::is_inside_word(&display_map, display_range.end))
12075                    {
12076                        next_selected_range = Some(offset_range);
12077                        break;
12078                    }
12079                }
12080
12081                if let Some(next_selected_range) = next_selected_range {
12082                    self.unfold_ranges(&[next_selected_range.clone()], false, true, cx);
12083                    self.change_selections(Some(Autoscroll::newest()), window, cx, |s| {
12084                        if action.replace_newest {
12085                            s.delete(s.newest_anchor().id);
12086                        }
12087                        s.insert_range(next_selected_range);
12088                    });
12089                } else {
12090                    select_prev_state.done = true;
12091                }
12092            }
12093
12094            self.select_prev_state = Some(select_prev_state);
12095        } else {
12096            let mut only_carets = true;
12097            let mut same_text_selected = true;
12098            let mut selected_text = None;
12099
12100            let mut selections_iter = selections.iter().peekable();
12101            while let Some(selection) = selections_iter.next() {
12102                if selection.start != selection.end {
12103                    only_carets = false;
12104                }
12105
12106                if same_text_selected {
12107                    if selected_text.is_none() {
12108                        selected_text =
12109                            Some(buffer.text_for_range(selection.range()).collect::<String>());
12110                    }
12111
12112                    if let Some(next_selection) = selections_iter.peek() {
12113                        if next_selection.range().len() == selection.range().len() {
12114                            let next_selected_text = buffer
12115                                .text_for_range(next_selection.range())
12116                                .collect::<String>();
12117                            if Some(next_selected_text) != selected_text {
12118                                same_text_selected = false;
12119                                selected_text = None;
12120                            }
12121                        } else {
12122                            same_text_selected = false;
12123                            selected_text = None;
12124                        }
12125                    }
12126                }
12127            }
12128
12129            if only_carets {
12130                for selection in &mut selections {
12131                    let word_range = movement::surrounding_word(
12132                        &display_map,
12133                        selection.start.to_display_point(&display_map),
12134                    );
12135                    selection.start = word_range.start.to_offset(&display_map, Bias::Left);
12136                    selection.end = word_range.end.to_offset(&display_map, Bias::Left);
12137                    selection.goal = SelectionGoal::None;
12138                    selection.reversed = false;
12139                }
12140                if selections.len() == 1 {
12141                    let selection = selections
12142                        .last()
12143                        .expect("ensured that there's only one selection");
12144                    let query = buffer
12145                        .text_for_range(selection.start..selection.end)
12146                        .collect::<String>();
12147                    let is_empty = query.is_empty();
12148                    let select_state = SelectNextState {
12149                        query: AhoCorasick::new(&[query.chars().rev().collect::<String>()])?,
12150                        wordwise: true,
12151                        done: is_empty,
12152                    };
12153                    self.select_prev_state = Some(select_state);
12154                } else {
12155                    self.select_prev_state = None;
12156                }
12157
12158                self.unfold_ranges(
12159                    &selections.iter().map(|s| s.range()).collect::<Vec<_>>(),
12160                    false,
12161                    true,
12162                    cx,
12163                );
12164                self.change_selections(Some(Autoscroll::newest()), window, cx, |s| {
12165                    s.select(selections);
12166                });
12167            } else if let Some(selected_text) = selected_text {
12168                self.select_prev_state = Some(SelectNextState {
12169                    query: AhoCorasick::new(&[selected_text.chars().rev().collect::<String>()])?,
12170                    wordwise: false,
12171                    done: false,
12172                });
12173                self.select_previous(action, window, cx)?;
12174            }
12175        }
12176        Ok(())
12177    }
12178
12179    pub fn find_next_match(
12180        &mut self,
12181        _: &FindNextMatch,
12182        window: &mut Window,
12183        cx: &mut Context<Self>,
12184    ) -> Result<()> {
12185        let selections = self.selections.disjoint_anchors();
12186        match selections.first() {
12187            Some(first) if selections.len() >= 2 => {
12188                self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
12189                    s.select_ranges([first.range()]);
12190                });
12191            }
12192            _ => self.select_next(
12193                &SelectNext {
12194                    replace_newest: true,
12195                },
12196                window,
12197                cx,
12198            )?,
12199        }
12200        Ok(())
12201    }
12202
12203    pub fn find_previous_match(
12204        &mut self,
12205        _: &FindPreviousMatch,
12206        window: &mut Window,
12207        cx: &mut Context<Self>,
12208    ) -> Result<()> {
12209        let selections = self.selections.disjoint_anchors();
12210        match selections.last() {
12211            Some(last) if selections.len() >= 2 => {
12212                self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
12213                    s.select_ranges([last.range()]);
12214                });
12215            }
12216            _ => self.select_previous(
12217                &SelectPrevious {
12218                    replace_newest: true,
12219                },
12220                window,
12221                cx,
12222            )?,
12223        }
12224        Ok(())
12225    }
12226
12227    pub fn toggle_comments(
12228        &mut self,
12229        action: &ToggleComments,
12230        window: &mut Window,
12231        cx: &mut Context<Self>,
12232    ) {
12233        if self.read_only(cx) {
12234            return;
12235        }
12236        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
12237        let text_layout_details = &self.text_layout_details(window);
12238        self.transact(window, cx, |this, window, cx| {
12239            let mut selections = this.selections.all::<MultiBufferPoint>(cx);
12240            let mut edits = Vec::new();
12241            let mut selection_edit_ranges = Vec::new();
12242            let mut last_toggled_row = None;
12243            let snapshot = this.buffer.read(cx).read(cx);
12244            let empty_str: Arc<str> = Arc::default();
12245            let mut suffixes_inserted = Vec::new();
12246            let ignore_indent = action.ignore_indent;
12247
12248            fn comment_prefix_range(
12249                snapshot: &MultiBufferSnapshot,
12250                row: MultiBufferRow,
12251                comment_prefix: &str,
12252                comment_prefix_whitespace: &str,
12253                ignore_indent: bool,
12254            ) -> Range<Point> {
12255                let indent_size = if ignore_indent {
12256                    0
12257                } else {
12258                    snapshot.indent_size_for_line(row).len
12259                };
12260
12261                let start = Point::new(row.0, indent_size);
12262
12263                let mut line_bytes = snapshot
12264                    .bytes_in_range(start..snapshot.max_point())
12265                    .flatten()
12266                    .copied();
12267
12268                // If this line currently begins with the line comment prefix, then record
12269                // the range containing the prefix.
12270                if line_bytes
12271                    .by_ref()
12272                    .take(comment_prefix.len())
12273                    .eq(comment_prefix.bytes())
12274                {
12275                    // Include any whitespace that matches the comment prefix.
12276                    let matching_whitespace_len = line_bytes
12277                        .zip(comment_prefix_whitespace.bytes())
12278                        .take_while(|(a, b)| a == b)
12279                        .count() as u32;
12280                    let end = Point::new(
12281                        start.row,
12282                        start.column + comment_prefix.len() as u32 + matching_whitespace_len,
12283                    );
12284                    start..end
12285                } else {
12286                    start..start
12287                }
12288            }
12289
12290            fn comment_suffix_range(
12291                snapshot: &MultiBufferSnapshot,
12292                row: MultiBufferRow,
12293                comment_suffix: &str,
12294                comment_suffix_has_leading_space: bool,
12295            ) -> Range<Point> {
12296                let end = Point::new(row.0, snapshot.line_len(row));
12297                let suffix_start_column = end.column.saturating_sub(comment_suffix.len() as u32);
12298
12299                let mut line_end_bytes = snapshot
12300                    .bytes_in_range(Point::new(end.row, suffix_start_column.saturating_sub(1))..end)
12301                    .flatten()
12302                    .copied();
12303
12304                let leading_space_len = if suffix_start_column > 0
12305                    && line_end_bytes.next() == Some(b' ')
12306                    && comment_suffix_has_leading_space
12307                {
12308                    1
12309                } else {
12310                    0
12311                };
12312
12313                // If this line currently begins with the line comment prefix, then record
12314                // the range containing the prefix.
12315                if line_end_bytes.by_ref().eq(comment_suffix.bytes()) {
12316                    let start = Point::new(end.row, suffix_start_column - leading_space_len);
12317                    start..end
12318                } else {
12319                    end..end
12320                }
12321            }
12322
12323            // TODO: Handle selections that cross excerpts
12324            for selection in &mut selections {
12325                let start_column = snapshot
12326                    .indent_size_for_line(MultiBufferRow(selection.start.row))
12327                    .len;
12328                let language = if let Some(language) =
12329                    snapshot.language_scope_at(Point::new(selection.start.row, start_column))
12330                {
12331                    language
12332                } else {
12333                    continue;
12334                };
12335
12336                selection_edit_ranges.clear();
12337
12338                // If multiple selections contain a given row, avoid processing that
12339                // row more than once.
12340                let mut start_row = MultiBufferRow(selection.start.row);
12341                if last_toggled_row == Some(start_row) {
12342                    start_row = start_row.next_row();
12343                }
12344                let end_row =
12345                    if selection.end.row > selection.start.row && selection.end.column == 0 {
12346                        MultiBufferRow(selection.end.row - 1)
12347                    } else {
12348                        MultiBufferRow(selection.end.row)
12349                    };
12350                last_toggled_row = Some(end_row);
12351
12352                if start_row > end_row {
12353                    continue;
12354                }
12355
12356                // If the language has line comments, toggle those.
12357                let mut full_comment_prefixes = language.line_comment_prefixes().to_vec();
12358
12359                // If ignore_indent is set, trim spaces from the right side of all full_comment_prefixes
12360                if ignore_indent {
12361                    full_comment_prefixes = full_comment_prefixes
12362                        .into_iter()
12363                        .map(|s| Arc::from(s.trim_end()))
12364                        .collect();
12365                }
12366
12367                if !full_comment_prefixes.is_empty() {
12368                    let first_prefix = full_comment_prefixes
12369                        .first()
12370                        .expect("prefixes is non-empty");
12371                    let prefix_trimmed_lengths = full_comment_prefixes
12372                        .iter()
12373                        .map(|p| p.trim_end_matches(' ').len())
12374                        .collect::<SmallVec<[usize; 4]>>();
12375
12376                    let mut all_selection_lines_are_comments = true;
12377
12378                    for row in start_row.0..=end_row.0 {
12379                        let row = MultiBufferRow(row);
12380                        if start_row < end_row && snapshot.is_line_blank(row) {
12381                            continue;
12382                        }
12383
12384                        let prefix_range = full_comment_prefixes
12385                            .iter()
12386                            .zip(prefix_trimmed_lengths.iter().copied())
12387                            .map(|(prefix, trimmed_prefix_len)| {
12388                                comment_prefix_range(
12389                                    snapshot.deref(),
12390                                    row,
12391                                    &prefix[..trimmed_prefix_len],
12392                                    &prefix[trimmed_prefix_len..],
12393                                    ignore_indent,
12394                                )
12395                            })
12396                            .max_by_key(|range| range.end.column - range.start.column)
12397                            .expect("prefixes is non-empty");
12398
12399                        if prefix_range.is_empty() {
12400                            all_selection_lines_are_comments = false;
12401                        }
12402
12403                        selection_edit_ranges.push(prefix_range);
12404                    }
12405
12406                    if all_selection_lines_are_comments {
12407                        edits.extend(
12408                            selection_edit_ranges
12409                                .iter()
12410                                .cloned()
12411                                .map(|range| (range, empty_str.clone())),
12412                        );
12413                    } else {
12414                        let min_column = selection_edit_ranges
12415                            .iter()
12416                            .map(|range| range.start.column)
12417                            .min()
12418                            .unwrap_or(0);
12419                        edits.extend(selection_edit_ranges.iter().map(|range| {
12420                            let position = Point::new(range.start.row, min_column);
12421                            (position..position, first_prefix.clone())
12422                        }));
12423                    }
12424                } else if let Some((full_comment_prefix, comment_suffix)) =
12425                    language.block_comment_delimiters()
12426                {
12427                    let comment_prefix = full_comment_prefix.trim_end_matches(' ');
12428                    let comment_prefix_whitespace = &full_comment_prefix[comment_prefix.len()..];
12429                    let prefix_range = comment_prefix_range(
12430                        snapshot.deref(),
12431                        start_row,
12432                        comment_prefix,
12433                        comment_prefix_whitespace,
12434                        ignore_indent,
12435                    );
12436                    let suffix_range = comment_suffix_range(
12437                        snapshot.deref(),
12438                        end_row,
12439                        comment_suffix.trim_start_matches(' '),
12440                        comment_suffix.starts_with(' '),
12441                    );
12442
12443                    if prefix_range.is_empty() || suffix_range.is_empty() {
12444                        edits.push((
12445                            prefix_range.start..prefix_range.start,
12446                            full_comment_prefix.clone(),
12447                        ));
12448                        edits.push((suffix_range.end..suffix_range.end, comment_suffix.clone()));
12449                        suffixes_inserted.push((end_row, comment_suffix.len()));
12450                    } else {
12451                        edits.push((prefix_range, empty_str.clone()));
12452                        edits.push((suffix_range, empty_str.clone()));
12453                    }
12454                } else {
12455                    continue;
12456                }
12457            }
12458
12459            drop(snapshot);
12460            this.buffer.update(cx, |buffer, cx| {
12461                buffer.edit(edits, None, cx);
12462            });
12463
12464            // Adjust selections so that they end before any comment suffixes that
12465            // were inserted.
12466            let mut suffixes_inserted = suffixes_inserted.into_iter().peekable();
12467            let mut selections = this.selections.all::<Point>(cx);
12468            let snapshot = this.buffer.read(cx).read(cx);
12469            for selection in &mut selections {
12470                while let Some((row, suffix_len)) = suffixes_inserted.peek().copied() {
12471                    match row.cmp(&MultiBufferRow(selection.end.row)) {
12472                        Ordering::Less => {
12473                            suffixes_inserted.next();
12474                            continue;
12475                        }
12476                        Ordering::Greater => break,
12477                        Ordering::Equal => {
12478                            if selection.end.column == snapshot.line_len(row) {
12479                                if selection.is_empty() {
12480                                    selection.start.column -= suffix_len as u32;
12481                                }
12482                                selection.end.column -= suffix_len as u32;
12483                            }
12484                            break;
12485                        }
12486                    }
12487                }
12488            }
12489
12490            drop(snapshot);
12491            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
12492                s.select(selections)
12493            });
12494
12495            let selections = this.selections.all::<Point>(cx);
12496            let selections_on_single_row = selections.windows(2).all(|selections| {
12497                selections[0].start.row == selections[1].start.row
12498                    && selections[0].end.row == selections[1].end.row
12499                    && selections[0].start.row == selections[0].end.row
12500            });
12501            let selections_selecting = selections
12502                .iter()
12503                .any(|selection| selection.start != selection.end);
12504            let advance_downwards = action.advance_downwards
12505                && selections_on_single_row
12506                && !selections_selecting
12507                && !matches!(this.mode, EditorMode::SingleLine { .. });
12508
12509            if advance_downwards {
12510                let snapshot = this.buffer.read(cx).snapshot(cx);
12511
12512                this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
12513                    s.move_cursors_with(|display_snapshot, display_point, _| {
12514                        let mut point = display_point.to_point(display_snapshot);
12515                        point.row += 1;
12516                        point = snapshot.clip_point(point, Bias::Left);
12517                        let display_point = point.to_display_point(display_snapshot);
12518                        let goal = SelectionGoal::HorizontalPosition(
12519                            display_snapshot
12520                                .x_for_display_point(display_point, text_layout_details)
12521                                .into(),
12522                        );
12523                        (display_point, goal)
12524                    })
12525                });
12526            }
12527        });
12528    }
12529
12530    pub fn select_enclosing_symbol(
12531        &mut self,
12532        _: &SelectEnclosingSymbol,
12533        window: &mut Window,
12534        cx: &mut Context<Self>,
12535    ) {
12536        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
12537
12538        let buffer = self.buffer.read(cx).snapshot(cx);
12539        let old_selections = self.selections.all::<usize>(cx).into_boxed_slice();
12540
12541        fn update_selection(
12542            selection: &Selection<usize>,
12543            buffer_snap: &MultiBufferSnapshot,
12544        ) -> Option<Selection<usize>> {
12545            let cursor = selection.head();
12546            let (_buffer_id, symbols) = buffer_snap.symbols_containing(cursor, None)?;
12547            for symbol in symbols.iter().rev() {
12548                let start = symbol.range.start.to_offset(buffer_snap);
12549                let end = symbol.range.end.to_offset(buffer_snap);
12550                let new_range = start..end;
12551                if start < selection.start || end > selection.end {
12552                    return Some(Selection {
12553                        id: selection.id,
12554                        start: new_range.start,
12555                        end: new_range.end,
12556                        goal: SelectionGoal::None,
12557                        reversed: selection.reversed,
12558                    });
12559                }
12560            }
12561            None
12562        }
12563
12564        let mut selected_larger_symbol = false;
12565        let new_selections = old_selections
12566            .iter()
12567            .map(|selection| match update_selection(selection, &buffer) {
12568                Some(new_selection) => {
12569                    if new_selection.range() != selection.range() {
12570                        selected_larger_symbol = true;
12571                    }
12572                    new_selection
12573                }
12574                None => selection.clone(),
12575            })
12576            .collect::<Vec<_>>();
12577
12578        if selected_larger_symbol {
12579            self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
12580                s.select(new_selections);
12581            });
12582        }
12583    }
12584
12585    pub fn select_larger_syntax_node(
12586        &mut self,
12587        _: &SelectLargerSyntaxNode,
12588        window: &mut Window,
12589        cx: &mut Context<Self>,
12590    ) {
12591        let Some(visible_row_count) = self.visible_row_count() else {
12592            return;
12593        };
12594        let old_selections: Box<[_]> = self.selections.all::<usize>(cx).into();
12595        if old_selections.is_empty() {
12596            return;
12597        }
12598
12599        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
12600
12601        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
12602        let buffer = self.buffer.read(cx).snapshot(cx);
12603
12604        let mut selected_larger_node = false;
12605        let mut new_selections = old_selections
12606            .iter()
12607            .map(|selection| {
12608                let old_range = selection.start..selection.end;
12609
12610                if let Some((node, _)) = buffer.syntax_ancestor(old_range.clone()) {
12611                    // manually select word at selection
12612                    if ["string_content", "inline"].contains(&node.kind()) {
12613                        let word_range = {
12614                            let display_point = buffer
12615                                .offset_to_point(old_range.start)
12616                                .to_display_point(&display_map);
12617                            let Range { start, end } =
12618                                movement::surrounding_word(&display_map, display_point);
12619                            start.to_point(&display_map).to_offset(&buffer)
12620                                ..end.to_point(&display_map).to_offset(&buffer)
12621                        };
12622                        // ignore if word is already selected
12623                        if !word_range.is_empty() && old_range != word_range {
12624                            let last_word_range = {
12625                                let display_point = buffer
12626                                    .offset_to_point(old_range.end)
12627                                    .to_display_point(&display_map);
12628                                let Range { start, end } =
12629                                    movement::surrounding_word(&display_map, display_point);
12630                                start.to_point(&display_map).to_offset(&buffer)
12631                                    ..end.to_point(&display_map).to_offset(&buffer)
12632                            };
12633                            // only select word if start and end point belongs to same word
12634                            if word_range == last_word_range {
12635                                selected_larger_node = true;
12636                                return Selection {
12637                                    id: selection.id,
12638                                    start: word_range.start,
12639                                    end: word_range.end,
12640                                    goal: SelectionGoal::None,
12641                                    reversed: selection.reversed,
12642                                };
12643                            }
12644                        }
12645                    }
12646                }
12647
12648                let mut new_range = old_range.clone();
12649                let mut new_node = None;
12650                while let Some((node, containing_range)) = buffer.syntax_ancestor(new_range.clone())
12651                {
12652                    new_node = Some(node);
12653                    new_range = match containing_range {
12654                        MultiOrSingleBufferOffsetRange::Single(_) => break,
12655                        MultiOrSingleBufferOffsetRange::Multi(range) => range,
12656                    };
12657                    if !display_map.intersects_fold(new_range.start)
12658                        && !display_map.intersects_fold(new_range.end)
12659                    {
12660                        break;
12661                    }
12662                }
12663
12664                if let Some(node) = new_node {
12665                    // Log the ancestor, to support using this action as a way to explore TreeSitter
12666                    // nodes. Parent and grandparent are also logged because this operation will not
12667                    // visit nodes that have the same range as their parent.
12668                    log::info!("Node: {node:?}");
12669                    let parent = node.parent();
12670                    log::info!("Parent: {parent:?}");
12671                    let grandparent = parent.and_then(|x| x.parent());
12672                    log::info!("Grandparent: {grandparent:?}");
12673                }
12674
12675                selected_larger_node |= new_range != old_range;
12676                Selection {
12677                    id: selection.id,
12678                    start: new_range.start,
12679                    end: new_range.end,
12680                    goal: SelectionGoal::None,
12681                    reversed: selection.reversed,
12682                }
12683            })
12684            .collect::<Vec<_>>();
12685
12686        if !selected_larger_node {
12687            return; // don't put this call in the history
12688        }
12689
12690        // scroll based on transformation done to the last selection created by the user
12691        let (last_old, last_new) = old_selections
12692            .last()
12693            .zip(new_selections.last().cloned())
12694            .expect("old_selections isn't empty");
12695
12696        // revert selection
12697        let is_selection_reversed = {
12698            let should_newest_selection_be_reversed = last_old.start != last_new.start;
12699            new_selections.last_mut().expect("checked above").reversed =
12700                should_newest_selection_be_reversed;
12701            should_newest_selection_be_reversed
12702        };
12703
12704        if selected_larger_node {
12705            self.select_syntax_node_history.disable_clearing = true;
12706            self.change_selections(None, window, cx, |s| {
12707                s.select(new_selections.clone());
12708            });
12709            self.select_syntax_node_history.disable_clearing = false;
12710        }
12711
12712        let start_row = last_new.start.to_display_point(&display_map).row().0;
12713        let end_row = last_new.end.to_display_point(&display_map).row().0;
12714        let selection_height = end_row - start_row + 1;
12715        let scroll_margin_rows = self.vertical_scroll_margin() as u32;
12716
12717        let fits_on_the_screen = visible_row_count >= selection_height + scroll_margin_rows * 2;
12718        let scroll_behavior = if fits_on_the_screen {
12719            self.request_autoscroll(Autoscroll::fit(), cx);
12720            SelectSyntaxNodeScrollBehavior::FitSelection
12721        } else if is_selection_reversed {
12722            self.scroll_cursor_top(&ScrollCursorTop, window, cx);
12723            SelectSyntaxNodeScrollBehavior::CursorTop
12724        } else {
12725            self.scroll_cursor_bottom(&ScrollCursorBottom, window, cx);
12726            SelectSyntaxNodeScrollBehavior::CursorBottom
12727        };
12728
12729        self.select_syntax_node_history.push((
12730            old_selections,
12731            scroll_behavior,
12732            is_selection_reversed,
12733        ));
12734    }
12735
12736    pub fn select_smaller_syntax_node(
12737        &mut self,
12738        _: &SelectSmallerSyntaxNode,
12739        window: &mut Window,
12740        cx: &mut Context<Self>,
12741    ) {
12742        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
12743
12744        if let Some((mut selections, scroll_behavior, is_selection_reversed)) =
12745            self.select_syntax_node_history.pop()
12746        {
12747            if let Some(selection) = selections.last_mut() {
12748                selection.reversed = is_selection_reversed;
12749            }
12750
12751            self.select_syntax_node_history.disable_clearing = true;
12752            self.change_selections(None, window, cx, |s| {
12753                s.select(selections.to_vec());
12754            });
12755            self.select_syntax_node_history.disable_clearing = false;
12756
12757            match scroll_behavior {
12758                SelectSyntaxNodeScrollBehavior::CursorTop => {
12759                    self.scroll_cursor_top(&ScrollCursorTop, window, cx);
12760                }
12761                SelectSyntaxNodeScrollBehavior::FitSelection => {
12762                    self.request_autoscroll(Autoscroll::fit(), cx);
12763                }
12764                SelectSyntaxNodeScrollBehavior::CursorBottom => {
12765                    self.scroll_cursor_bottom(&ScrollCursorBottom, window, cx);
12766                }
12767            }
12768        }
12769    }
12770
12771    fn refresh_runnables(&mut self, window: &mut Window, cx: &mut Context<Self>) -> Task<()> {
12772        if !EditorSettings::get_global(cx).gutter.runnables {
12773            self.clear_tasks();
12774            return Task::ready(());
12775        }
12776        let project = self.project.as_ref().map(Entity::downgrade);
12777        let task_sources = self.lsp_task_sources(cx);
12778        cx.spawn_in(window, async move |editor, cx| {
12779            cx.background_executor().timer(UPDATE_DEBOUNCE).await;
12780            let Some(project) = project.and_then(|p| p.upgrade()) else {
12781                return;
12782            };
12783            let Ok(display_snapshot) = editor.update(cx, |this, cx| {
12784                this.display_map.update(cx, |map, cx| map.snapshot(cx))
12785            }) else {
12786                return;
12787            };
12788
12789            let hide_runnables = project
12790                .update(cx, |project, cx| {
12791                    // Do not display any test indicators in non-dev server remote projects.
12792                    project.is_via_collab() && project.ssh_connection_string(cx).is_none()
12793                })
12794                .unwrap_or(true);
12795            if hide_runnables {
12796                return;
12797            }
12798            let new_rows =
12799                cx.background_spawn({
12800                    let snapshot = display_snapshot.clone();
12801                    async move {
12802                        Self::fetch_runnable_ranges(&snapshot, Anchor::min()..Anchor::max())
12803                    }
12804                })
12805                    .await;
12806            let Ok(lsp_tasks) =
12807                cx.update(|_, cx| crate::lsp_tasks(project.clone(), &task_sources, None, cx))
12808            else {
12809                return;
12810            };
12811            let lsp_tasks = lsp_tasks.await;
12812
12813            let Ok(mut lsp_tasks_by_rows) = cx.update(|_, cx| {
12814                lsp_tasks
12815                    .into_iter()
12816                    .flat_map(|(kind, tasks)| {
12817                        tasks.into_iter().filter_map(move |(location, task)| {
12818                            Some((kind.clone(), location?, task))
12819                        })
12820                    })
12821                    .fold(HashMap::default(), |mut acc, (kind, location, task)| {
12822                        let buffer = location.target.buffer;
12823                        let buffer_snapshot = buffer.read(cx).snapshot();
12824                        let offset = display_snapshot.buffer_snapshot.excerpts().find_map(
12825                            |(excerpt_id, snapshot, _)| {
12826                                if snapshot.remote_id() == buffer_snapshot.remote_id() {
12827                                    display_snapshot
12828                                        .buffer_snapshot
12829                                        .anchor_in_excerpt(excerpt_id, location.target.range.start)
12830                                } else {
12831                                    None
12832                                }
12833                            },
12834                        );
12835                        if let Some(offset) = offset {
12836                            let task_buffer_range =
12837                                location.target.range.to_point(&buffer_snapshot);
12838                            let context_buffer_range =
12839                                task_buffer_range.to_offset(&buffer_snapshot);
12840                            let context_range = BufferOffset(context_buffer_range.start)
12841                                ..BufferOffset(context_buffer_range.end);
12842
12843                            acc.entry((buffer_snapshot.remote_id(), task_buffer_range.start.row))
12844                                .or_insert_with(|| RunnableTasks {
12845                                    templates: Vec::new(),
12846                                    offset,
12847                                    column: task_buffer_range.start.column,
12848                                    extra_variables: HashMap::default(),
12849                                    context_range,
12850                                })
12851                                .templates
12852                                .push((kind, task.original_task().clone()));
12853                        }
12854
12855                        acc
12856                    })
12857            }) else {
12858                return;
12859            };
12860
12861            let rows = Self::runnable_rows(project, display_snapshot, new_rows, cx.clone());
12862            editor
12863                .update(cx, |editor, _| {
12864                    editor.clear_tasks();
12865                    for (key, mut value) in rows {
12866                        if let Some(lsp_tasks) = lsp_tasks_by_rows.remove(&key) {
12867                            value.templates.extend(lsp_tasks.templates);
12868                        }
12869
12870                        editor.insert_tasks(key, value);
12871                    }
12872                    for (key, value) in lsp_tasks_by_rows {
12873                        editor.insert_tasks(key, value);
12874                    }
12875                })
12876                .ok();
12877        })
12878    }
12879    fn fetch_runnable_ranges(
12880        snapshot: &DisplaySnapshot,
12881        range: Range<Anchor>,
12882    ) -> Vec<language::RunnableRange> {
12883        snapshot.buffer_snapshot.runnable_ranges(range).collect()
12884    }
12885
12886    fn runnable_rows(
12887        project: Entity<Project>,
12888        snapshot: DisplaySnapshot,
12889        runnable_ranges: Vec<RunnableRange>,
12890        mut cx: AsyncWindowContext,
12891    ) -> Vec<((BufferId, BufferRow), RunnableTasks)> {
12892        runnable_ranges
12893            .into_iter()
12894            .filter_map(|mut runnable| {
12895                let tasks = cx
12896                    .update(|_, cx| Self::templates_with_tags(&project, &mut runnable.runnable, cx))
12897                    .ok()?;
12898                if tasks.is_empty() {
12899                    return None;
12900                }
12901
12902                let point = runnable.run_range.start.to_point(&snapshot.buffer_snapshot);
12903
12904                let row = snapshot
12905                    .buffer_snapshot
12906                    .buffer_line_for_row(MultiBufferRow(point.row))?
12907                    .1
12908                    .start
12909                    .row;
12910
12911                let context_range =
12912                    BufferOffset(runnable.full_range.start)..BufferOffset(runnable.full_range.end);
12913                Some((
12914                    (runnable.buffer_id, row),
12915                    RunnableTasks {
12916                        templates: tasks,
12917                        offset: snapshot
12918                            .buffer_snapshot
12919                            .anchor_before(runnable.run_range.start),
12920                        context_range,
12921                        column: point.column,
12922                        extra_variables: runnable.extra_captures,
12923                    },
12924                ))
12925            })
12926            .collect()
12927    }
12928
12929    fn templates_with_tags(
12930        project: &Entity<Project>,
12931        runnable: &mut Runnable,
12932        cx: &mut App,
12933    ) -> Vec<(TaskSourceKind, TaskTemplate)> {
12934        let (inventory, worktree_id, file) = project.read_with(cx, |project, cx| {
12935            let (worktree_id, file) = project
12936                .buffer_for_id(runnable.buffer, cx)
12937                .and_then(|buffer| buffer.read(cx).file())
12938                .map(|file| (file.worktree_id(cx), file.clone()))
12939                .unzip();
12940
12941            (
12942                project.task_store().read(cx).task_inventory().cloned(),
12943                worktree_id,
12944                file,
12945            )
12946        });
12947
12948        let mut templates_with_tags = mem::take(&mut runnable.tags)
12949            .into_iter()
12950            .flat_map(|RunnableTag(tag)| {
12951                inventory
12952                    .as_ref()
12953                    .into_iter()
12954                    .flat_map(|inventory| {
12955                        inventory.read(cx).list_tasks(
12956                            file.clone(),
12957                            Some(runnable.language.clone()),
12958                            worktree_id,
12959                            cx,
12960                        )
12961                    })
12962                    .filter(move |(_, template)| {
12963                        template.tags.iter().any(|source_tag| source_tag == &tag)
12964                    })
12965            })
12966            .sorted_by_key(|(kind, _)| kind.to_owned())
12967            .collect::<Vec<_>>();
12968        if let Some((leading_tag_source, _)) = templates_with_tags.first() {
12969            // Strongest source wins; if we have worktree tag binding, prefer that to
12970            // global and language bindings;
12971            // if we have a global binding, prefer that to language binding.
12972            let first_mismatch = templates_with_tags
12973                .iter()
12974                .position(|(tag_source, _)| tag_source != leading_tag_source);
12975            if let Some(index) = first_mismatch {
12976                templates_with_tags.truncate(index);
12977            }
12978        }
12979
12980        templates_with_tags
12981    }
12982
12983    pub fn move_to_enclosing_bracket(
12984        &mut self,
12985        _: &MoveToEnclosingBracket,
12986        window: &mut Window,
12987        cx: &mut Context<Self>,
12988    ) {
12989        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
12990        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
12991            s.move_offsets_with(|snapshot, selection| {
12992                let Some(enclosing_bracket_ranges) =
12993                    snapshot.enclosing_bracket_ranges(selection.start..selection.end)
12994                else {
12995                    return;
12996                };
12997
12998                let mut best_length = usize::MAX;
12999                let mut best_inside = false;
13000                let mut best_in_bracket_range = false;
13001                let mut best_destination = None;
13002                for (open, close) in enclosing_bracket_ranges {
13003                    let close = close.to_inclusive();
13004                    let length = close.end() - open.start;
13005                    let inside = selection.start >= open.end && selection.end <= *close.start();
13006                    let in_bracket_range = open.to_inclusive().contains(&selection.head())
13007                        || close.contains(&selection.head());
13008
13009                    // If best is next to a bracket and current isn't, skip
13010                    if !in_bracket_range && best_in_bracket_range {
13011                        continue;
13012                    }
13013
13014                    // Prefer smaller lengths unless best is inside and current isn't
13015                    if length > best_length && (best_inside || !inside) {
13016                        continue;
13017                    }
13018
13019                    best_length = length;
13020                    best_inside = inside;
13021                    best_in_bracket_range = in_bracket_range;
13022                    best_destination = Some(
13023                        if close.contains(&selection.start) && close.contains(&selection.end) {
13024                            if inside { open.end } else { open.start }
13025                        } else if inside {
13026                            *close.start()
13027                        } else {
13028                            *close.end()
13029                        },
13030                    );
13031                }
13032
13033                if let Some(destination) = best_destination {
13034                    selection.collapse_to(destination, SelectionGoal::None);
13035                }
13036            })
13037        });
13038    }
13039
13040    pub fn undo_selection(
13041        &mut self,
13042        _: &UndoSelection,
13043        window: &mut Window,
13044        cx: &mut Context<Self>,
13045    ) {
13046        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
13047        self.end_selection(window, cx);
13048        self.selection_history.mode = SelectionHistoryMode::Undoing;
13049        if let Some(entry) = self.selection_history.undo_stack.pop_back() {
13050            self.change_selections(None, window, cx, |s| {
13051                s.select_anchors(entry.selections.to_vec())
13052            });
13053            self.select_next_state = entry.select_next_state;
13054            self.select_prev_state = entry.select_prev_state;
13055            self.add_selections_state = entry.add_selections_state;
13056            self.request_autoscroll(Autoscroll::newest(), cx);
13057        }
13058        self.selection_history.mode = SelectionHistoryMode::Normal;
13059    }
13060
13061    pub fn redo_selection(
13062        &mut self,
13063        _: &RedoSelection,
13064        window: &mut Window,
13065        cx: &mut Context<Self>,
13066    ) {
13067        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
13068        self.end_selection(window, cx);
13069        self.selection_history.mode = SelectionHistoryMode::Redoing;
13070        if let Some(entry) = self.selection_history.redo_stack.pop_back() {
13071            self.change_selections(None, window, cx, |s| {
13072                s.select_anchors(entry.selections.to_vec())
13073            });
13074            self.select_next_state = entry.select_next_state;
13075            self.select_prev_state = entry.select_prev_state;
13076            self.add_selections_state = entry.add_selections_state;
13077            self.request_autoscroll(Autoscroll::newest(), cx);
13078        }
13079        self.selection_history.mode = SelectionHistoryMode::Normal;
13080    }
13081
13082    pub fn expand_excerpts(
13083        &mut self,
13084        action: &ExpandExcerpts,
13085        _: &mut Window,
13086        cx: &mut Context<Self>,
13087    ) {
13088        self.expand_excerpts_for_direction(action.lines, ExpandExcerptDirection::UpAndDown, cx)
13089    }
13090
13091    pub fn expand_excerpts_down(
13092        &mut self,
13093        action: &ExpandExcerptsDown,
13094        _: &mut Window,
13095        cx: &mut Context<Self>,
13096    ) {
13097        self.expand_excerpts_for_direction(action.lines, ExpandExcerptDirection::Down, cx)
13098    }
13099
13100    pub fn expand_excerpts_up(
13101        &mut self,
13102        action: &ExpandExcerptsUp,
13103        _: &mut Window,
13104        cx: &mut Context<Self>,
13105    ) {
13106        self.expand_excerpts_for_direction(action.lines, ExpandExcerptDirection::Up, cx)
13107    }
13108
13109    pub fn expand_excerpts_for_direction(
13110        &mut self,
13111        lines: u32,
13112        direction: ExpandExcerptDirection,
13113
13114        cx: &mut Context<Self>,
13115    ) {
13116        let selections = self.selections.disjoint_anchors();
13117
13118        let lines = if lines == 0 {
13119            EditorSettings::get_global(cx).expand_excerpt_lines
13120        } else {
13121            lines
13122        };
13123
13124        self.buffer.update(cx, |buffer, cx| {
13125            let snapshot = buffer.snapshot(cx);
13126            let mut excerpt_ids = selections
13127                .iter()
13128                .flat_map(|selection| snapshot.excerpt_ids_for_range(selection.range()))
13129                .collect::<Vec<_>>();
13130            excerpt_ids.sort();
13131            excerpt_ids.dedup();
13132            buffer.expand_excerpts(excerpt_ids, lines, direction, cx)
13133        })
13134    }
13135
13136    pub fn expand_excerpt(
13137        &mut self,
13138        excerpt: ExcerptId,
13139        direction: ExpandExcerptDirection,
13140        window: &mut Window,
13141        cx: &mut Context<Self>,
13142    ) {
13143        let current_scroll_position = self.scroll_position(cx);
13144        let lines_to_expand = EditorSettings::get_global(cx).expand_excerpt_lines;
13145        let mut should_scroll_up = false;
13146
13147        if direction == ExpandExcerptDirection::Down {
13148            let multi_buffer = self.buffer.read(cx);
13149            let snapshot = multi_buffer.snapshot(cx);
13150            if let Some(buffer_id) = snapshot.buffer_id_for_excerpt(excerpt) {
13151                if let Some(buffer) = multi_buffer.buffer(buffer_id) {
13152                    if let Some(excerpt_range) = snapshot.buffer_range_for_excerpt(excerpt) {
13153                        let buffer_snapshot = buffer.read(cx).snapshot();
13154                        let excerpt_end_row =
13155                            Point::from_anchor(&excerpt_range.end, &buffer_snapshot).row;
13156                        let last_row = buffer_snapshot.max_point().row;
13157                        let lines_below = last_row.saturating_sub(excerpt_end_row);
13158                        should_scroll_up = lines_below >= lines_to_expand;
13159                    }
13160                }
13161            }
13162        }
13163
13164        self.buffer.update(cx, |buffer, cx| {
13165            buffer.expand_excerpts([excerpt], lines_to_expand, direction, cx)
13166        });
13167
13168        if should_scroll_up {
13169            let new_scroll_position =
13170                current_scroll_position + gpui::Point::new(0.0, lines_to_expand as f32);
13171            self.set_scroll_position(new_scroll_position, window, cx);
13172        }
13173    }
13174
13175    pub fn go_to_singleton_buffer_point(
13176        &mut self,
13177        point: Point,
13178        window: &mut Window,
13179        cx: &mut Context<Self>,
13180    ) {
13181        self.go_to_singleton_buffer_range(point..point, window, cx);
13182    }
13183
13184    pub fn go_to_singleton_buffer_range(
13185        &mut self,
13186        range: Range<Point>,
13187        window: &mut Window,
13188        cx: &mut Context<Self>,
13189    ) {
13190        let multibuffer = self.buffer().read(cx);
13191        let Some(buffer) = multibuffer.as_singleton() else {
13192            return;
13193        };
13194        let Some(start) = multibuffer.buffer_point_to_anchor(&buffer, range.start, cx) else {
13195            return;
13196        };
13197        let Some(end) = multibuffer.buffer_point_to_anchor(&buffer, range.end, cx) else {
13198            return;
13199        };
13200        self.change_selections(Some(Autoscroll::center()), window, cx, |s| {
13201            s.select_anchor_ranges([start..end])
13202        });
13203    }
13204
13205    pub fn go_to_diagnostic(
13206        &mut self,
13207        _: &GoToDiagnostic,
13208        window: &mut Window,
13209        cx: &mut Context<Self>,
13210    ) {
13211        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
13212        self.go_to_diagnostic_impl(Direction::Next, window, cx)
13213    }
13214
13215    pub fn go_to_prev_diagnostic(
13216        &mut self,
13217        _: &GoToPreviousDiagnostic,
13218        window: &mut Window,
13219        cx: &mut Context<Self>,
13220    ) {
13221        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
13222        self.go_to_diagnostic_impl(Direction::Prev, window, cx)
13223    }
13224
13225    pub fn go_to_diagnostic_impl(
13226        &mut self,
13227        direction: Direction,
13228        window: &mut Window,
13229        cx: &mut Context<Self>,
13230    ) {
13231        let buffer = self.buffer.read(cx).snapshot(cx);
13232        let selection = self.selections.newest::<usize>(cx);
13233
13234        let mut active_group_id = None;
13235        if let ActiveDiagnostic::Group(active_group) = &self.active_diagnostics {
13236            if active_group.active_range.start.to_offset(&buffer) == selection.start {
13237                active_group_id = Some(active_group.group_id);
13238            }
13239        }
13240
13241        fn filtered(
13242            snapshot: EditorSnapshot,
13243            diagnostics: impl Iterator<Item = DiagnosticEntry<usize>>,
13244        ) -> impl Iterator<Item = DiagnosticEntry<usize>> {
13245            diagnostics
13246                .filter(|entry| entry.range.start != entry.range.end)
13247                .filter(|entry| !entry.diagnostic.is_unnecessary)
13248                .filter(move |entry| !snapshot.intersects_fold(entry.range.start))
13249        }
13250
13251        let snapshot = self.snapshot(window, cx);
13252        let before = filtered(
13253            snapshot.clone(),
13254            buffer
13255                .diagnostics_in_range(0..selection.start)
13256                .filter(|entry| entry.range.start <= selection.start),
13257        );
13258        let after = filtered(
13259            snapshot,
13260            buffer
13261                .diagnostics_in_range(selection.start..buffer.len())
13262                .filter(|entry| entry.range.start >= selection.start),
13263        );
13264
13265        let mut found: Option<DiagnosticEntry<usize>> = None;
13266        if direction == Direction::Prev {
13267            'outer: for prev_diagnostics in [before.collect::<Vec<_>>(), after.collect::<Vec<_>>()]
13268            {
13269                for diagnostic in prev_diagnostics.into_iter().rev() {
13270                    if diagnostic.range.start != selection.start
13271                        || active_group_id
13272                            .is_some_and(|active| diagnostic.diagnostic.group_id < active)
13273                    {
13274                        found = Some(diagnostic);
13275                        break 'outer;
13276                    }
13277                }
13278            }
13279        } else {
13280            for diagnostic in after.chain(before) {
13281                if diagnostic.range.start != selection.start
13282                    || active_group_id.is_some_and(|active| diagnostic.diagnostic.group_id > active)
13283                {
13284                    found = Some(diagnostic);
13285                    break;
13286                }
13287            }
13288        }
13289        let Some(next_diagnostic) = found else {
13290            return;
13291        };
13292
13293        let Some(buffer_id) = buffer.anchor_after(next_diagnostic.range.start).buffer_id else {
13294            return;
13295        };
13296        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
13297            s.select_ranges(vec![
13298                next_diagnostic.range.start..next_diagnostic.range.start,
13299            ])
13300        });
13301        self.activate_diagnostics(buffer_id, next_diagnostic, window, cx);
13302        self.refresh_inline_completion(false, true, window, cx);
13303    }
13304
13305    fn go_to_next_hunk(&mut self, _: &GoToHunk, window: &mut Window, cx: &mut Context<Self>) {
13306        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
13307        let snapshot = self.snapshot(window, cx);
13308        let selection = self.selections.newest::<Point>(cx);
13309        self.go_to_hunk_before_or_after_position(
13310            &snapshot,
13311            selection.head(),
13312            Direction::Next,
13313            window,
13314            cx,
13315        );
13316    }
13317
13318    pub fn go_to_hunk_before_or_after_position(
13319        &mut self,
13320        snapshot: &EditorSnapshot,
13321        position: Point,
13322        direction: Direction,
13323        window: &mut Window,
13324        cx: &mut Context<Editor>,
13325    ) {
13326        let row = if direction == Direction::Next {
13327            self.hunk_after_position(snapshot, position)
13328                .map(|hunk| hunk.row_range.start)
13329        } else {
13330            self.hunk_before_position(snapshot, position)
13331        };
13332
13333        if let Some(row) = row {
13334            let destination = Point::new(row.0, 0);
13335            let autoscroll = Autoscroll::center();
13336
13337            self.unfold_ranges(&[destination..destination], false, false, cx);
13338            self.change_selections(Some(autoscroll), window, cx, |s| {
13339                s.select_ranges([destination..destination]);
13340            });
13341        }
13342    }
13343
13344    fn hunk_after_position(
13345        &mut self,
13346        snapshot: &EditorSnapshot,
13347        position: Point,
13348    ) -> Option<MultiBufferDiffHunk> {
13349        snapshot
13350            .buffer_snapshot
13351            .diff_hunks_in_range(position..snapshot.buffer_snapshot.max_point())
13352            .find(|hunk| hunk.row_range.start.0 > position.row)
13353            .or_else(|| {
13354                snapshot
13355                    .buffer_snapshot
13356                    .diff_hunks_in_range(Point::zero()..position)
13357                    .find(|hunk| hunk.row_range.end.0 < position.row)
13358            })
13359    }
13360
13361    fn go_to_prev_hunk(
13362        &mut self,
13363        _: &GoToPreviousHunk,
13364        window: &mut Window,
13365        cx: &mut Context<Self>,
13366    ) {
13367        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
13368        let snapshot = self.snapshot(window, cx);
13369        let selection = self.selections.newest::<Point>(cx);
13370        self.go_to_hunk_before_or_after_position(
13371            &snapshot,
13372            selection.head(),
13373            Direction::Prev,
13374            window,
13375            cx,
13376        );
13377    }
13378
13379    fn hunk_before_position(
13380        &mut self,
13381        snapshot: &EditorSnapshot,
13382        position: Point,
13383    ) -> Option<MultiBufferRow> {
13384        snapshot
13385            .buffer_snapshot
13386            .diff_hunk_before(position)
13387            .or_else(|| snapshot.buffer_snapshot.diff_hunk_before(Point::MAX))
13388    }
13389
13390    fn go_to_next_change(
13391        &mut self,
13392        _: &GoToNextChange,
13393        window: &mut Window,
13394        cx: &mut Context<Self>,
13395    ) {
13396        if let Some(selections) = self
13397            .change_list
13398            .next_change(1, Direction::Next)
13399            .map(|s| s.to_vec())
13400        {
13401            self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
13402                let map = s.display_map();
13403                s.select_display_ranges(selections.iter().map(|a| {
13404                    let point = a.to_display_point(&map);
13405                    point..point
13406                }))
13407            })
13408        }
13409    }
13410
13411    fn go_to_previous_change(
13412        &mut self,
13413        _: &GoToPreviousChange,
13414        window: &mut Window,
13415        cx: &mut Context<Self>,
13416    ) {
13417        if let Some(selections) = self
13418            .change_list
13419            .next_change(1, Direction::Prev)
13420            .map(|s| s.to_vec())
13421        {
13422            self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
13423                let map = s.display_map();
13424                s.select_display_ranges(selections.iter().map(|a| {
13425                    let point = a.to_display_point(&map);
13426                    point..point
13427                }))
13428            })
13429        }
13430    }
13431
13432    fn go_to_line<T: 'static>(
13433        &mut self,
13434        position: Anchor,
13435        highlight_color: Option<Hsla>,
13436        window: &mut Window,
13437        cx: &mut Context<Self>,
13438    ) {
13439        let snapshot = self.snapshot(window, cx).display_snapshot;
13440        let position = position.to_point(&snapshot.buffer_snapshot);
13441        let start = snapshot
13442            .buffer_snapshot
13443            .clip_point(Point::new(position.row, 0), Bias::Left);
13444        let end = start + Point::new(1, 0);
13445        let start = snapshot.buffer_snapshot.anchor_before(start);
13446        let end = snapshot.buffer_snapshot.anchor_before(end);
13447
13448        self.highlight_rows::<T>(
13449            start..end,
13450            highlight_color
13451                .unwrap_or_else(|| cx.theme().colors().editor_highlighted_line_background),
13452            false,
13453            cx,
13454        );
13455        self.request_autoscroll(Autoscroll::center().for_anchor(start), cx);
13456    }
13457
13458    pub fn go_to_definition(
13459        &mut self,
13460        _: &GoToDefinition,
13461        window: &mut Window,
13462        cx: &mut Context<Self>,
13463    ) -> Task<Result<Navigated>> {
13464        let definition =
13465            self.go_to_definition_of_kind(GotoDefinitionKind::Symbol, false, window, cx);
13466        let fallback_strategy = EditorSettings::get_global(cx).go_to_definition_fallback;
13467        cx.spawn_in(window, async move |editor, cx| {
13468            if definition.await? == Navigated::Yes {
13469                return Ok(Navigated::Yes);
13470            }
13471            match fallback_strategy {
13472                GoToDefinitionFallback::None => Ok(Navigated::No),
13473                GoToDefinitionFallback::FindAllReferences => {
13474                    match editor.update_in(cx, |editor, window, cx| {
13475                        editor.find_all_references(&FindAllReferences, window, cx)
13476                    })? {
13477                        Some(references) => references.await,
13478                        None => Ok(Navigated::No),
13479                    }
13480                }
13481            }
13482        })
13483    }
13484
13485    pub fn go_to_declaration(
13486        &mut self,
13487        _: &GoToDeclaration,
13488        window: &mut Window,
13489        cx: &mut Context<Self>,
13490    ) -> Task<Result<Navigated>> {
13491        self.go_to_definition_of_kind(GotoDefinitionKind::Declaration, false, window, cx)
13492    }
13493
13494    pub fn go_to_declaration_split(
13495        &mut self,
13496        _: &GoToDeclaration,
13497        window: &mut Window,
13498        cx: &mut Context<Self>,
13499    ) -> Task<Result<Navigated>> {
13500        self.go_to_definition_of_kind(GotoDefinitionKind::Declaration, true, window, cx)
13501    }
13502
13503    pub fn go_to_implementation(
13504        &mut self,
13505        _: &GoToImplementation,
13506        window: &mut Window,
13507        cx: &mut Context<Self>,
13508    ) -> Task<Result<Navigated>> {
13509        self.go_to_definition_of_kind(GotoDefinitionKind::Implementation, false, window, cx)
13510    }
13511
13512    pub fn go_to_implementation_split(
13513        &mut self,
13514        _: &GoToImplementationSplit,
13515        window: &mut Window,
13516        cx: &mut Context<Self>,
13517    ) -> Task<Result<Navigated>> {
13518        self.go_to_definition_of_kind(GotoDefinitionKind::Implementation, true, window, cx)
13519    }
13520
13521    pub fn go_to_type_definition(
13522        &mut self,
13523        _: &GoToTypeDefinition,
13524        window: &mut Window,
13525        cx: &mut Context<Self>,
13526    ) -> Task<Result<Navigated>> {
13527        self.go_to_definition_of_kind(GotoDefinitionKind::Type, false, window, cx)
13528    }
13529
13530    pub fn go_to_definition_split(
13531        &mut self,
13532        _: &GoToDefinitionSplit,
13533        window: &mut Window,
13534        cx: &mut Context<Self>,
13535    ) -> Task<Result<Navigated>> {
13536        self.go_to_definition_of_kind(GotoDefinitionKind::Symbol, true, window, cx)
13537    }
13538
13539    pub fn go_to_type_definition_split(
13540        &mut self,
13541        _: &GoToTypeDefinitionSplit,
13542        window: &mut Window,
13543        cx: &mut Context<Self>,
13544    ) -> Task<Result<Navigated>> {
13545        self.go_to_definition_of_kind(GotoDefinitionKind::Type, true, window, cx)
13546    }
13547
13548    fn go_to_definition_of_kind(
13549        &mut self,
13550        kind: GotoDefinitionKind,
13551        split: bool,
13552        window: &mut Window,
13553        cx: &mut Context<Self>,
13554    ) -> Task<Result<Navigated>> {
13555        let Some(provider) = self.semantics_provider.clone() else {
13556            return Task::ready(Ok(Navigated::No));
13557        };
13558        let head = self.selections.newest::<usize>(cx).head();
13559        let buffer = self.buffer.read(cx);
13560        let (buffer, head) = if let Some(text_anchor) = buffer.text_anchor_for_position(head, cx) {
13561            text_anchor
13562        } else {
13563            return Task::ready(Ok(Navigated::No));
13564        };
13565
13566        let Some(definitions) = provider.definitions(&buffer, head, kind, cx) else {
13567            return Task::ready(Ok(Navigated::No));
13568        };
13569
13570        cx.spawn_in(window, async move |editor, cx| {
13571            let definitions = definitions.await?;
13572            let navigated = editor
13573                .update_in(cx, |editor, window, cx| {
13574                    editor.navigate_to_hover_links(
13575                        Some(kind),
13576                        definitions
13577                            .into_iter()
13578                            .filter(|location| {
13579                                hover_links::exclude_link_to_position(&buffer, &head, location, cx)
13580                            })
13581                            .map(HoverLink::Text)
13582                            .collect::<Vec<_>>(),
13583                        split,
13584                        window,
13585                        cx,
13586                    )
13587                })?
13588                .await?;
13589            anyhow::Ok(navigated)
13590        })
13591    }
13592
13593    pub fn open_url(&mut self, _: &OpenUrl, window: &mut Window, cx: &mut Context<Self>) {
13594        let selection = self.selections.newest_anchor();
13595        let head = selection.head();
13596        let tail = selection.tail();
13597
13598        let Some((buffer, start_position)) =
13599            self.buffer.read(cx).text_anchor_for_position(head, cx)
13600        else {
13601            return;
13602        };
13603
13604        let end_position = if head != tail {
13605            let Some((_, pos)) = self.buffer.read(cx).text_anchor_for_position(tail, cx) else {
13606                return;
13607            };
13608            Some(pos)
13609        } else {
13610            None
13611        };
13612
13613        let url_finder = cx.spawn_in(window, async move |editor, cx| {
13614            let url = if let Some(end_pos) = end_position {
13615                find_url_from_range(&buffer, start_position..end_pos, cx.clone())
13616            } else {
13617                find_url(&buffer, start_position, cx.clone()).map(|(_, url)| url)
13618            };
13619
13620            if let Some(url) = url {
13621                editor.update(cx, |_, cx| {
13622                    cx.open_url(&url);
13623                })
13624            } else {
13625                Ok(())
13626            }
13627        });
13628
13629        url_finder.detach();
13630    }
13631
13632    pub fn open_selected_filename(
13633        &mut self,
13634        _: &OpenSelectedFilename,
13635        window: &mut Window,
13636        cx: &mut Context<Self>,
13637    ) {
13638        let Some(workspace) = self.workspace() else {
13639            return;
13640        };
13641
13642        let position = self.selections.newest_anchor().head();
13643
13644        let Some((buffer, buffer_position)) =
13645            self.buffer.read(cx).text_anchor_for_position(position, cx)
13646        else {
13647            return;
13648        };
13649
13650        let project = self.project.clone();
13651
13652        cx.spawn_in(window, async move |_, cx| {
13653            let result = find_file(&buffer, project, buffer_position, cx).await;
13654
13655            if let Some((_, path)) = result {
13656                workspace
13657                    .update_in(cx, |workspace, window, cx| {
13658                        workspace.open_resolved_path(path, window, cx)
13659                    })?
13660                    .await?;
13661            }
13662            anyhow::Ok(())
13663        })
13664        .detach();
13665    }
13666
13667    pub(crate) fn navigate_to_hover_links(
13668        &mut self,
13669        kind: Option<GotoDefinitionKind>,
13670        mut definitions: Vec<HoverLink>,
13671        split: bool,
13672        window: &mut Window,
13673        cx: &mut Context<Editor>,
13674    ) -> Task<Result<Navigated>> {
13675        // If there is one definition, just open it directly
13676        if definitions.len() == 1 {
13677            let definition = definitions.pop().unwrap();
13678
13679            enum TargetTaskResult {
13680                Location(Option<Location>),
13681                AlreadyNavigated,
13682            }
13683
13684            let target_task = match definition {
13685                HoverLink::Text(link) => {
13686                    Task::ready(anyhow::Ok(TargetTaskResult::Location(Some(link.target))))
13687                }
13688                HoverLink::InlayHint(lsp_location, server_id) => {
13689                    let computation =
13690                        self.compute_target_location(lsp_location, server_id, window, cx);
13691                    cx.background_spawn(async move {
13692                        let location = computation.await?;
13693                        Ok(TargetTaskResult::Location(location))
13694                    })
13695                }
13696                HoverLink::Url(url) => {
13697                    cx.open_url(&url);
13698                    Task::ready(Ok(TargetTaskResult::AlreadyNavigated))
13699                }
13700                HoverLink::File(path) => {
13701                    if let Some(workspace) = self.workspace() {
13702                        cx.spawn_in(window, async move |_, cx| {
13703                            workspace
13704                                .update_in(cx, |workspace, window, cx| {
13705                                    workspace.open_resolved_path(path, window, cx)
13706                                })?
13707                                .await
13708                                .map(|_| TargetTaskResult::AlreadyNavigated)
13709                        })
13710                    } else {
13711                        Task::ready(Ok(TargetTaskResult::Location(None)))
13712                    }
13713                }
13714            };
13715            cx.spawn_in(window, async move |editor, cx| {
13716                let target = match target_task.await.context("target resolution task")? {
13717                    TargetTaskResult::AlreadyNavigated => return Ok(Navigated::Yes),
13718                    TargetTaskResult::Location(None) => return Ok(Navigated::No),
13719                    TargetTaskResult::Location(Some(target)) => target,
13720                };
13721
13722                editor.update_in(cx, |editor, window, cx| {
13723                    let Some(workspace) = editor.workspace() else {
13724                        return Navigated::No;
13725                    };
13726                    let pane = workspace.read(cx).active_pane().clone();
13727
13728                    let range = target.range.to_point(target.buffer.read(cx));
13729                    let range = editor.range_for_match(&range);
13730                    let range = collapse_multiline_range(range);
13731
13732                    if !split
13733                        && Some(&target.buffer) == editor.buffer.read(cx).as_singleton().as_ref()
13734                    {
13735                        editor.go_to_singleton_buffer_range(range.clone(), window, cx);
13736                    } else {
13737                        window.defer(cx, move |window, cx| {
13738                            let target_editor: Entity<Self> =
13739                                workspace.update(cx, |workspace, cx| {
13740                                    let pane = if split {
13741                                        workspace.adjacent_pane(window, cx)
13742                                    } else {
13743                                        workspace.active_pane().clone()
13744                                    };
13745
13746                                    workspace.open_project_item(
13747                                        pane,
13748                                        target.buffer.clone(),
13749                                        true,
13750                                        true,
13751                                        window,
13752                                        cx,
13753                                    )
13754                                });
13755                            target_editor.update(cx, |target_editor, cx| {
13756                                // When selecting a definition in a different buffer, disable the nav history
13757                                // to avoid creating a history entry at the previous cursor location.
13758                                pane.update(cx, |pane, _| pane.disable_history());
13759                                target_editor.go_to_singleton_buffer_range(range, window, cx);
13760                                pane.update(cx, |pane, _| pane.enable_history());
13761                            });
13762                        });
13763                    }
13764                    Navigated::Yes
13765                })
13766            })
13767        } else if !definitions.is_empty() {
13768            cx.spawn_in(window, async move |editor, cx| {
13769                let (title, location_tasks, workspace) = editor
13770                    .update_in(cx, |editor, window, cx| {
13771                        let tab_kind = match kind {
13772                            Some(GotoDefinitionKind::Implementation) => "Implementations",
13773                            _ => "Definitions",
13774                        };
13775                        let title = definitions
13776                            .iter()
13777                            .find_map(|definition| match definition {
13778                                HoverLink::Text(link) => link.origin.as_ref().map(|origin| {
13779                                    let buffer = origin.buffer.read(cx);
13780                                    format!(
13781                                        "{} for {}",
13782                                        tab_kind,
13783                                        buffer
13784                                            .text_for_range(origin.range.clone())
13785                                            .collect::<String>()
13786                                    )
13787                                }),
13788                                HoverLink::InlayHint(_, _) => None,
13789                                HoverLink::Url(_) => None,
13790                                HoverLink::File(_) => None,
13791                            })
13792                            .unwrap_or(tab_kind.to_string());
13793                        let location_tasks = definitions
13794                            .into_iter()
13795                            .map(|definition| match definition {
13796                                HoverLink::Text(link) => Task::ready(Ok(Some(link.target))),
13797                                HoverLink::InlayHint(lsp_location, server_id) => editor
13798                                    .compute_target_location(lsp_location, server_id, window, cx),
13799                                HoverLink::Url(_) => Task::ready(Ok(None)),
13800                                HoverLink::File(_) => Task::ready(Ok(None)),
13801                            })
13802                            .collect::<Vec<_>>();
13803                        (title, location_tasks, editor.workspace().clone())
13804                    })
13805                    .context("location tasks preparation")?;
13806
13807                let locations = future::join_all(location_tasks)
13808                    .await
13809                    .into_iter()
13810                    .filter_map(|location| location.transpose())
13811                    .collect::<Result<_>>()
13812                    .context("location tasks")?;
13813
13814                let Some(workspace) = workspace else {
13815                    return Ok(Navigated::No);
13816                };
13817                let opened = workspace
13818                    .update_in(cx, |workspace, window, cx| {
13819                        Self::open_locations_in_multibuffer(
13820                            workspace,
13821                            locations,
13822                            title,
13823                            split,
13824                            MultibufferSelectionMode::First,
13825                            window,
13826                            cx,
13827                        )
13828                    })
13829                    .ok();
13830
13831                anyhow::Ok(Navigated::from_bool(opened.is_some()))
13832            })
13833        } else {
13834            Task::ready(Ok(Navigated::No))
13835        }
13836    }
13837
13838    fn compute_target_location(
13839        &self,
13840        lsp_location: lsp::Location,
13841        server_id: LanguageServerId,
13842        window: &mut Window,
13843        cx: &mut Context<Self>,
13844    ) -> Task<anyhow::Result<Option<Location>>> {
13845        let Some(project) = self.project.clone() else {
13846            return Task::ready(Ok(None));
13847        };
13848
13849        cx.spawn_in(window, async move |editor, cx| {
13850            let location_task = editor.update(cx, |_, cx| {
13851                project.update(cx, |project, cx| {
13852                    let language_server_name = project
13853                        .language_server_statuses(cx)
13854                        .find(|(id, _)| server_id == *id)
13855                        .map(|(_, status)| LanguageServerName::from(status.name.as_str()));
13856                    language_server_name.map(|language_server_name| {
13857                        project.open_local_buffer_via_lsp(
13858                            lsp_location.uri.clone(),
13859                            server_id,
13860                            language_server_name,
13861                            cx,
13862                        )
13863                    })
13864                })
13865            })?;
13866            let location = match location_task {
13867                Some(task) => Some({
13868                    let target_buffer_handle = task.await.context("open local buffer")?;
13869                    let range = target_buffer_handle.update(cx, |target_buffer, _| {
13870                        let target_start = target_buffer
13871                            .clip_point_utf16(point_from_lsp(lsp_location.range.start), Bias::Left);
13872                        let target_end = target_buffer
13873                            .clip_point_utf16(point_from_lsp(lsp_location.range.end), Bias::Left);
13874                        target_buffer.anchor_after(target_start)
13875                            ..target_buffer.anchor_before(target_end)
13876                    })?;
13877                    Location {
13878                        buffer: target_buffer_handle,
13879                        range,
13880                    }
13881                }),
13882                None => None,
13883            };
13884            Ok(location)
13885        })
13886    }
13887
13888    pub fn find_all_references(
13889        &mut self,
13890        _: &FindAllReferences,
13891        window: &mut Window,
13892        cx: &mut Context<Self>,
13893    ) -> Option<Task<Result<Navigated>>> {
13894        let selection = self.selections.newest::<usize>(cx);
13895        let multi_buffer = self.buffer.read(cx);
13896        let head = selection.head();
13897
13898        let multi_buffer_snapshot = multi_buffer.snapshot(cx);
13899        let head_anchor = multi_buffer_snapshot.anchor_at(
13900            head,
13901            if head < selection.tail() {
13902                Bias::Right
13903            } else {
13904                Bias::Left
13905            },
13906        );
13907
13908        match self
13909            .find_all_references_task_sources
13910            .binary_search_by(|anchor| anchor.cmp(&head_anchor, &multi_buffer_snapshot))
13911        {
13912            Ok(_) => {
13913                log::info!(
13914                    "Ignoring repeated FindAllReferences invocation with the position of already running task"
13915                );
13916                return None;
13917            }
13918            Err(i) => {
13919                self.find_all_references_task_sources.insert(i, head_anchor);
13920            }
13921        }
13922
13923        let (buffer, head) = multi_buffer.text_anchor_for_position(head, cx)?;
13924        let workspace = self.workspace()?;
13925        let project = workspace.read(cx).project().clone();
13926        let references = project.update(cx, |project, cx| project.references(&buffer, head, cx));
13927        Some(cx.spawn_in(window, async move |editor, cx| {
13928            let _cleanup = cx.on_drop(&editor, move |editor, _| {
13929                if let Ok(i) = editor
13930                    .find_all_references_task_sources
13931                    .binary_search_by(|anchor| anchor.cmp(&head_anchor, &multi_buffer_snapshot))
13932                {
13933                    editor.find_all_references_task_sources.remove(i);
13934                }
13935            });
13936
13937            let locations = references.await?;
13938            if locations.is_empty() {
13939                return anyhow::Ok(Navigated::No);
13940            }
13941
13942            workspace.update_in(cx, |workspace, window, cx| {
13943                let title = locations
13944                    .first()
13945                    .as_ref()
13946                    .map(|location| {
13947                        let buffer = location.buffer.read(cx);
13948                        format!(
13949                            "References to `{}`",
13950                            buffer
13951                                .text_for_range(location.range.clone())
13952                                .collect::<String>()
13953                        )
13954                    })
13955                    .unwrap();
13956                Self::open_locations_in_multibuffer(
13957                    workspace,
13958                    locations,
13959                    title,
13960                    false,
13961                    MultibufferSelectionMode::First,
13962                    window,
13963                    cx,
13964                );
13965                Navigated::Yes
13966            })
13967        }))
13968    }
13969
13970    /// Opens a multibuffer with the given project locations in it
13971    pub fn open_locations_in_multibuffer(
13972        workspace: &mut Workspace,
13973        mut locations: Vec<Location>,
13974        title: String,
13975        split: bool,
13976        multibuffer_selection_mode: MultibufferSelectionMode,
13977        window: &mut Window,
13978        cx: &mut Context<Workspace>,
13979    ) {
13980        // If there are multiple definitions, open them in a multibuffer
13981        locations.sort_by_key(|location| location.buffer.read(cx).remote_id());
13982        let mut locations = locations.into_iter().peekable();
13983        let mut ranges: Vec<Range<Anchor>> = Vec::new();
13984        let capability = workspace.project().read(cx).capability();
13985
13986        let excerpt_buffer = cx.new(|cx| {
13987            let mut multibuffer = MultiBuffer::new(capability);
13988            while let Some(location) = locations.next() {
13989                let buffer = location.buffer.read(cx);
13990                let mut ranges_for_buffer = Vec::new();
13991                let range = location.range.to_point(buffer);
13992                ranges_for_buffer.push(range.clone());
13993
13994                while let Some(next_location) = locations.peek() {
13995                    if next_location.buffer == location.buffer {
13996                        ranges_for_buffer.push(next_location.range.to_point(buffer));
13997                        locations.next();
13998                    } else {
13999                        break;
14000                    }
14001                }
14002
14003                ranges_for_buffer.sort_by_key(|range| (range.start, Reverse(range.end)));
14004                let (new_ranges, _) = multibuffer.set_excerpts_for_path(
14005                    PathKey::for_buffer(&location.buffer, cx),
14006                    location.buffer.clone(),
14007                    ranges_for_buffer,
14008                    DEFAULT_MULTIBUFFER_CONTEXT,
14009                    cx,
14010                );
14011                ranges.extend(new_ranges)
14012            }
14013
14014            multibuffer.with_title(title)
14015        });
14016
14017        let editor = cx.new(|cx| {
14018            Editor::for_multibuffer(
14019                excerpt_buffer,
14020                Some(workspace.project().clone()),
14021                window,
14022                cx,
14023            )
14024        });
14025        editor.update(cx, |editor, cx| {
14026            match multibuffer_selection_mode {
14027                MultibufferSelectionMode::First => {
14028                    if let Some(first_range) = ranges.first() {
14029                        editor.change_selections(None, window, cx, |selections| {
14030                            selections.clear_disjoint();
14031                            selections.select_anchor_ranges(std::iter::once(first_range.clone()));
14032                        });
14033                    }
14034                    editor.highlight_background::<Self>(
14035                        &ranges,
14036                        |theme| theme.editor_highlighted_line_background,
14037                        cx,
14038                    );
14039                }
14040                MultibufferSelectionMode::All => {
14041                    editor.change_selections(None, window, cx, |selections| {
14042                        selections.clear_disjoint();
14043                        selections.select_anchor_ranges(ranges);
14044                    });
14045                }
14046            }
14047            editor.register_buffers_with_language_servers(cx);
14048        });
14049
14050        let item = Box::new(editor);
14051        let item_id = item.item_id();
14052
14053        if split {
14054            workspace.split_item(SplitDirection::Right, item.clone(), window, cx);
14055        } else {
14056            if PreviewTabsSettings::get_global(cx).enable_preview_from_code_navigation {
14057                let (preview_item_id, preview_item_idx) =
14058                    workspace.active_pane().update(cx, |pane, _| {
14059                        (pane.preview_item_id(), pane.preview_item_idx())
14060                    });
14061
14062                workspace.add_item_to_active_pane(item.clone(), preview_item_idx, true, window, cx);
14063
14064                if let Some(preview_item_id) = preview_item_id {
14065                    workspace.active_pane().update(cx, |pane, cx| {
14066                        pane.remove_item(preview_item_id, false, false, window, cx);
14067                    });
14068                }
14069            } else {
14070                workspace.add_item_to_active_pane(item.clone(), None, true, window, cx);
14071            }
14072        }
14073        workspace.active_pane().update(cx, |pane, cx| {
14074            pane.set_preview_item_id(Some(item_id), cx);
14075        });
14076    }
14077
14078    pub fn rename(
14079        &mut self,
14080        _: &Rename,
14081        window: &mut Window,
14082        cx: &mut Context<Self>,
14083    ) -> Option<Task<Result<()>>> {
14084        use language::ToOffset as _;
14085
14086        let provider = self.semantics_provider.clone()?;
14087        let selection = self.selections.newest_anchor().clone();
14088        let (cursor_buffer, cursor_buffer_position) = self
14089            .buffer
14090            .read(cx)
14091            .text_anchor_for_position(selection.head(), cx)?;
14092        let (tail_buffer, cursor_buffer_position_end) = self
14093            .buffer
14094            .read(cx)
14095            .text_anchor_for_position(selection.tail(), cx)?;
14096        if tail_buffer != cursor_buffer {
14097            return None;
14098        }
14099
14100        let snapshot = cursor_buffer.read(cx).snapshot();
14101        let cursor_buffer_offset = cursor_buffer_position.to_offset(&snapshot);
14102        let cursor_buffer_offset_end = cursor_buffer_position_end.to_offset(&snapshot);
14103        let prepare_rename = provider
14104            .range_for_rename(&cursor_buffer, cursor_buffer_position, cx)
14105            .unwrap_or_else(|| Task::ready(Ok(None)));
14106        drop(snapshot);
14107
14108        Some(cx.spawn_in(window, async move |this, cx| {
14109            let rename_range = if let Some(range) = prepare_rename.await? {
14110                Some(range)
14111            } else {
14112                this.update(cx, |this, cx| {
14113                    let buffer = this.buffer.read(cx).snapshot(cx);
14114                    let mut buffer_highlights = this
14115                        .document_highlights_for_position(selection.head(), &buffer)
14116                        .filter(|highlight| {
14117                            highlight.start.excerpt_id == selection.head().excerpt_id
14118                                && highlight.end.excerpt_id == selection.head().excerpt_id
14119                        });
14120                    buffer_highlights
14121                        .next()
14122                        .map(|highlight| highlight.start.text_anchor..highlight.end.text_anchor)
14123                })?
14124            };
14125            if let Some(rename_range) = rename_range {
14126                this.update_in(cx, |this, window, cx| {
14127                    let snapshot = cursor_buffer.read(cx).snapshot();
14128                    let rename_buffer_range = rename_range.to_offset(&snapshot);
14129                    let cursor_offset_in_rename_range =
14130                        cursor_buffer_offset.saturating_sub(rename_buffer_range.start);
14131                    let cursor_offset_in_rename_range_end =
14132                        cursor_buffer_offset_end.saturating_sub(rename_buffer_range.start);
14133
14134                    this.take_rename(false, window, cx);
14135                    let buffer = this.buffer.read(cx).read(cx);
14136                    let cursor_offset = selection.head().to_offset(&buffer);
14137                    let rename_start = cursor_offset.saturating_sub(cursor_offset_in_rename_range);
14138                    let rename_end = rename_start + rename_buffer_range.len();
14139                    let range = buffer.anchor_before(rename_start)..buffer.anchor_after(rename_end);
14140                    let mut old_highlight_id = None;
14141                    let old_name: Arc<str> = buffer
14142                        .chunks(rename_start..rename_end, true)
14143                        .map(|chunk| {
14144                            if old_highlight_id.is_none() {
14145                                old_highlight_id = chunk.syntax_highlight_id;
14146                            }
14147                            chunk.text
14148                        })
14149                        .collect::<String>()
14150                        .into();
14151
14152                    drop(buffer);
14153
14154                    // Position the selection in the rename editor so that it matches the current selection.
14155                    this.show_local_selections = false;
14156                    let rename_editor = cx.new(|cx| {
14157                        let mut editor = Editor::single_line(window, cx);
14158                        editor.buffer.update(cx, |buffer, cx| {
14159                            buffer.edit([(0..0, old_name.clone())], None, cx)
14160                        });
14161                        let rename_selection_range = match cursor_offset_in_rename_range
14162                            .cmp(&cursor_offset_in_rename_range_end)
14163                        {
14164                            Ordering::Equal => {
14165                                editor.select_all(&SelectAll, window, cx);
14166                                return editor;
14167                            }
14168                            Ordering::Less => {
14169                                cursor_offset_in_rename_range..cursor_offset_in_rename_range_end
14170                            }
14171                            Ordering::Greater => {
14172                                cursor_offset_in_rename_range_end..cursor_offset_in_rename_range
14173                            }
14174                        };
14175                        if rename_selection_range.end > old_name.len() {
14176                            editor.select_all(&SelectAll, window, cx);
14177                        } else {
14178                            editor.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
14179                                s.select_ranges([rename_selection_range]);
14180                            });
14181                        }
14182                        editor
14183                    });
14184                    cx.subscribe(&rename_editor, |_, _, e: &EditorEvent, cx| {
14185                        if e == &EditorEvent::Focused {
14186                            cx.emit(EditorEvent::FocusedIn)
14187                        }
14188                    })
14189                    .detach();
14190
14191                    let write_highlights =
14192                        this.clear_background_highlights::<DocumentHighlightWrite>(cx);
14193                    let read_highlights =
14194                        this.clear_background_highlights::<DocumentHighlightRead>(cx);
14195                    let ranges = write_highlights
14196                        .iter()
14197                        .flat_map(|(_, ranges)| ranges.iter())
14198                        .chain(read_highlights.iter().flat_map(|(_, ranges)| ranges.iter()))
14199                        .cloned()
14200                        .collect();
14201
14202                    this.highlight_text::<Rename>(
14203                        ranges,
14204                        HighlightStyle {
14205                            fade_out: Some(0.6),
14206                            ..Default::default()
14207                        },
14208                        cx,
14209                    );
14210                    let rename_focus_handle = rename_editor.focus_handle(cx);
14211                    window.focus(&rename_focus_handle);
14212                    let block_id = this.insert_blocks(
14213                        [BlockProperties {
14214                            style: BlockStyle::Flex,
14215                            placement: BlockPlacement::Below(range.start),
14216                            height: Some(1),
14217                            render: Arc::new({
14218                                let rename_editor = rename_editor.clone();
14219                                move |cx: &mut BlockContext| {
14220                                    let mut text_style = cx.editor_style.text.clone();
14221                                    if let Some(highlight_style) = old_highlight_id
14222                                        .and_then(|h| h.style(&cx.editor_style.syntax))
14223                                    {
14224                                        text_style = text_style.highlight(highlight_style);
14225                                    }
14226                                    div()
14227                                        .block_mouse_down()
14228                                        .pl(cx.anchor_x)
14229                                        .child(EditorElement::new(
14230                                            &rename_editor,
14231                                            EditorStyle {
14232                                                background: cx.theme().system().transparent,
14233                                                local_player: cx.editor_style.local_player,
14234                                                text: text_style,
14235                                                scrollbar_width: cx.editor_style.scrollbar_width,
14236                                                syntax: cx.editor_style.syntax.clone(),
14237                                                status: cx.editor_style.status.clone(),
14238                                                inlay_hints_style: HighlightStyle {
14239                                                    font_weight: Some(FontWeight::BOLD),
14240                                                    ..make_inlay_hints_style(cx.app)
14241                                                },
14242                                                inline_completion_styles: make_suggestion_styles(
14243                                                    cx.app,
14244                                                ),
14245                                                ..EditorStyle::default()
14246                                            },
14247                                        ))
14248                                        .into_any_element()
14249                                }
14250                            }),
14251                            priority: 0,
14252                        }],
14253                        Some(Autoscroll::fit()),
14254                        cx,
14255                    )[0];
14256                    this.pending_rename = Some(RenameState {
14257                        range,
14258                        old_name,
14259                        editor: rename_editor,
14260                        block_id,
14261                    });
14262                })?;
14263            }
14264
14265            Ok(())
14266        }))
14267    }
14268
14269    pub fn confirm_rename(
14270        &mut self,
14271        _: &ConfirmRename,
14272        window: &mut Window,
14273        cx: &mut Context<Self>,
14274    ) -> Option<Task<Result<()>>> {
14275        let rename = self.take_rename(false, window, cx)?;
14276        let workspace = self.workspace()?.downgrade();
14277        let (buffer, start) = self
14278            .buffer
14279            .read(cx)
14280            .text_anchor_for_position(rename.range.start, cx)?;
14281        let (end_buffer, _) = self
14282            .buffer
14283            .read(cx)
14284            .text_anchor_for_position(rename.range.end, cx)?;
14285        if buffer != end_buffer {
14286            return None;
14287        }
14288
14289        let old_name = rename.old_name;
14290        let new_name = rename.editor.read(cx).text(cx);
14291
14292        let rename = self.semantics_provider.as_ref()?.perform_rename(
14293            &buffer,
14294            start,
14295            new_name.clone(),
14296            cx,
14297        )?;
14298
14299        Some(cx.spawn_in(window, async move |editor, cx| {
14300            let project_transaction = rename.await?;
14301            Self::open_project_transaction(
14302                &editor,
14303                workspace,
14304                project_transaction,
14305                format!("Rename: {}{}", old_name, new_name),
14306                cx,
14307            )
14308            .await?;
14309
14310            editor.update(cx, |editor, cx| {
14311                editor.refresh_document_highlights(cx);
14312            })?;
14313            Ok(())
14314        }))
14315    }
14316
14317    fn take_rename(
14318        &mut self,
14319        moving_cursor: bool,
14320        window: &mut Window,
14321        cx: &mut Context<Self>,
14322    ) -> Option<RenameState> {
14323        let rename = self.pending_rename.take()?;
14324        if rename.editor.focus_handle(cx).is_focused(window) {
14325            window.focus(&self.focus_handle);
14326        }
14327
14328        self.remove_blocks(
14329            [rename.block_id].into_iter().collect(),
14330            Some(Autoscroll::fit()),
14331            cx,
14332        );
14333        self.clear_highlights::<Rename>(cx);
14334        self.show_local_selections = true;
14335
14336        if moving_cursor {
14337            let cursor_in_rename_editor = rename.editor.update(cx, |editor, cx| {
14338                editor.selections.newest::<usize>(cx).head()
14339            });
14340
14341            // Update the selection to match the position of the selection inside
14342            // the rename editor.
14343            let snapshot = self.buffer.read(cx).read(cx);
14344            let rename_range = rename.range.to_offset(&snapshot);
14345            let cursor_in_editor = snapshot
14346                .clip_offset(rename_range.start + cursor_in_rename_editor, Bias::Left)
14347                .min(rename_range.end);
14348            drop(snapshot);
14349
14350            self.change_selections(None, window, cx, |s| {
14351                s.select_ranges(vec![cursor_in_editor..cursor_in_editor])
14352            });
14353        } else {
14354            self.refresh_document_highlights(cx);
14355        }
14356
14357        Some(rename)
14358    }
14359
14360    pub fn pending_rename(&self) -> Option<&RenameState> {
14361        self.pending_rename.as_ref()
14362    }
14363
14364    fn format(
14365        &mut self,
14366        _: &Format,
14367        window: &mut Window,
14368        cx: &mut Context<Self>,
14369    ) -> Option<Task<Result<()>>> {
14370        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
14371
14372        let project = match &self.project {
14373            Some(project) => project.clone(),
14374            None => return None,
14375        };
14376
14377        Some(self.perform_format(
14378            project,
14379            FormatTrigger::Manual,
14380            FormatTarget::Buffers,
14381            window,
14382            cx,
14383        ))
14384    }
14385
14386    fn format_selections(
14387        &mut self,
14388        _: &FormatSelections,
14389        window: &mut Window,
14390        cx: &mut Context<Self>,
14391    ) -> Option<Task<Result<()>>> {
14392        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
14393
14394        let project = match &self.project {
14395            Some(project) => project.clone(),
14396            None => return None,
14397        };
14398
14399        let ranges = self
14400            .selections
14401            .all_adjusted(cx)
14402            .into_iter()
14403            .map(|selection| selection.range())
14404            .collect_vec();
14405
14406        Some(self.perform_format(
14407            project,
14408            FormatTrigger::Manual,
14409            FormatTarget::Ranges(ranges),
14410            window,
14411            cx,
14412        ))
14413    }
14414
14415    fn perform_format(
14416        &mut self,
14417        project: Entity<Project>,
14418        trigger: FormatTrigger,
14419        target: FormatTarget,
14420        window: &mut Window,
14421        cx: &mut Context<Self>,
14422    ) -> Task<Result<()>> {
14423        let buffer = self.buffer.clone();
14424        let (buffers, target) = match target {
14425            FormatTarget::Buffers => {
14426                let mut buffers = buffer.read(cx).all_buffers();
14427                if trigger == FormatTrigger::Save {
14428                    buffers.retain(|buffer| buffer.read(cx).is_dirty());
14429                }
14430                (buffers, LspFormatTarget::Buffers)
14431            }
14432            FormatTarget::Ranges(selection_ranges) => {
14433                let multi_buffer = buffer.read(cx);
14434                let snapshot = multi_buffer.read(cx);
14435                let mut buffers = HashSet::default();
14436                let mut buffer_id_to_ranges: BTreeMap<BufferId, Vec<Range<text::Anchor>>> =
14437                    BTreeMap::new();
14438                for selection_range in selection_ranges {
14439                    for (buffer, buffer_range, _) in
14440                        snapshot.range_to_buffer_ranges(selection_range)
14441                    {
14442                        let buffer_id = buffer.remote_id();
14443                        let start = buffer.anchor_before(buffer_range.start);
14444                        let end = buffer.anchor_after(buffer_range.end);
14445                        buffers.insert(multi_buffer.buffer(buffer_id).unwrap());
14446                        buffer_id_to_ranges
14447                            .entry(buffer_id)
14448                            .and_modify(|buffer_ranges| buffer_ranges.push(start..end))
14449                            .or_insert_with(|| vec![start..end]);
14450                    }
14451                }
14452                (buffers, LspFormatTarget::Ranges(buffer_id_to_ranges))
14453            }
14454        };
14455
14456        let transaction_id_prev = buffer.read_with(cx, |b, cx| b.last_transaction_id(cx));
14457        let selections_prev = transaction_id_prev
14458            .and_then(|transaction_id_prev| {
14459                // default to selections as they were after the last edit, if we have them,
14460                // instead of how they are now.
14461                // This will make it so that editing, moving somewhere else, formatting, then undoing the format
14462                // will take you back to where you made the last edit, instead of staying where you scrolled
14463                self.selection_history
14464                    .transaction(transaction_id_prev)
14465                    .map(|t| t.0.clone())
14466            })
14467            .unwrap_or_else(|| {
14468                log::info!("Failed to determine selections from before format. Falling back to selections when format was initiated");
14469                self.selections.disjoint_anchors()
14470            });
14471
14472        let mut timeout = cx.background_executor().timer(FORMAT_TIMEOUT).fuse();
14473        let format = project.update(cx, |project, cx| {
14474            project.format(buffers, target, true, trigger, cx)
14475        });
14476
14477        cx.spawn_in(window, async move |editor, cx| {
14478            let transaction = futures::select_biased! {
14479                transaction = format.log_err().fuse() => transaction,
14480                () = timeout => {
14481                    log::warn!("timed out waiting for formatting");
14482                    None
14483                }
14484            };
14485
14486            buffer
14487                .update(cx, |buffer, cx| {
14488                    if let Some(transaction) = transaction {
14489                        if !buffer.is_singleton() {
14490                            buffer.push_transaction(&transaction.0, cx);
14491                        }
14492                    }
14493                    cx.notify();
14494                })
14495                .ok();
14496
14497            if let Some(transaction_id_now) =
14498                buffer.read_with(cx, |b, cx| b.last_transaction_id(cx))?
14499            {
14500                let has_new_transaction = transaction_id_prev != Some(transaction_id_now);
14501                if has_new_transaction {
14502                    _ = editor.update(cx, |editor, _| {
14503                        editor
14504                            .selection_history
14505                            .insert_transaction(transaction_id_now, selections_prev);
14506                    });
14507                }
14508            }
14509
14510            Ok(())
14511        })
14512    }
14513
14514    fn organize_imports(
14515        &mut self,
14516        _: &OrganizeImports,
14517        window: &mut Window,
14518        cx: &mut Context<Self>,
14519    ) -> Option<Task<Result<()>>> {
14520        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
14521        let project = match &self.project {
14522            Some(project) => project.clone(),
14523            None => return None,
14524        };
14525        Some(self.perform_code_action_kind(
14526            project,
14527            CodeActionKind::SOURCE_ORGANIZE_IMPORTS,
14528            window,
14529            cx,
14530        ))
14531    }
14532
14533    fn perform_code_action_kind(
14534        &mut self,
14535        project: Entity<Project>,
14536        kind: CodeActionKind,
14537        window: &mut Window,
14538        cx: &mut Context<Self>,
14539    ) -> Task<Result<()>> {
14540        let buffer = self.buffer.clone();
14541        let buffers = buffer.read(cx).all_buffers();
14542        let mut timeout = cx.background_executor().timer(CODE_ACTION_TIMEOUT).fuse();
14543        let apply_action = project.update(cx, |project, cx| {
14544            project.apply_code_action_kind(buffers, kind, true, cx)
14545        });
14546        cx.spawn_in(window, async move |_, cx| {
14547            let transaction = futures::select_biased! {
14548                () = timeout => {
14549                    log::warn!("timed out waiting for executing code action");
14550                    None
14551                }
14552                transaction = apply_action.log_err().fuse() => transaction,
14553            };
14554            buffer
14555                .update(cx, |buffer, cx| {
14556                    // check if we need this
14557                    if let Some(transaction) = transaction {
14558                        if !buffer.is_singleton() {
14559                            buffer.push_transaction(&transaction.0, cx);
14560                        }
14561                    }
14562                    cx.notify();
14563                })
14564                .ok();
14565            Ok(())
14566        })
14567    }
14568
14569    fn restart_language_server(
14570        &mut self,
14571        _: &RestartLanguageServer,
14572        _: &mut Window,
14573        cx: &mut Context<Self>,
14574    ) {
14575        if let Some(project) = self.project.clone() {
14576            self.buffer.update(cx, |multi_buffer, cx| {
14577                project.update(cx, |project, cx| {
14578                    project.restart_language_servers_for_buffers(
14579                        multi_buffer.all_buffers().into_iter().collect(),
14580                        cx,
14581                    );
14582                });
14583            })
14584        }
14585    }
14586
14587    fn stop_language_server(
14588        &mut self,
14589        _: &StopLanguageServer,
14590        _: &mut Window,
14591        cx: &mut Context<Self>,
14592    ) {
14593        if let Some(project) = self.project.clone() {
14594            self.buffer.update(cx, |multi_buffer, cx| {
14595                project.update(cx, |project, cx| {
14596                    project.stop_language_servers_for_buffers(
14597                        multi_buffer.all_buffers().into_iter().collect(),
14598                        cx,
14599                    );
14600                    cx.emit(project::Event::RefreshInlayHints);
14601                });
14602            });
14603        }
14604    }
14605
14606    fn cancel_language_server_work(
14607        workspace: &mut Workspace,
14608        _: &actions::CancelLanguageServerWork,
14609        _: &mut Window,
14610        cx: &mut Context<Workspace>,
14611    ) {
14612        let project = workspace.project();
14613        let buffers = workspace
14614            .active_item(cx)
14615            .and_then(|item| item.act_as::<Editor>(cx))
14616            .map_or(HashSet::default(), |editor| {
14617                editor.read(cx).buffer.read(cx).all_buffers()
14618            });
14619        project.update(cx, |project, cx| {
14620            project.cancel_language_server_work_for_buffers(buffers, cx);
14621        });
14622    }
14623
14624    fn show_character_palette(
14625        &mut self,
14626        _: &ShowCharacterPalette,
14627        window: &mut Window,
14628        _: &mut Context<Self>,
14629    ) {
14630        window.show_character_palette();
14631    }
14632
14633    fn refresh_active_diagnostics(&mut self, cx: &mut Context<Editor>) {
14634        if let ActiveDiagnostic::Group(active_diagnostics) = &mut self.active_diagnostics {
14635            let buffer = self.buffer.read(cx).snapshot(cx);
14636            let primary_range_start = active_diagnostics.active_range.start.to_offset(&buffer);
14637            let primary_range_end = active_diagnostics.active_range.end.to_offset(&buffer);
14638            let is_valid = buffer
14639                .diagnostics_in_range::<usize>(primary_range_start..primary_range_end)
14640                .any(|entry| {
14641                    entry.diagnostic.is_primary
14642                        && !entry.range.is_empty()
14643                        && entry.range.start == primary_range_start
14644                        && entry.diagnostic.message == active_diagnostics.active_message
14645                });
14646
14647            if !is_valid {
14648                self.dismiss_diagnostics(cx);
14649            }
14650        }
14651    }
14652
14653    pub fn active_diagnostic_group(&self) -> Option<&ActiveDiagnosticGroup> {
14654        match &self.active_diagnostics {
14655            ActiveDiagnostic::Group(group) => Some(group),
14656            _ => None,
14657        }
14658    }
14659
14660    pub fn set_all_diagnostics_active(&mut self, cx: &mut Context<Self>) {
14661        self.dismiss_diagnostics(cx);
14662        self.active_diagnostics = ActiveDiagnostic::All;
14663    }
14664
14665    fn activate_diagnostics(
14666        &mut self,
14667        buffer_id: BufferId,
14668        diagnostic: DiagnosticEntry<usize>,
14669        window: &mut Window,
14670        cx: &mut Context<Self>,
14671    ) {
14672        if matches!(self.active_diagnostics, ActiveDiagnostic::All) {
14673            return;
14674        }
14675        self.dismiss_diagnostics(cx);
14676        let snapshot = self.snapshot(window, cx);
14677        let Some(diagnostic_renderer) = cx
14678            .try_global::<GlobalDiagnosticRenderer>()
14679            .map(|g| g.0.clone())
14680        else {
14681            return;
14682        };
14683        let buffer = self.buffer.read(cx).snapshot(cx);
14684
14685        let diagnostic_group = buffer
14686            .diagnostic_group(buffer_id, diagnostic.diagnostic.group_id)
14687            .collect::<Vec<_>>();
14688
14689        let blocks = diagnostic_renderer.render_group(
14690            diagnostic_group,
14691            buffer_id,
14692            snapshot,
14693            cx.weak_entity(),
14694            cx,
14695        );
14696
14697        let blocks = self.display_map.update(cx, |display_map, cx| {
14698            display_map.insert_blocks(blocks, cx).into_iter().collect()
14699        });
14700        self.active_diagnostics = ActiveDiagnostic::Group(ActiveDiagnosticGroup {
14701            active_range: buffer.anchor_before(diagnostic.range.start)
14702                ..buffer.anchor_after(diagnostic.range.end),
14703            active_message: diagnostic.diagnostic.message.clone(),
14704            group_id: diagnostic.diagnostic.group_id,
14705            blocks,
14706        });
14707        cx.notify();
14708    }
14709
14710    fn dismiss_diagnostics(&mut self, cx: &mut Context<Self>) {
14711        if matches!(self.active_diagnostics, ActiveDiagnostic::All) {
14712            return;
14713        };
14714
14715        let prev = mem::replace(&mut self.active_diagnostics, ActiveDiagnostic::None);
14716        if let ActiveDiagnostic::Group(group) = prev {
14717            self.display_map.update(cx, |display_map, cx| {
14718                display_map.remove_blocks(group.blocks, cx);
14719            });
14720            cx.notify();
14721        }
14722    }
14723
14724    /// Disable inline diagnostics rendering for this editor.
14725    pub fn disable_inline_diagnostics(&mut self) {
14726        self.inline_diagnostics_enabled = false;
14727        self.inline_diagnostics_update = Task::ready(());
14728        self.inline_diagnostics.clear();
14729    }
14730
14731    pub fn inline_diagnostics_enabled(&self) -> bool {
14732        self.inline_diagnostics_enabled
14733    }
14734
14735    pub fn show_inline_diagnostics(&self) -> bool {
14736        self.show_inline_diagnostics
14737    }
14738
14739    pub fn toggle_inline_diagnostics(
14740        &mut self,
14741        _: &ToggleInlineDiagnostics,
14742        window: &mut Window,
14743        cx: &mut Context<Editor>,
14744    ) {
14745        self.show_inline_diagnostics = !self.show_inline_diagnostics;
14746        self.refresh_inline_diagnostics(false, window, cx);
14747    }
14748
14749    fn refresh_inline_diagnostics(
14750        &mut self,
14751        debounce: bool,
14752        window: &mut Window,
14753        cx: &mut Context<Self>,
14754    ) {
14755        if !self.inline_diagnostics_enabled || !self.show_inline_diagnostics {
14756            self.inline_diagnostics_update = Task::ready(());
14757            self.inline_diagnostics.clear();
14758            return;
14759        }
14760
14761        let debounce_ms = ProjectSettings::get_global(cx)
14762            .diagnostics
14763            .inline
14764            .update_debounce_ms;
14765        let debounce = if debounce && debounce_ms > 0 {
14766            Some(Duration::from_millis(debounce_ms))
14767        } else {
14768            None
14769        };
14770        self.inline_diagnostics_update = cx.spawn_in(window, async move |editor, cx| {
14771            let editor = editor.upgrade().unwrap();
14772
14773            if let Some(debounce) = debounce {
14774                cx.background_executor().timer(debounce).await;
14775            }
14776            let Some(snapshot) = editor
14777                .update(cx, |editor, cx| editor.buffer().read(cx).snapshot(cx))
14778                .ok()
14779            else {
14780                return;
14781            };
14782
14783            let new_inline_diagnostics = cx
14784                .background_spawn(async move {
14785                    let mut inline_diagnostics = Vec::<(Anchor, InlineDiagnostic)>::new();
14786                    for diagnostic_entry in snapshot.diagnostics_in_range(0..snapshot.len()) {
14787                        let message = diagnostic_entry
14788                            .diagnostic
14789                            .message
14790                            .split_once('\n')
14791                            .map(|(line, _)| line)
14792                            .map(SharedString::new)
14793                            .unwrap_or_else(|| {
14794                                SharedString::from(diagnostic_entry.diagnostic.message)
14795                            });
14796                        let start_anchor = snapshot.anchor_before(diagnostic_entry.range.start);
14797                        let (Ok(i) | Err(i)) = inline_diagnostics
14798                            .binary_search_by(|(probe, _)| probe.cmp(&start_anchor, &snapshot));
14799                        inline_diagnostics.insert(
14800                            i,
14801                            (
14802                                start_anchor,
14803                                InlineDiagnostic {
14804                                    message,
14805                                    group_id: diagnostic_entry.diagnostic.group_id,
14806                                    start: diagnostic_entry.range.start.to_point(&snapshot),
14807                                    is_primary: diagnostic_entry.diagnostic.is_primary,
14808                                    severity: diagnostic_entry.diagnostic.severity,
14809                                },
14810                            ),
14811                        );
14812                    }
14813                    inline_diagnostics
14814                })
14815                .await;
14816
14817            editor
14818                .update(cx, |editor, cx| {
14819                    editor.inline_diagnostics = new_inline_diagnostics;
14820                    cx.notify();
14821                })
14822                .ok();
14823        });
14824    }
14825
14826    pub fn set_selections_from_remote(
14827        &mut self,
14828        selections: Vec<Selection<Anchor>>,
14829        pending_selection: Option<Selection<Anchor>>,
14830        window: &mut Window,
14831        cx: &mut Context<Self>,
14832    ) {
14833        let old_cursor_position = self.selections.newest_anchor().head();
14834        self.selections.change_with(cx, |s| {
14835            s.select_anchors(selections);
14836            if let Some(pending_selection) = pending_selection {
14837                s.set_pending(pending_selection, SelectMode::Character);
14838            } else {
14839                s.clear_pending();
14840            }
14841        });
14842        self.selections_did_change(false, &old_cursor_position, true, window, cx);
14843    }
14844
14845    fn push_to_selection_history(&mut self) {
14846        self.selection_history.push(SelectionHistoryEntry {
14847            selections: self.selections.disjoint_anchors(),
14848            select_next_state: self.select_next_state.clone(),
14849            select_prev_state: self.select_prev_state.clone(),
14850            add_selections_state: self.add_selections_state.clone(),
14851        });
14852    }
14853
14854    pub fn transact(
14855        &mut self,
14856        window: &mut Window,
14857        cx: &mut Context<Self>,
14858        update: impl FnOnce(&mut Self, &mut Window, &mut Context<Self>),
14859    ) -> Option<TransactionId> {
14860        self.start_transaction_at(Instant::now(), window, cx);
14861        update(self, window, cx);
14862        self.end_transaction_at(Instant::now(), cx)
14863    }
14864
14865    pub fn start_transaction_at(
14866        &mut self,
14867        now: Instant,
14868        window: &mut Window,
14869        cx: &mut Context<Self>,
14870    ) {
14871        self.end_selection(window, cx);
14872        if let Some(tx_id) = self
14873            .buffer
14874            .update(cx, |buffer, cx| buffer.start_transaction_at(now, cx))
14875        {
14876            self.selection_history
14877                .insert_transaction(tx_id, self.selections.disjoint_anchors());
14878            cx.emit(EditorEvent::TransactionBegun {
14879                transaction_id: tx_id,
14880            })
14881        }
14882    }
14883
14884    pub fn end_transaction_at(
14885        &mut self,
14886        now: Instant,
14887        cx: &mut Context<Self>,
14888    ) -> Option<TransactionId> {
14889        if let Some(transaction_id) = self
14890            .buffer
14891            .update(cx, |buffer, cx| buffer.end_transaction_at(now, cx))
14892        {
14893            if let Some((_, end_selections)) =
14894                self.selection_history.transaction_mut(transaction_id)
14895            {
14896                *end_selections = Some(self.selections.disjoint_anchors());
14897            } else {
14898                log::error!("unexpectedly ended a transaction that wasn't started by this editor");
14899            }
14900
14901            cx.emit(EditorEvent::Edited { transaction_id });
14902            Some(transaction_id)
14903        } else {
14904            None
14905        }
14906    }
14907
14908    pub fn set_mark(&mut self, _: &actions::SetMark, window: &mut Window, cx: &mut Context<Self>) {
14909        if self.selection_mark_mode {
14910            self.change_selections(None, window, cx, |s| {
14911                s.move_with(|_, sel| {
14912                    sel.collapse_to(sel.head(), SelectionGoal::None);
14913                });
14914            })
14915        }
14916        self.selection_mark_mode = true;
14917        cx.notify();
14918    }
14919
14920    pub fn swap_selection_ends(
14921        &mut self,
14922        _: &actions::SwapSelectionEnds,
14923        window: &mut Window,
14924        cx: &mut Context<Self>,
14925    ) {
14926        self.change_selections(None, window, cx, |s| {
14927            s.move_with(|_, sel| {
14928                if sel.start != sel.end {
14929                    sel.reversed = !sel.reversed
14930                }
14931            });
14932        });
14933        self.request_autoscroll(Autoscroll::newest(), cx);
14934        cx.notify();
14935    }
14936
14937    pub fn toggle_fold(
14938        &mut self,
14939        _: &actions::ToggleFold,
14940        window: &mut Window,
14941        cx: &mut Context<Self>,
14942    ) {
14943        if self.is_singleton(cx) {
14944            let selection = self.selections.newest::<Point>(cx);
14945
14946            let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
14947            let range = if selection.is_empty() {
14948                let point = selection.head().to_display_point(&display_map);
14949                let start = DisplayPoint::new(point.row(), 0).to_point(&display_map);
14950                let end = DisplayPoint::new(point.row(), display_map.line_len(point.row()))
14951                    .to_point(&display_map);
14952                start..end
14953            } else {
14954                selection.range()
14955            };
14956            if display_map.folds_in_range(range).next().is_some() {
14957                self.unfold_lines(&Default::default(), window, cx)
14958            } else {
14959                self.fold(&Default::default(), window, cx)
14960            }
14961        } else {
14962            let multi_buffer_snapshot = self.buffer.read(cx).snapshot(cx);
14963            let buffer_ids: HashSet<_> = self
14964                .selections
14965                .disjoint_anchor_ranges()
14966                .flat_map(|range| multi_buffer_snapshot.buffer_ids_for_range(range))
14967                .collect();
14968
14969            let should_unfold = buffer_ids
14970                .iter()
14971                .any(|buffer_id| self.is_buffer_folded(*buffer_id, cx));
14972
14973            for buffer_id in buffer_ids {
14974                if should_unfold {
14975                    self.unfold_buffer(buffer_id, cx);
14976                } else {
14977                    self.fold_buffer(buffer_id, cx);
14978                }
14979            }
14980        }
14981    }
14982
14983    pub fn toggle_fold_recursive(
14984        &mut self,
14985        _: &actions::ToggleFoldRecursive,
14986        window: &mut Window,
14987        cx: &mut Context<Self>,
14988    ) {
14989        let selection = self.selections.newest::<Point>(cx);
14990
14991        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
14992        let range = if selection.is_empty() {
14993            let point = selection.head().to_display_point(&display_map);
14994            let start = DisplayPoint::new(point.row(), 0).to_point(&display_map);
14995            let end = DisplayPoint::new(point.row(), display_map.line_len(point.row()))
14996                .to_point(&display_map);
14997            start..end
14998        } else {
14999            selection.range()
15000        };
15001        if display_map.folds_in_range(range).next().is_some() {
15002            self.unfold_recursive(&Default::default(), window, cx)
15003        } else {
15004            self.fold_recursive(&Default::default(), window, cx)
15005        }
15006    }
15007
15008    pub fn fold(&mut self, _: &actions::Fold, window: &mut Window, cx: &mut Context<Self>) {
15009        if self.is_singleton(cx) {
15010            let mut to_fold = Vec::new();
15011            let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
15012            let selections = self.selections.all_adjusted(cx);
15013
15014            for selection in selections {
15015                let range = selection.range().sorted();
15016                let buffer_start_row = range.start.row;
15017
15018                if range.start.row != range.end.row {
15019                    let mut found = false;
15020                    let mut row = range.start.row;
15021                    while row <= range.end.row {
15022                        if let Some(crease) = display_map.crease_for_buffer_row(MultiBufferRow(row))
15023                        {
15024                            found = true;
15025                            row = crease.range().end.row + 1;
15026                            to_fold.push(crease);
15027                        } else {
15028                            row += 1
15029                        }
15030                    }
15031                    if found {
15032                        continue;
15033                    }
15034                }
15035
15036                for row in (0..=range.start.row).rev() {
15037                    if let Some(crease) = display_map.crease_for_buffer_row(MultiBufferRow(row)) {
15038                        if crease.range().end.row >= buffer_start_row {
15039                            to_fold.push(crease);
15040                            if row <= range.start.row {
15041                                break;
15042                            }
15043                        }
15044                    }
15045                }
15046            }
15047
15048            self.fold_creases(to_fold, true, window, cx);
15049        } else {
15050            let multi_buffer_snapshot = self.buffer.read(cx).snapshot(cx);
15051            let buffer_ids = self
15052                .selections
15053                .disjoint_anchor_ranges()
15054                .flat_map(|range| multi_buffer_snapshot.buffer_ids_for_range(range))
15055                .collect::<HashSet<_>>();
15056            for buffer_id in buffer_ids {
15057                self.fold_buffer(buffer_id, cx);
15058            }
15059        }
15060    }
15061
15062    fn fold_at_level(
15063        &mut self,
15064        fold_at: &FoldAtLevel,
15065        window: &mut Window,
15066        cx: &mut Context<Self>,
15067    ) {
15068        if !self.buffer.read(cx).is_singleton() {
15069            return;
15070        }
15071
15072        let fold_at_level = fold_at.0;
15073        let snapshot = self.buffer.read(cx).snapshot(cx);
15074        let mut to_fold = Vec::new();
15075        let mut stack = vec![(0, snapshot.max_row().0, 1)];
15076
15077        while let Some((mut start_row, end_row, current_level)) = stack.pop() {
15078            while start_row < end_row {
15079                match self
15080                    .snapshot(window, cx)
15081                    .crease_for_buffer_row(MultiBufferRow(start_row))
15082                {
15083                    Some(crease) => {
15084                        let nested_start_row = crease.range().start.row + 1;
15085                        let nested_end_row = crease.range().end.row;
15086
15087                        if current_level < fold_at_level {
15088                            stack.push((nested_start_row, nested_end_row, current_level + 1));
15089                        } else if current_level == fold_at_level {
15090                            to_fold.push(crease);
15091                        }
15092
15093                        start_row = nested_end_row + 1;
15094                    }
15095                    None => start_row += 1,
15096                }
15097            }
15098        }
15099
15100        self.fold_creases(to_fold, true, window, cx);
15101    }
15102
15103    pub fn fold_all(&mut self, _: &actions::FoldAll, window: &mut Window, cx: &mut Context<Self>) {
15104        if self.buffer.read(cx).is_singleton() {
15105            let mut fold_ranges = Vec::new();
15106            let snapshot = self.buffer.read(cx).snapshot(cx);
15107
15108            for row in 0..snapshot.max_row().0 {
15109                if let Some(foldable_range) = self
15110                    .snapshot(window, cx)
15111                    .crease_for_buffer_row(MultiBufferRow(row))
15112                {
15113                    fold_ranges.push(foldable_range);
15114                }
15115            }
15116
15117            self.fold_creases(fold_ranges, true, window, cx);
15118        } else {
15119            self.toggle_fold_multiple_buffers = cx.spawn_in(window, async move |editor, cx| {
15120                editor
15121                    .update_in(cx, |editor, _, cx| {
15122                        for buffer_id in editor.buffer.read(cx).excerpt_buffer_ids() {
15123                            editor.fold_buffer(buffer_id, cx);
15124                        }
15125                    })
15126                    .ok();
15127            });
15128        }
15129    }
15130
15131    pub fn fold_function_bodies(
15132        &mut self,
15133        _: &actions::FoldFunctionBodies,
15134        window: &mut Window,
15135        cx: &mut Context<Self>,
15136    ) {
15137        let snapshot = self.buffer.read(cx).snapshot(cx);
15138
15139        let ranges = snapshot
15140            .text_object_ranges(0..snapshot.len(), TreeSitterOptions::default())
15141            .filter_map(|(range, obj)| (obj == TextObject::InsideFunction).then_some(range))
15142            .collect::<Vec<_>>();
15143
15144        let creases = ranges
15145            .into_iter()
15146            .map(|range| Crease::simple(range, self.display_map.read(cx).fold_placeholder.clone()))
15147            .collect();
15148
15149        self.fold_creases(creases, true, window, cx);
15150    }
15151
15152    pub fn fold_recursive(
15153        &mut self,
15154        _: &actions::FoldRecursive,
15155        window: &mut Window,
15156        cx: &mut Context<Self>,
15157    ) {
15158        let mut to_fold = Vec::new();
15159        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
15160        let selections = self.selections.all_adjusted(cx);
15161
15162        for selection in selections {
15163            let range = selection.range().sorted();
15164            let buffer_start_row = range.start.row;
15165
15166            if range.start.row != range.end.row {
15167                let mut found = false;
15168                for row in range.start.row..=range.end.row {
15169                    if let Some(crease) = display_map.crease_for_buffer_row(MultiBufferRow(row)) {
15170                        found = true;
15171                        to_fold.push(crease);
15172                    }
15173                }
15174                if found {
15175                    continue;
15176                }
15177            }
15178
15179            for row in (0..=range.start.row).rev() {
15180                if let Some(crease) = display_map.crease_for_buffer_row(MultiBufferRow(row)) {
15181                    if crease.range().end.row >= buffer_start_row {
15182                        to_fold.push(crease);
15183                    } else {
15184                        break;
15185                    }
15186                }
15187            }
15188        }
15189
15190        self.fold_creases(to_fold, true, window, cx);
15191    }
15192
15193    pub fn fold_at(
15194        &mut self,
15195        buffer_row: MultiBufferRow,
15196        window: &mut Window,
15197        cx: &mut Context<Self>,
15198    ) {
15199        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
15200
15201        if let Some(crease) = display_map.crease_for_buffer_row(buffer_row) {
15202            let autoscroll = self
15203                .selections
15204                .all::<Point>(cx)
15205                .iter()
15206                .any(|selection| crease.range().overlaps(&selection.range()));
15207
15208            self.fold_creases(vec![crease], autoscroll, window, cx);
15209        }
15210    }
15211
15212    pub fn unfold_lines(&mut self, _: &UnfoldLines, _window: &mut Window, cx: &mut Context<Self>) {
15213        if self.is_singleton(cx) {
15214            let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
15215            let buffer = &display_map.buffer_snapshot;
15216            let selections = self.selections.all::<Point>(cx);
15217            let ranges = selections
15218                .iter()
15219                .map(|s| {
15220                    let range = s.display_range(&display_map).sorted();
15221                    let mut start = range.start.to_point(&display_map);
15222                    let mut end = range.end.to_point(&display_map);
15223                    start.column = 0;
15224                    end.column = buffer.line_len(MultiBufferRow(end.row));
15225                    start..end
15226                })
15227                .collect::<Vec<_>>();
15228
15229            self.unfold_ranges(&ranges, true, true, cx);
15230        } else {
15231            let multi_buffer_snapshot = self.buffer.read(cx).snapshot(cx);
15232            let buffer_ids = self
15233                .selections
15234                .disjoint_anchor_ranges()
15235                .flat_map(|range| multi_buffer_snapshot.buffer_ids_for_range(range))
15236                .collect::<HashSet<_>>();
15237            for buffer_id in buffer_ids {
15238                self.unfold_buffer(buffer_id, cx);
15239            }
15240        }
15241    }
15242
15243    pub fn unfold_recursive(
15244        &mut self,
15245        _: &UnfoldRecursive,
15246        _window: &mut Window,
15247        cx: &mut Context<Self>,
15248    ) {
15249        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
15250        let selections = self.selections.all::<Point>(cx);
15251        let ranges = selections
15252            .iter()
15253            .map(|s| {
15254                let mut range = s.display_range(&display_map).sorted();
15255                *range.start.column_mut() = 0;
15256                *range.end.column_mut() = display_map.line_len(range.end.row());
15257                let start = range.start.to_point(&display_map);
15258                let end = range.end.to_point(&display_map);
15259                start..end
15260            })
15261            .collect::<Vec<_>>();
15262
15263        self.unfold_ranges(&ranges, true, true, cx);
15264    }
15265
15266    pub fn unfold_at(
15267        &mut self,
15268        buffer_row: MultiBufferRow,
15269        _window: &mut Window,
15270        cx: &mut Context<Self>,
15271    ) {
15272        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
15273
15274        let intersection_range = Point::new(buffer_row.0, 0)
15275            ..Point::new(
15276                buffer_row.0,
15277                display_map.buffer_snapshot.line_len(buffer_row),
15278            );
15279
15280        let autoscroll = self
15281            .selections
15282            .all::<Point>(cx)
15283            .iter()
15284            .any(|selection| RangeExt::overlaps(&selection.range(), &intersection_range));
15285
15286        self.unfold_ranges(&[intersection_range], true, autoscroll, cx);
15287    }
15288
15289    pub fn unfold_all(
15290        &mut self,
15291        _: &actions::UnfoldAll,
15292        _window: &mut Window,
15293        cx: &mut Context<Self>,
15294    ) {
15295        if self.buffer.read(cx).is_singleton() {
15296            let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
15297            self.unfold_ranges(&[0..display_map.buffer_snapshot.len()], true, true, cx);
15298        } else {
15299            self.toggle_fold_multiple_buffers = cx.spawn(async move |editor, cx| {
15300                editor
15301                    .update(cx, |editor, cx| {
15302                        for buffer_id in editor.buffer.read(cx).excerpt_buffer_ids() {
15303                            editor.unfold_buffer(buffer_id, cx);
15304                        }
15305                    })
15306                    .ok();
15307            });
15308        }
15309    }
15310
15311    pub fn fold_selected_ranges(
15312        &mut self,
15313        _: &FoldSelectedRanges,
15314        window: &mut Window,
15315        cx: &mut Context<Self>,
15316    ) {
15317        let selections = self.selections.all_adjusted(cx);
15318        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
15319        let ranges = selections
15320            .into_iter()
15321            .map(|s| Crease::simple(s.range(), display_map.fold_placeholder.clone()))
15322            .collect::<Vec<_>>();
15323        self.fold_creases(ranges, true, window, cx);
15324    }
15325
15326    pub fn fold_ranges<T: ToOffset + Clone>(
15327        &mut self,
15328        ranges: Vec<Range<T>>,
15329        auto_scroll: bool,
15330        window: &mut Window,
15331        cx: &mut Context<Self>,
15332    ) {
15333        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
15334        let ranges = ranges
15335            .into_iter()
15336            .map(|r| Crease::simple(r, display_map.fold_placeholder.clone()))
15337            .collect::<Vec<_>>();
15338        self.fold_creases(ranges, auto_scroll, window, cx);
15339    }
15340
15341    pub fn fold_creases<T: ToOffset + Clone>(
15342        &mut self,
15343        creases: Vec<Crease<T>>,
15344        auto_scroll: bool,
15345        _window: &mut Window,
15346        cx: &mut Context<Self>,
15347    ) {
15348        if creases.is_empty() {
15349            return;
15350        }
15351
15352        let mut buffers_affected = HashSet::default();
15353        let multi_buffer = self.buffer().read(cx);
15354        for crease in &creases {
15355            if let Some((_, buffer, _)) =
15356                multi_buffer.excerpt_containing(crease.range().start.clone(), cx)
15357            {
15358                buffers_affected.insert(buffer.read(cx).remote_id());
15359            };
15360        }
15361
15362        self.display_map.update(cx, |map, cx| map.fold(creases, cx));
15363
15364        if auto_scroll {
15365            self.request_autoscroll(Autoscroll::fit(), cx);
15366        }
15367
15368        cx.notify();
15369
15370        self.scrollbar_marker_state.dirty = true;
15371        self.folds_did_change(cx);
15372    }
15373
15374    /// Removes any folds whose ranges intersect any of the given ranges.
15375    pub fn unfold_ranges<T: ToOffset + Clone>(
15376        &mut self,
15377        ranges: &[Range<T>],
15378        inclusive: bool,
15379        auto_scroll: bool,
15380        cx: &mut Context<Self>,
15381    ) {
15382        self.remove_folds_with(ranges, auto_scroll, cx, |map, cx| {
15383            map.unfold_intersecting(ranges.iter().cloned(), inclusive, cx)
15384        });
15385        self.folds_did_change(cx);
15386    }
15387
15388    pub fn fold_buffer(&mut self, buffer_id: BufferId, cx: &mut Context<Self>) {
15389        if self.buffer().read(cx).is_singleton() || self.is_buffer_folded(buffer_id, cx) {
15390            return;
15391        }
15392        let folded_excerpts = self.buffer().read(cx).excerpts_for_buffer(buffer_id, cx);
15393        self.display_map.update(cx, |display_map, cx| {
15394            display_map.fold_buffers([buffer_id], cx)
15395        });
15396        cx.emit(EditorEvent::BufferFoldToggled {
15397            ids: folded_excerpts.iter().map(|&(id, _)| id).collect(),
15398            folded: true,
15399        });
15400        cx.notify();
15401    }
15402
15403    pub fn unfold_buffer(&mut self, buffer_id: BufferId, cx: &mut Context<Self>) {
15404        if self.buffer().read(cx).is_singleton() || !self.is_buffer_folded(buffer_id, cx) {
15405            return;
15406        }
15407        let unfolded_excerpts = self.buffer().read(cx).excerpts_for_buffer(buffer_id, cx);
15408        self.display_map.update(cx, |display_map, cx| {
15409            display_map.unfold_buffers([buffer_id], cx);
15410        });
15411        cx.emit(EditorEvent::BufferFoldToggled {
15412            ids: unfolded_excerpts.iter().map(|&(id, _)| id).collect(),
15413            folded: false,
15414        });
15415        cx.notify();
15416    }
15417
15418    pub fn is_buffer_folded(&self, buffer: BufferId, cx: &App) -> bool {
15419        self.display_map.read(cx).is_buffer_folded(buffer)
15420    }
15421
15422    pub fn folded_buffers<'a>(&self, cx: &'a App) -> &'a HashSet<BufferId> {
15423        self.display_map.read(cx).folded_buffers()
15424    }
15425
15426    pub fn disable_header_for_buffer(&mut self, buffer_id: BufferId, cx: &mut Context<Self>) {
15427        self.display_map.update(cx, |display_map, cx| {
15428            display_map.disable_header_for_buffer(buffer_id, cx);
15429        });
15430        cx.notify();
15431    }
15432
15433    /// Removes any folds with the given ranges.
15434    pub fn remove_folds_with_type<T: ToOffset + Clone>(
15435        &mut self,
15436        ranges: &[Range<T>],
15437        type_id: TypeId,
15438        auto_scroll: bool,
15439        cx: &mut Context<Self>,
15440    ) {
15441        self.remove_folds_with(ranges, auto_scroll, cx, |map, cx| {
15442            map.remove_folds_with_type(ranges.iter().cloned(), type_id, cx)
15443        });
15444        self.folds_did_change(cx);
15445    }
15446
15447    fn remove_folds_with<T: ToOffset + Clone>(
15448        &mut self,
15449        ranges: &[Range<T>],
15450        auto_scroll: bool,
15451        cx: &mut Context<Self>,
15452        update: impl FnOnce(&mut DisplayMap, &mut Context<DisplayMap>),
15453    ) {
15454        if ranges.is_empty() {
15455            return;
15456        }
15457
15458        let mut buffers_affected = HashSet::default();
15459        let multi_buffer = self.buffer().read(cx);
15460        for range in ranges {
15461            if let Some((_, buffer, _)) = multi_buffer.excerpt_containing(range.start.clone(), cx) {
15462                buffers_affected.insert(buffer.read(cx).remote_id());
15463            };
15464        }
15465
15466        self.display_map.update(cx, update);
15467
15468        if auto_scroll {
15469            self.request_autoscroll(Autoscroll::fit(), cx);
15470        }
15471
15472        cx.notify();
15473        self.scrollbar_marker_state.dirty = true;
15474        self.active_indent_guides_state.dirty = true;
15475    }
15476
15477    pub fn update_fold_widths(
15478        &mut self,
15479        widths: impl IntoIterator<Item = (FoldId, Pixels)>,
15480        cx: &mut Context<Self>,
15481    ) -> bool {
15482        self.display_map
15483            .update(cx, |map, cx| map.update_fold_widths(widths, cx))
15484    }
15485
15486    pub fn default_fold_placeholder(&self, cx: &App) -> FoldPlaceholder {
15487        self.display_map.read(cx).fold_placeholder.clone()
15488    }
15489
15490    pub fn set_expand_all_diff_hunks(&mut self, cx: &mut App) {
15491        self.buffer.update(cx, |buffer, cx| {
15492            buffer.set_all_diff_hunks_expanded(cx);
15493        });
15494    }
15495
15496    pub fn expand_all_diff_hunks(
15497        &mut self,
15498        _: &ExpandAllDiffHunks,
15499        _window: &mut Window,
15500        cx: &mut Context<Self>,
15501    ) {
15502        self.buffer.update(cx, |buffer, cx| {
15503            buffer.expand_diff_hunks(vec![Anchor::min()..Anchor::max()], cx)
15504        });
15505    }
15506
15507    pub fn toggle_selected_diff_hunks(
15508        &mut self,
15509        _: &ToggleSelectedDiffHunks,
15510        _window: &mut Window,
15511        cx: &mut Context<Self>,
15512    ) {
15513        let ranges: Vec<_> = self.selections.disjoint.iter().map(|s| s.range()).collect();
15514        self.toggle_diff_hunks_in_ranges(ranges, cx);
15515    }
15516
15517    pub fn diff_hunks_in_ranges<'a>(
15518        &'a self,
15519        ranges: &'a [Range<Anchor>],
15520        buffer: &'a MultiBufferSnapshot,
15521    ) -> impl 'a + Iterator<Item = MultiBufferDiffHunk> {
15522        ranges.iter().flat_map(move |range| {
15523            let end_excerpt_id = range.end.excerpt_id;
15524            let range = range.to_point(buffer);
15525            let mut peek_end = range.end;
15526            if range.end.row < buffer.max_row().0 {
15527                peek_end = Point::new(range.end.row + 1, 0);
15528            }
15529            buffer
15530                .diff_hunks_in_range(range.start..peek_end)
15531                .filter(move |hunk| hunk.excerpt_id.cmp(&end_excerpt_id, buffer).is_le())
15532        })
15533    }
15534
15535    pub fn has_stageable_diff_hunks_in_ranges(
15536        &self,
15537        ranges: &[Range<Anchor>],
15538        snapshot: &MultiBufferSnapshot,
15539    ) -> bool {
15540        let mut hunks = self.diff_hunks_in_ranges(ranges, &snapshot);
15541        hunks.any(|hunk| hunk.status().has_secondary_hunk())
15542    }
15543
15544    pub fn toggle_staged_selected_diff_hunks(
15545        &mut self,
15546        _: &::git::ToggleStaged,
15547        _: &mut Window,
15548        cx: &mut Context<Self>,
15549    ) {
15550        let snapshot = self.buffer.read(cx).snapshot(cx);
15551        let ranges: Vec<_> = self.selections.disjoint.iter().map(|s| s.range()).collect();
15552        let stage = self.has_stageable_diff_hunks_in_ranges(&ranges, &snapshot);
15553        self.stage_or_unstage_diff_hunks(stage, ranges, cx);
15554    }
15555
15556    pub fn set_render_diff_hunk_controls(
15557        &mut self,
15558        render_diff_hunk_controls: RenderDiffHunkControlsFn,
15559        cx: &mut Context<Self>,
15560    ) {
15561        self.render_diff_hunk_controls = render_diff_hunk_controls;
15562        cx.notify();
15563    }
15564
15565    pub fn stage_and_next(
15566        &mut self,
15567        _: &::git::StageAndNext,
15568        window: &mut Window,
15569        cx: &mut Context<Self>,
15570    ) {
15571        self.do_stage_or_unstage_and_next(true, window, cx);
15572    }
15573
15574    pub fn unstage_and_next(
15575        &mut self,
15576        _: &::git::UnstageAndNext,
15577        window: &mut Window,
15578        cx: &mut Context<Self>,
15579    ) {
15580        self.do_stage_or_unstage_and_next(false, window, cx);
15581    }
15582
15583    pub fn stage_or_unstage_diff_hunks(
15584        &mut self,
15585        stage: bool,
15586        ranges: Vec<Range<Anchor>>,
15587        cx: &mut Context<Self>,
15588    ) {
15589        let task = self.save_buffers_for_ranges_if_needed(&ranges, cx);
15590        cx.spawn(async move |this, cx| {
15591            task.await?;
15592            this.update(cx, |this, cx| {
15593                let snapshot = this.buffer.read(cx).snapshot(cx);
15594                let chunk_by = this
15595                    .diff_hunks_in_ranges(&ranges, &snapshot)
15596                    .chunk_by(|hunk| hunk.buffer_id);
15597                for (buffer_id, hunks) in &chunk_by {
15598                    this.do_stage_or_unstage(stage, buffer_id, hunks, cx);
15599                }
15600            })
15601        })
15602        .detach_and_log_err(cx);
15603    }
15604
15605    fn save_buffers_for_ranges_if_needed(
15606        &mut self,
15607        ranges: &[Range<Anchor>],
15608        cx: &mut Context<Editor>,
15609    ) -> Task<Result<()>> {
15610        let multibuffer = self.buffer.read(cx);
15611        let snapshot = multibuffer.read(cx);
15612        let buffer_ids: HashSet<_> = ranges
15613            .iter()
15614            .flat_map(|range| snapshot.buffer_ids_for_range(range.clone()))
15615            .collect();
15616        drop(snapshot);
15617
15618        let mut buffers = HashSet::default();
15619        for buffer_id in buffer_ids {
15620            if let Some(buffer_entity) = multibuffer.buffer(buffer_id) {
15621                let buffer = buffer_entity.read(cx);
15622                if buffer.file().is_some_and(|file| file.disk_state().exists()) && buffer.is_dirty()
15623                {
15624                    buffers.insert(buffer_entity);
15625                }
15626            }
15627        }
15628
15629        if let Some(project) = &self.project {
15630            project.update(cx, |project, cx| project.save_buffers(buffers, cx))
15631        } else {
15632            Task::ready(Ok(()))
15633        }
15634    }
15635
15636    fn do_stage_or_unstage_and_next(
15637        &mut self,
15638        stage: bool,
15639        window: &mut Window,
15640        cx: &mut Context<Self>,
15641    ) {
15642        let ranges = self.selections.disjoint_anchor_ranges().collect::<Vec<_>>();
15643
15644        if ranges.iter().any(|range| range.start != range.end) {
15645            self.stage_or_unstage_diff_hunks(stage, ranges, cx);
15646            return;
15647        }
15648
15649        self.stage_or_unstage_diff_hunks(stage, ranges, cx);
15650        let snapshot = self.snapshot(window, cx);
15651        let position = self.selections.newest::<Point>(cx).head();
15652        let mut row = snapshot
15653            .buffer_snapshot
15654            .diff_hunks_in_range(position..snapshot.buffer_snapshot.max_point())
15655            .find(|hunk| hunk.row_range.start.0 > position.row)
15656            .map(|hunk| hunk.row_range.start);
15657
15658        let all_diff_hunks_expanded = self.buffer().read(cx).all_diff_hunks_expanded();
15659        // Outside of the project diff editor, wrap around to the beginning.
15660        if !all_diff_hunks_expanded {
15661            row = row.or_else(|| {
15662                snapshot
15663                    .buffer_snapshot
15664                    .diff_hunks_in_range(Point::zero()..position)
15665                    .find(|hunk| hunk.row_range.end.0 < position.row)
15666                    .map(|hunk| hunk.row_range.start)
15667            });
15668        }
15669
15670        if let Some(row) = row {
15671            let destination = Point::new(row.0, 0);
15672            let autoscroll = Autoscroll::center();
15673
15674            self.unfold_ranges(&[destination..destination], false, false, cx);
15675            self.change_selections(Some(autoscroll), window, cx, |s| {
15676                s.select_ranges([destination..destination]);
15677            });
15678        }
15679    }
15680
15681    fn do_stage_or_unstage(
15682        &self,
15683        stage: bool,
15684        buffer_id: BufferId,
15685        hunks: impl Iterator<Item = MultiBufferDiffHunk>,
15686        cx: &mut App,
15687    ) -> Option<()> {
15688        let project = self.project.as_ref()?;
15689        let buffer = project.read(cx).buffer_for_id(buffer_id, cx)?;
15690        let diff = self.buffer.read(cx).diff_for(buffer_id)?;
15691        let buffer_snapshot = buffer.read(cx).snapshot();
15692        let file_exists = buffer_snapshot
15693            .file()
15694            .is_some_and(|file| file.disk_state().exists());
15695        diff.update(cx, |diff, cx| {
15696            diff.stage_or_unstage_hunks(
15697                stage,
15698                &hunks
15699                    .map(|hunk| buffer_diff::DiffHunk {
15700                        buffer_range: hunk.buffer_range,
15701                        diff_base_byte_range: hunk.diff_base_byte_range,
15702                        secondary_status: hunk.secondary_status,
15703                        range: Point::zero()..Point::zero(), // unused
15704                    })
15705                    .collect::<Vec<_>>(),
15706                &buffer_snapshot,
15707                file_exists,
15708                cx,
15709            )
15710        });
15711        None
15712    }
15713
15714    pub fn expand_selected_diff_hunks(&mut self, cx: &mut Context<Self>) {
15715        let ranges: Vec<_> = self.selections.disjoint.iter().map(|s| s.range()).collect();
15716        self.buffer
15717            .update(cx, |buffer, cx| buffer.expand_diff_hunks(ranges, cx))
15718    }
15719
15720    pub fn clear_expanded_diff_hunks(&mut self, cx: &mut Context<Self>) -> bool {
15721        self.buffer.update(cx, |buffer, cx| {
15722            let ranges = vec![Anchor::min()..Anchor::max()];
15723            if !buffer.all_diff_hunks_expanded()
15724                && buffer.has_expanded_diff_hunks_in_ranges(&ranges, cx)
15725            {
15726                buffer.collapse_diff_hunks(ranges, cx);
15727                true
15728            } else {
15729                false
15730            }
15731        })
15732    }
15733
15734    fn toggle_diff_hunks_in_ranges(
15735        &mut self,
15736        ranges: Vec<Range<Anchor>>,
15737        cx: &mut Context<Editor>,
15738    ) {
15739        self.buffer.update(cx, |buffer, cx| {
15740            let expand = !buffer.has_expanded_diff_hunks_in_ranges(&ranges, cx);
15741            buffer.expand_or_collapse_diff_hunks(ranges, expand, cx);
15742        })
15743    }
15744
15745    fn toggle_single_diff_hunk(&mut self, range: Range<Anchor>, cx: &mut Context<Self>) {
15746        self.buffer.update(cx, |buffer, cx| {
15747            let snapshot = buffer.snapshot(cx);
15748            let excerpt_id = range.end.excerpt_id;
15749            let point_range = range.to_point(&snapshot);
15750            let expand = !buffer.single_hunk_is_expanded(range, cx);
15751            buffer.expand_or_collapse_diff_hunks_inner([(point_range, excerpt_id)], expand, cx);
15752        })
15753    }
15754
15755    pub(crate) fn apply_all_diff_hunks(
15756        &mut self,
15757        _: &ApplyAllDiffHunks,
15758        window: &mut Window,
15759        cx: &mut Context<Self>,
15760    ) {
15761        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
15762
15763        let buffers = self.buffer.read(cx).all_buffers();
15764        for branch_buffer in buffers {
15765            branch_buffer.update(cx, |branch_buffer, cx| {
15766                branch_buffer.merge_into_base(Vec::new(), cx);
15767            });
15768        }
15769
15770        if let Some(project) = self.project.clone() {
15771            self.save(true, project, window, cx).detach_and_log_err(cx);
15772        }
15773    }
15774
15775    pub(crate) fn apply_selected_diff_hunks(
15776        &mut self,
15777        _: &ApplyDiffHunk,
15778        window: &mut Window,
15779        cx: &mut Context<Self>,
15780    ) {
15781        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
15782        let snapshot = self.snapshot(window, cx);
15783        let hunks = snapshot.hunks_for_ranges(self.selections.ranges(cx));
15784        let mut ranges_by_buffer = HashMap::default();
15785        self.transact(window, cx, |editor, _window, cx| {
15786            for hunk in hunks {
15787                if let Some(buffer) = editor.buffer.read(cx).buffer(hunk.buffer_id) {
15788                    ranges_by_buffer
15789                        .entry(buffer.clone())
15790                        .or_insert_with(Vec::new)
15791                        .push(hunk.buffer_range.to_offset(buffer.read(cx)));
15792                }
15793            }
15794
15795            for (buffer, ranges) in ranges_by_buffer {
15796                buffer.update(cx, |buffer, cx| {
15797                    buffer.merge_into_base(ranges, cx);
15798                });
15799            }
15800        });
15801
15802        if let Some(project) = self.project.clone() {
15803            self.save(true, project, window, cx).detach_and_log_err(cx);
15804        }
15805    }
15806
15807    pub fn set_gutter_hovered(&mut self, hovered: bool, cx: &mut Context<Self>) {
15808        if hovered != self.gutter_hovered {
15809            self.gutter_hovered = hovered;
15810            cx.notify();
15811        }
15812    }
15813
15814    pub fn insert_blocks(
15815        &mut self,
15816        blocks: impl IntoIterator<Item = BlockProperties<Anchor>>,
15817        autoscroll: Option<Autoscroll>,
15818        cx: &mut Context<Self>,
15819    ) -> Vec<CustomBlockId> {
15820        let blocks = self
15821            .display_map
15822            .update(cx, |display_map, cx| display_map.insert_blocks(blocks, cx));
15823        if let Some(autoscroll) = autoscroll {
15824            self.request_autoscroll(autoscroll, cx);
15825        }
15826        cx.notify();
15827        blocks
15828    }
15829
15830    pub fn resize_blocks(
15831        &mut self,
15832        heights: HashMap<CustomBlockId, u32>,
15833        autoscroll: Option<Autoscroll>,
15834        cx: &mut Context<Self>,
15835    ) {
15836        self.display_map
15837            .update(cx, |display_map, cx| display_map.resize_blocks(heights, cx));
15838        if let Some(autoscroll) = autoscroll {
15839            self.request_autoscroll(autoscroll, cx);
15840        }
15841        cx.notify();
15842    }
15843
15844    pub fn replace_blocks(
15845        &mut self,
15846        renderers: HashMap<CustomBlockId, RenderBlock>,
15847        autoscroll: Option<Autoscroll>,
15848        cx: &mut Context<Self>,
15849    ) {
15850        self.display_map
15851            .update(cx, |display_map, _cx| display_map.replace_blocks(renderers));
15852        if let Some(autoscroll) = autoscroll {
15853            self.request_autoscroll(autoscroll, cx);
15854        }
15855        cx.notify();
15856    }
15857
15858    pub fn remove_blocks(
15859        &mut self,
15860        block_ids: HashSet<CustomBlockId>,
15861        autoscroll: Option<Autoscroll>,
15862        cx: &mut Context<Self>,
15863    ) {
15864        self.display_map.update(cx, |display_map, cx| {
15865            display_map.remove_blocks(block_ids, cx)
15866        });
15867        if let Some(autoscroll) = autoscroll {
15868            self.request_autoscroll(autoscroll, cx);
15869        }
15870        cx.notify();
15871    }
15872
15873    pub fn row_for_block(
15874        &self,
15875        block_id: CustomBlockId,
15876        cx: &mut Context<Self>,
15877    ) -> Option<DisplayRow> {
15878        self.display_map
15879            .update(cx, |map, cx| map.row_for_block(block_id, cx))
15880    }
15881
15882    pub(crate) fn set_focused_block(&mut self, focused_block: FocusedBlock) {
15883        self.focused_block = Some(focused_block);
15884    }
15885
15886    pub(crate) fn take_focused_block(&mut self) -> Option<FocusedBlock> {
15887        self.focused_block.take()
15888    }
15889
15890    pub fn insert_creases(
15891        &mut self,
15892        creases: impl IntoIterator<Item = Crease<Anchor>>,
15893        cx: &mut Context<Self>,
15894    ) -> Vec<CreaseId> {
15895        self.display_map
15896            .update(cx, |map, cx| map.insert_creases(creases, cx))
15897    }
15898
15899    pub fn remove_creases(
15900        &mut self,
15901        ids: impl IntoIterator<Item = CreaseId>,
15902        cx: &mut Context<Self>,
15903    ) {
15904        self.display_map
15905            .update(cx, |map, cx| map.remove_creases(ids, cx));
15906    }
15907
15908    pub fn longest_row(&self, cx: &mut App) -> DisplayRow {
15909        self.display_map
15910            .update(cx, |map, cx| map.snapshot(cx))
15911            .longest_row()
15912    }
15913
15914    pub fn max_point(&self, cx: &mut App) -> DisplayPoint {
15915        self.display_map
15916            .update(cx, |map, cx| map.snapshot(cx))
15917            .max_point()
15918    }
15919
15920    pub fn text(&self, cx: &App) -> String {
15921        self.buffer.read(cx).read(cx).text()
15922    }
15923
15924    pub fn is_empty(&self, cx: &App) -> bool {
15925        self.buffer.read(cx).read(cx).is_empty()
15926    }
15927
15928    pub fn text_option(&self, cx: &App) -> Option<String> {
15929        let text = self.text(cx);
15930        let text = text.trim();
15931
15932        if text.is_empty() {
15933            return None;
15934        }
15935
15936        Some(text.to_string())
15937    }
15938
15939    pub fn set_text(
15940        &mut self,
15941        text: impl Into<Arc<str>>,
15942        window: &mut Window,
15943        cx: &mut Context<Self>,
15944    ) {
15945        self.transact(window, cx, |this, _, cx| {
15946            this.buffer
15947                .read(cx)
15948                .as_singleton()
15949                .expect("you can only call set_text on editors for singleton buffers")
15950                .update(cx, |buffer, cx| buffer.set_text(text, cx));
15951        });
15952    }
15953
15954    pub fn display_text(&self, cx: &mut App) -> String {
15955        self.display_map
15956            .update(cx, |map, cx| map.snapshot(cx))
15957            .text()
15958    }
15959
15960    pub fn wrap_guides(&self, cx: &App) -> SmallVec<[(usize, bool); 2]> {
15961        let mut wrap_guides = smallvec::smallvec![];
15962
15963        if self.show_wrap_guides == Some(false) {
15964            return wrap_guides;
15965        }
15966
15967        let settings = self.buffer.read(cx).language_settings(cx);
15968        if settings.show_wrap_guides {
15969            match self.soft_wrap_mode(cx) {
15970                SoftWrap::Column(soft_wrap) => {
15971                    wrap_guides.push((soft_wrap as usize, true));
15972                }
15973                SoftWrap::Bounded(soft_wrap) => {
15974                    wrap_guides.push((soft_wrap as usize, true));
15975                }
15976                SoftWrap::GitDiff | SoftWrap::None | SoftWrap::EditorWidth => {}
15977            }
15978            wrap_guides.extend(settings.wrap_guides.iter().map(|guide| (*guide, false)))
15979        }
15980
15981        wrap_guides
15982    }
15983
15984    pub fn soft_wrap_mode(&self, cx: &App) -> SoftWrap {
15985        let settings = self.buffer.read(cx).language_settings(cx);
15986        let mode = self.soft_wrap_mode_override.unwrap_or(settings.soft_wrap);
15987        match mode {
15988            language_settings::SoftWrap::PreferLine | language_settings::SoftWrap::None => {
15989                SoftWrap::None
15990            }
15991            language_settings::SoftWrap::EditorWidth => SoftWrap::EditorWidth,
15992            language_settings::SoftWrap::PreferredLineLength => {
15993                SoftWrap::Column(settings.preferred_line_length)
15994            }
15995            language_settings::SoftWrap::Bounded => {
15996                SoftWrap::Bounded(settings.preferred_line_length)
15997            }
15998        }
15999    }
16000
16001    pub fn set_soft_wrap_mode(
16002        &mut self,
16003        mode: language_settings::SoftWrap,
16004
16005        cx: &mut Context<Self>,
16006    ) {
16007        self.soft_wrap_mode_override = Some(mode);
16008        cx.notify();
16009    }
16010
16011    pub fn set_hard_wrap(&mut self, hard_wrap: Option<usize>, cx: &mut Context<Self>) {
16012        self.hard_wrap = hard_wrap;
16013        cx.notify();
16014    }
16015
16016    pub fn set_text_style_refinement(&mut self, style: TextStyleRefinement) {
16017        self.text_style_refinement = Some(style);
16018    }
16019
16020    /// called by the Element so we know what style we were most recently rendered with.
16021    pub(crate) fn set_style(
16022        &mut self,
16023        style: EditorStyle,
16024        window: &mut Window,
16025        cx: &mut Context<Self>,
16026    ) {
16027        let rem_size = window.rem_size();
16028        self.display_map.update(cx, |map, cx| {
16029            map.set_font(
16030                style.text.font(),
16031                style.text.font_size.to_pixels(rem_size),
16032                cx,
16033            )
16034        });
16035        self.style = Some(style);
16036    }
16037
16038    pub fn style(&self) -> Option<&EditorStyle> {
16039        self.style.as_ref()
16040    }
16041
16042    // Called by the element. This method is not designed to be called outside of the editor
16043    // element's layout code because it does not notify when rewrapping is computed synchronously.
16044    pub(crate) fn set_wrap_width(&self, width: Option<Pixels>, cx: &mut App) -> bool {
16045        self.display_map
16046            .update(cx, |map, cx| map.set_wrap_width(width, cx))
16047    }
16048
16049    pub fn set_soft_wrap(&mut self) {
16050        self.soft_wrap_mode_override = Some(language_settings::SoftWrap::EditorWidth)
16051    }
16052
16053    pub fn toggle_soft_wrap(&mut self, _: &ToggleSoftWrap, _: &mut Window, cx: &mut Context<Self>) {
16054        if self.soft_wrap_mode_override.is_some() {
16055            self.soft_wrap_mode_override.take();
16056        } else {
16057            let soft_wrap = match self.soft_wrap_mode(cx) {
16058                SoftWrap::GitDiff => return,
16059                SoftWrap::None => language_settings::SoftWrap::EditorWidth,
16060                SoftWrap::EditorWidth | SoftWrap::Column(_) | SoftWrap::Bounded(_) => {
16061                    language_settings::SoftWrap::None
16062                }
16063            };
16064            self.soft_wrap_mode_override = Some(soft_wrap);
16065        }
16066        cx.notify();
16067    }
16068
16069    pub fn toggle_tab_bar(&mut self, _: &ToggleTabBar, _: &mut Window, cx: &mut Context<Self>) {
16070        let Some(workspace) = self.workspace() else {
16071            return;
16072        };
16073        let fs = workspace.read(cx).app_state().fs.clone();
16074        let current_show = TabBarSettings::get_global(cx).show;
16075        update_settings_file::<TabBarSettings>(fs, cx, move |setting, _| {
16076            setting.show = Some(!current_show);
16077        });
16078    }
16079
16080    pub fn toggle_indent_guides(
16081        &mut self,
16082        _: &ToggleIndentGuides,
16083        _: &mut Window,
16084        cx: &mut Context<Self>,
16085    ) {
16086        let currently_enabled = self.should_show_indent_guides().unwrap_or_else(|| {
16087            self.buffer
16088                .read(cx)
16089                .language_settings(cx)
16090                .indent_guides
16091                .enabled
16092        });
16093        self.show_indent_guides = Some(!currently_enabled);
16094        cx.notify();
16095    }
16096
16097    fn should_show_indent_guides(&self) -> Option<bool> {
16098        self.show_indent_guides
16099    }
16100
16101    pub fn toggle_line_numbers(
16102        &mut self,
16103        _: &ToggleLineNumbers,
16104        _: &mut Window,
16105        cx: &mut Context<Self>,
16106    ) {
16107        let mut editor_settings = EditorSettings::get_global(cx).clone();
16108        editor_settings.gutter.line_numbers = !editor_settings.gutter.line_numbers;
16109        EditorSettings::override_global(editor_settings, cx);
16110    }
16111
16112    pub fn line_numbers_enabled(&self, cx: &App) -> bool {
16113        if let Some(show_line_numbers) = self.show_line_numbers {
16114            return show_line_numbers;
16115        }
16116        EditorSettings::get_global(cx).gutter.line_numbers
16117    }
16118
16119    pub fn should_use_relative_line_numbers(&self, cx: &mut App) -> bool {
16120        self.use_relative_line_numbers
16121            .unwrap_or(EditorSettings::get_global(cx).relative_line_numbers)
16122    }
16123
16124    pub fn toggle_relative_line_numbers(
16125        &mut self,
16126        _: &ToggleRelativeLineNumbers,
16127        _: &mut Window,
16128        cx: &mut Context<Self>,
16129    ) {
16130        let is_relative = self.should_use_relative_line_numbers(cx);
16131        self.set_relative_line_number(Some(!is_relative), cx)
16132    }
16133
16134    pub fn set_relative_line_number(&mut self, is_relative: Option<bool>, cx: &mut Context<Self>) {
16135        self.use_relative_line_numbers = is_relative;
16136        cx.notify();
16137    }
16138
16139    pub fn set_show_gutter(&mut self, show_gutter: bool, cx: &mut Context<Self>) {
16140        self.show_gutter = show_gutter;
16141        cx.notify();
16142    }
16143
16144    pub fn set_show_scrollbars(&mut self, show_scrollbars: bool, cx: &mut Context<Self>) {
16145        self.show_scrollbars = show_scrollbars;
16146        cx.notify();
16147    }
16148
16149    pub fn set_show_line_numbers(&mut self, show_line_numbers: bool, cx: &mut Context<Self>) {
16150        self.show_line_numbers = Some(show_line_numbers);
16151        cx.notify();
16152    }
16153
16154    pub fn set_show_git_diff_gutter(&mut self, show_git_diff_gutter: bool, cx: &mut Context<Self>) {
16155        self.show_git_diff_gutter = Some(show_git_diff_gutter);
16156        cx.notify();
16157    }
16158
16159    pub fn set_show_code_actions(&mut self, show_code_actions: bool, cx: &mut Context<Self>) {
16160        self.show_code_actions = Some(show_code_actions);
16161        cx.notify();
16162    }
16163
16164    pub fn set_show_runnables(&mut self, show_runnables: bool, cx: &mut Context<Self>) {
16165        self.show_runnables = Some(show_runnables);
16166        cx.notify();
16167    }
16168
16169    pub fn set_show_breakpoints(&mut self, show_breakpoints: bool, cx: &mut Context<Self>) {
16170        self.show_breakpoints = Some(show_breakpoints);
16171        cx.notify();
16172    }
16173
16174    pub fn set_masked(&mut self, masked: bool, cx: &mut Context<Self>) {
16175        if self.display_map.read(cx).masked != masked {
16176            self.display_map.update(cx, |map, _| map.masked = masked);
16177        }
16178        cx.notify()
16179    }
16180
16181    pub fn set_show_wrap_guides(&mut self, show_wrap_guides: bool, cx: &mut Context<Self>) {
16182        self.show_wrap_guides = Some(show_wrap_guides);
16183        cx.notify();
16184    }
16185
16186    pub fn set_show_indent_guides(&mut self, show_indent_guides: bool, cx: &mut Context<Self>) {
16187        self.show_indent_guides = Some(show_indent_guides);
16188        cx.notify();
16189    }
16190
16191    pub fn working_directory(&self, cx: &App) -> Option<PathBuf> {
16192        if let Some(buffer) = self.buffer().read(cx).as_singleton() {
16193            if let Some(file) = buffer.read(cx).file().and_then(|f| f.as_local()) {
16194                if let Some(dir) = file.abs_path(cx).parent() {
16195                    return Some(dir.to_owned());
16196                }
16197            }
16198
16199            if let Some(project_path) = buffer.read(cx).project_path(cx) {
16200                return Some(project_path.path.to_path_buf());
16201            }
16202        }
16203
16204        None
16205    }
16206
16207    fn target_file<'a>(&self, cx: &'a App) -> Option<&'a dyn language::LocalFile> {
16208        self.active_excerpt(cx)?
16209            .1
16210            .read(cx)
16211            .file()
16212            .and_then(|f| f.as_local())
16213    }
16214
16215    pub fn target_file_abs_path(&self, cx: &mut Context<Self>) -> Option<PathBuf> {
16216        self.active_excerpt(cx).and_then(|(_, buffer, _)| {
16217            let buffer = buffer.read(cx);
16218            if let Some(project_path) = buffer.project_path(cx) {
16219                let project = self.project.as_ref()?.read(cx);
16220                project.absolute_path(&project_path, cx)
16221            } else {
16222                buffer
16223                    .file()
16224                    .and_then(|file| file.as_local().map(|file| file.abs_path(cx)))
16225            }
16226        })
16227    }
16228
16229    fn target_file_path(&self, cx: &mut Context<Self>) -> Option<PathBuf> {
16230        self.active_excerpt(cx).and_then(|(_, buffer, _)| {
16231            let project_path = buffer.read(cx).project_path(cx)?;
16232            let project = self.project.as_ref()?.read(cx);
16233            let entry = project.entry_for_path(&project_path, cx)?;
16234            let path = entry.path.to_path_buf();
16235            Some(path)
16236        })
16237    }
16238
16239    pub fn reveal_in_finder(
16240        &mut self,
16241        _: &RevealInFileManager,
16242        _window: &mut Window,
16243        cx: &mut Context<Self>,
16244    ) {
16245        if let Some(target) = self.target_file(cx) {
16246            cx.reveal_path(&target.abs_path(cx));
16247        }
16248    }
16249
16250    pub fn copy_path(
16251        &mut self,
16252        _: &zed_actions::workspace::CopyPath,
16253        _window: &mut Window,
16254        cx: &mut Context<Self>,
16255    ) {
16256        if let Some(path) = self.target_file_abs_path(cx) {
16257            if let Some(path) = path.to_str() {
16258                cx.write_to_clipboard(ClipboardItem::new_string(path.to_string()));
16259            }
16260        }
16261    }
16262
16263    pub fn copy_relative_path(
16264        &mut self,
16265        _: &zed_actions::workspace::CopyRelativePath,
16266        _window: &mut Window,
16267        cx: &mut Context<Self>,
16268    ) {
16269        if let Some(path) = self.target_file_path(cx) {
16270            if let Some(path) = path.to_str() {
16271                cx.write_to_clipboard(ClipboardItem::new_string(path.to_string()));
16272            }
16273        }
16274    }
16275
16276    pub fn project_path(&self, cx: &App) -> Option<ProjectPath> {
16277        if let Some(buffer) = self.buffer.read(cx).as_singleton() {
16278            buffer.read(cx).project_path(cx)
16279        } else {
16280            None
16281        }
16282    }
16283
16284    // Returns true if the editor handled a go-to-line request
16285    pub fn go_to_active_debug_line(&mut self, window: &mut Window, cx: &mut Context<Self>) -> bool {
16286        maybe!({
16287            let breakpoint_store = self.breakpoint_store.as_ref()?;
16288
16289            let Some((_, _, active_position)) =
16290                breakpoint_store.read(cx).active_position().cloned()
16291            else {
16292                self.clear_row_highlights::<DebugCurrentRowHighlight>();
16293                return None;
16294            };
16295
16296            let snapshot = self
16297                .project
16298                .as_ref()?
16299                .read(cx)
16300                .buffer_for_id(active_position.buffer_id?, cx)?
16301                .read(cx)
16302                .snapshot();
16303
16304            let mut handled = false;
16305            for (id, ExcerptRange { context, .. }) in self
16306                .buffer
16307                .read(cx)
16308                .excerpts_for_buffer(active_position.buffer_id?, cx)
16309            {
16310                if context.start.cmp(&active_position, &snapshot).is_ge()
16311                    || context.end.cmp(&active_position, &snapshot).is_lt()
16312                {
16313                    continue;
16314                }
16315                let snapshot = self.buffer.read(cx).snapshot(cx);
16316                let multibuffer_anchor = snapshot.anchor_in_excerpt(id, active_position)?;
16317
16318                handled = true;
16319                self.clear_row_highlights::<DebugCurrentRowHighlight>();
16320                self.go_to_line::<DebugCurrentRowHighlight>(
16321                    multibuffer_anchor,
16322                    Some(cx.theme().colors().editor_debugger_active_line_background),
16323                    window,
16324                    cx,
16325                );
16326
16327                cx.notify();
16328            }
16329            handled.then_some(())
16330        })
16331        .is_some()
16332    }
16333
16334    pub fn copy_file_name_without_extension(
16335        &mut self,
16336        _: &CopyFileNameWithoutExtension,
16337        _: &mut Window,
16338        cx: &mut Context<Self>,
16339    ) {
16340        if let Some(file) = self.target_file(cx) {
16341            if let Some(file_stem) = file.path().file_stem() {
16342                if let Some(name) = file_stem.to_str() {
16343                    cx.write_to_clipboard(ClipboardItem::new_string(name.to_string()));
16344                }
16345            }
16346        }
16347    }
16348
16349    pub fn copy_file_name(&mut self, _: &CopyFileName, _: &mut Window, cx: &mut Context<Self>) {
16350        if let Some(file) = self.target_file(cx) {
16351            if let Some(file_name) = file.path().file_name() {
16352                if let Some(name) = file_name.to_str() {
16353                    cx.write_to_clipboard(ClipboardItem::new_string(name.to_string()));
16354                }
16355            }
16356        }
16357    }
16358
16359    pub fn toggle_git_blame(
16360        &mut self,
16361        _: &::git::Blame,
16362        window: &mut Window,
16363        cx: &mut Context<Self>,
16364    ) {
16365        self.show_git_blame_gutter = !self.show_git_blame_gutter;
16366
16367        if self.show_git_blame_gutter && !self.has_blame_entries(cx) {
16368            self.start_git_blame(true, window, cx);
16369        }
16370
16371        cx.notify();
16372    }
16373
16374    pub fn toggle_git_blame_inline(
16375        &mut self,
16376        _: &ToggleGitBlameInline,
16377        window: &mut Window,
16378        cx: &mut Context<Self>,
16379    ) {
16380        self.toggle_git_blame_inline_internal(true, window, cx);
16381        cx.notify();
16382    }
16383
16384    pub fn open_git_blame_commit(
16385        &mut self,
16386        _: &OpenGitBlameCommit,
16387        window: &mut Window,
16388        cx: &mut Context<Self>,
16389    ) {
16390        self.open_git_blame_commit_internal(window, cx);
16391    }
16392
16393    fn open_git_blame_commit_internal(
16394        &mut self,
16395        window: &mut Window,
16396        cx: &mut Context<Self>,
16397    ) -> Option<()> {
16398        let blame = self.blame.as_ref()?;
16399        let snapshot = self.snapshot(window, cx);
16400        let cursor = self.selections.newest::<Point>(cx).head();
16401        let (buffer, point, _) = snapshot.buffer_snapshot.point_to_buffer_point(cursor)?;
16402        let blame_entry = blame
16403            .update(cx, |blame, cx| {
16404                blame
16405                    .blame_for_rows(
16406                        &[RowInfo {
16407                            buffer_id: Some(buffer.remote_id()),
16408                            buffer_row: Some(point.row),
16409                            ..Default::default()
16410                        }],
16411                        cx,
16412                    )
16413                    .next()
16414            })
16415            .flatten()?;
16416        let renderer = cx.global::<GlobalBlameRenderer>().0.clone();
16417        let repo = blame.read(cx).repository(cx)?;
16418        let workspace = self.workspace()?.downgrade();
16419        renderer.open_blame_commit(blame_entry, repo, workspace, window, cx);
16420        None
16421    }
16422
16423    pub fn git_blame_inline_enabled(&self) -> bool {
16424        self.git_blame_inline_enabled
16425    }
16426
16427    pub fn toggle_selection_menu(
16428        &mut self,
16429        _: &ToggleSelectionMenu,
16430        _: &mut Window,
16431        cx: &mut Context<Self>,
16432    ) {
16433        self.show_selection_menu = self
16434            .show_selection_menu
16435            .map(|show_selections_menu| !show_selections_menu)
16436            .or_else(|| Some(!EditorSettings::get_global(cx).toolbar.selections_menu));
16437
16438        cx.notify();
16439    }
16440
16441    pub fn selection_menu_enabled(&self, cx: &App) -> bool {
16442        self.show_selection_menu
16443            .unwrap_or_else(|| EditorSettings::get_global(cx).toolbar.selections_menu)
16444    }
16445
16446    fn start_git_blame(
16447        &mut self,
16448        user_triggered: bool,
16449        window: &mut Window,
16450        cx: &mut Context<Self>,
16451    ) {
16452        if let Some(project) = self.project.as_ref() {
16453            let Some(buffer) = self.buffer().read(cx).as_singleton() else {
16454                return;
16455            };
16456
16457            if buffer.read(cx).file().is_none() {
16458                return;
16459            }
16460
16461            let focused = self.focus_handle(cx).contains_focused(window, cx);
16462
16463            let project = project.clone();
16464            let blame = cx.new(|cx| GitBlame::new(buffer, project, user_triggered, focused, cx));
16465            self.blame_subscription =
16466                Some(cx.observe_in(&blame, window, |_, _, _, cx| cx.notify()));
16467            self.blame = Some(blame);
16468        }
16469    }
16470
16471    fn toggle_git_blame_inline_internal(
16472        &mut self,
16473        user_triggered: bool,
16474        window: &mut Window,
16475        cx: &mut Context<Self>,
16476    ) {
16477        if self.git_blame_inline_enabled {
16478            self.git_blame_inline_enabled = false;
16479            self.show_git_blame_inline = false;
16480            self.show_git_blame_inline_delay_task.take();
16481        } else {
16482            self.git_blame_inline_enabled = true;
16483            self.start_git_blame_inline(user_triggered, window, cx);
16484        }
16485
16486        cx.notify();
16487    }
16488
16489    fn start_git_blame_inline(
16490        &mut self,
16491        user_triggered: bool,
16492        window: &mut Window,
16493        cx: &mut Context<Self>,
16494    ) {
16495        self.start_git_blame(user_triggered, window, cx);
16496
16497        if ProjectSettings::get_global(cx)
16498            .git
16499            .inline_blame_delay()
16500            .is_some()
16501        {
16502            self.start_inline_blame_timer(window, cx);
16503        } else {
16504            self.show_git_blame_inline = true
16505        }
16506    }
16507
16508    pub fn blame(&self) -> Option<&Entity<GitBlame>> {
16509        self.blame.as_ref()
16510    }
16511
16512    pub fn show_git_blame_gutter(&self) -> bool {
16513        self.show_git_blame_gutter
16514    }
16515
16516    pub fn render_git_blame_gutter(&self, cx: &App) -> bool {
16517        self.show_git_blame_gutter && self.has_blame_entries(cx)
16518    }
16519
16520    pub fn render_git_blame_inline(&self, window: &Window, cx: &App) -> bool {
16521        self.show_git_blame_inline
16522            && (self.focus_handle.is_focused(window)
16523                || self
16524                    .git_blame_inline_tooltip
16525                    .as_ref()
16526                    .and_then(|t| t.upgrade())
16527                    .is_some())
16528            && !self.newest_selection_head_on_empty_line(cx)
16529            && self.has_blame_entries(cx)
16530    }
16531
16532    fn has_blame_entries(&self, cx: &App) -> bool {
16533        self.blame()
16534            .map_or(false, |blame| blame.read(cx).has_generated_entries())
16535    }
16536
16537    fn newest_selection_head_on_empty_line(&self, cx: &App) -> bool {
16538        let cursor_anchor = self.selections.newest_anchor().head();
16539
16540        let snapshot = self.buffer.read(cx).snapshot(cx);
16541        let buffer_row = MultiBufferRow(cursor_anchor.to_point(&snapshot).row);
16542
16543        snapshot.line_len(buffer_row) == 0
16544    }
16545
16546    fn get_permalink_to_line(&self, cx: &mut Context<Self>) -> Task<Result<url::Url>> {
16547        let buffer_and_selection = maybe!({
16548            let selection = self.selections.newest::<Point>(cx);
16549            let selection_range = selection.range();
16550
16551            let multi_buffer = self.buffer().read(cx);
16552            let multi_buffer_snapshot = multi_buffer.snapshot(cx);
16553            let buffer_ranges = multi_buffer_snapshot.range_to_buffer_ranges(selection_range);
16554
16555            let (buffer, range, _) = if selection.reversed {
16556                buffer_ranges.first()
16557            } else {
16558                buffer_ranges.last()
16559            }?;
16560
16561            let selection = text::ToPoint::to_point(&range.start, &buffer).row
16562                ..text::ToPoint::to_point(&range.end, &buffer).row;
16563            Some((
16564                multi_buffer.buffer(buffer.remote_id()).unwrap().clone(),
16565                selection,
16566            ))
16567        });
16568
16569        let Some((buffer, selection)) = buffer_and_selection else {
16570            return Task::ready(Err(anyhow!("failed to determine buffer and selection")));
16571        };
16572
16573        let Some(project) = self.project.as_ref() else {
16574            return Task::ready(Err(anyhow!("editor does not have project")));
16575        };
16576
16577        project.update(cx, |project, cx| {
16578            project.get_permalink_to_line(&buffer, selection, cx)
16579        })
16580    }
16581
16582    pub fn copy_permalink_to_line(
16583        &mut self,
16584        _: &CopyPermalinkToLine,
16585        window: &mut Window,
16586        cx: &mut Context<Self>,
16587    ) {
16588        let permalink_task = self.get_permalink_to_line(cx);
16589        let workspace = self.workspace();
16590
16591        cx.spawn_in(window, async move |_, cx| match permalink_task.await {
16592            Ok(permalink) => {
16593                cx.update(|_, cx| {
16594                    cx.write_to_clipboard(ClipboardItem::new_string(permalink.to_string()));
16595                })
16596                .ok();
16597            }
16598            Err(err) => {
16599                let message = format!("Failed to copy permalink: {err}");
16600
16601                Err::<(), anyhow::Error>(err).log_err();
16602
16603                if let Some(workspace) = workspace {
16604                    workspace
16605                        .update_in(cx, |workspace, _, cx| {
16606                            struct CopyPermalinkToLine;
16607
16608                            workspace.show_toast(
16609                                Toast::new(
16610                                    NotificationId::unique::<CopyPermalinkToLine>(),
16611                                    message,
16612                                ),
16613                                cx,
16614                            )
16615                        })
16616                        .ok();
16617                }
16618            }
16619        })
16620        .detach();
16621    }
16622
16623    pub fn copy_file_location(
16624        &mut self,
16625        _: &CopyFileLocation,
16626        _: &mut Window,
16627        cx: &mut Context<Self>,
16628    ) {
16629        let selection = self.selections.newest::<Point>(cx).start.row + 1;
16630        if let Some(file) = self.target_file(cx) {
16631            if let Some(path) = file.path().to_str() {
16632                cx.write_to_clipboard(ClipboardItem::new_string(format!("{path}:{selection}")));
16633            }
16634        }
16635    }
16636
16637    pub fn open_permalink_to_line(
16638        &mut self,
16639        _: &OpenPermalinkToLine,
16640        window: &mut Window,
16641        cx: &mut Context<Self>,
16642    ) {
16643        let permalink_task = self.get_permalink_to_line(cx);
16644        let workspace = self.workspace();
16645
16646        cx.spawn_in(window, async move |_, cx| match permalink_task.await {
16647            Ok(permalink) => {
16648                cx.update(|_, cx| {
16649                    cx.open_url(permalink.as_ref());
16650                })
16651                .ok();
16652            }
16653            Err(err) => {
16654                let message = format!("Failed to open permalink: {err}");
16655
16656                Err::<(), anyhow::Error>(err).log_err();
16657
16658                if let Some(workspace) = workspace {
16659                    workspace
16660                        .update(cx, |workspace, cx| {
16661                            struct OpenPermalinkToLine;
16662
16663                            workspace.show_toast(
16664                                Toast::new(
16665                                    NotificationId::unique::<OpenPermalinkToLine>(),
16666                                    message,
16667                                ),
16668                                cx,
16669                            )
16670                        })
16671                        .ok();
16672                }
16673            }
16674        })
16675        .detach();
16676    }
16677
16678    pub fn insert_uuid_v4(
16679        &mut self,
16680        _: &InsertUuidV4,
16681        window: &mut Window,
16682        cx: &mut Context<Self>,
16683    ) {
16684        self.insert_uuid(UuidVersion::V4, window, cx);
16685    }
16686
16687    pub fn insert_uuid_v7(
16688        &mut self,
16689        _: &InsertUuidV7,
16690        window: &mut Window,
16691        cx: &mut Context<Self>,
16692    ) {
16693        self.insert_uuid(UuidVersion::V7, window, cx);
16694    }
16695
16696    fn insert_uuid(&mut self, version: UuidVersion, window: &mut Window, cx: &mut Context<Self>) {
16697        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
16698        self.transact(window, cx, |this, window, cx| {
16699            let edits = this
16700                .selections
16701                .all::<Point>(cx)
16702                .into_iter()
16703                .map(|selection| {
16704                    let uuid = match version {
16705                        UuidVersion::V4 => uuid::Uuid::new_v4(),
16706                        UuidVersion::V7 => uuid::Uuid::now_v7(),
16707                    };
16708
16709                    (selection.range(), uuid.to_string())
16710                });
16711            this.edit(edits, cx);
16712            this.refresh_inline_completion(true, false, window, cx);
16713        });
16714    }
16715
16716    pub fn open_selections_in_multibuffer(
16717        &mut self,
16718        _: &OpenSelectionsInMultibuffer,
16719        window: &mut Window,
16720        cx: &mut Context<Self>,
16721    ) {
16722        let multibuffer = self.buffer.read(cx);
16723
16724        let Some(buffer) = multibuffer.as_singleton() else {
16725            return;
16726        };
16727
16728        let Some(workspace) = self.workspace() else {
16729            return;
16730        };
16731
16732        let locations = self
16733            .selections
16734            .disjoint_anchors()
16735            .iter()
16736            .map(|range| Location {
16737                buffer: buffer.clone(),
16738                range: range.start.text_anchor..range.end.text_anchor,
16739            })
16740            .collect::<Vec<_>>();
16741
16742        let title = multibuffer.title(cx).to_string();
16743
16744        cx.spawn_in(window, async move |_, cx| {
16745            workspace.update_in(cx, |workspace, window, cx| {
16746                Self::open_locations_in_multibuffer(
16747                    workspace,
16748                    locations,
16749                    format!("Selections for '{title}'"),
16750                    false,
16751                    MultibufferSelectionMode::All,
16752                    window,
16753                    cx,
16754                );
16755            })
16756        })
16757        .detach();
16758    }
16759
16760    /// Adds a row highlight for the given range. If a row has multiple highlights, the
16761    /// last highlight added will be used.
16762    ///
16763    /// If the range ends at the beginning of a line, then that line will not be highlighted.
16764    pub fn highlight_rows<T: 'static>(
16765        &mut self,
16766        range: Range<Anchor>,
16767        color: Hsla,
16768        should_autoscroll: bool,
16769        cx: &mut Context<Self>,
16770    ) {
16771        let snapshot = self.buffer().read(cx).snapshot(cx);
16772        let row_highlights = self.highlighted_rows.entry(TypeId::of::<T>()).or_default();
16773        let ix = row_highlights.binary_search_by(|highlight| {
16774            Ordering::Equal
16775                .then_with(|| highlight.range.start.cmp(&range.start, &snapshot))
16776                .then_with(|| highlight.range.end.cmp(&range.end, &snapshot))
16777        });
16778
16779        if let Err(mut ix) = ix {
16780            let index = post_inc(&mut self.highlight_order);
16781
16782            // If this range intersects with the preceding highlight, then merge it with
16783            // the preceding highlight. Otherwise insert a new highlight.
16784            let mut merged = false;
16785            if ix > 0 {
16786                let prev_highlight = &mut row_highlights[ix - 1];
16787                if prev_highlight
16788                    .range
16789                    .end
16790                    .cmp(&range.start, &snapshot)
16791                    .is_ge()
16792                {
16793                    ix -= 1;
16794                    if prev_highlight.range.end.cmp(&range.end, &snapshot).is_lt() {
16795                        prev_highlight.range.end = range.end;
16796                    }
16797                    merged = true;
16798                    prev_highlight.index = index;
16799                    prev_highlight.color = color;
16800                    prev_highlight.should_autoscroll = should_autoscroll;
16801                }
16802            }
16803
16804            if !merged {
16805                row_highlights.insert(
16806                    ix,
16807                    RowHighlight {
16808                        range: range.clone(),
16809                        index,
16810                        color,
16811                        should_autoscroll,
16812                    },
16813                );
16814            }
16815
16816            // If any of the following highlights intersect with this one, merge them.
16817            while let Some(next_highlight) = row_highlights.get(ix + 1) {
16818                let highlight = &row_highlights[ix];
16819                if next_highlight
16820                    .range
16821                    .start
16822                    .cmp(&highlight.range.end, &snapshot)
16823                    .is_le()
16824                {
16825                    if next_highlight
16826                        .range
16827                        .end
16828                        .cmp(&highlight.range.end, &snapshot)
16829                        .is_gt()
16830                    {
16831                        row_highlights[ix].range.end = next_highlight.range.end;
16832                    }
16833                    row_highlights.remove(ix + 1);
16834                } else {
16835                    break;
16836                }
16837            }
16838        }
16839    }
16840
16841    /// Remove any highlighted row ranges of the given type that intersect the
16842    /// given ranges.
16843    pub fn remove_highlighted_rows<T: 'static>(
16844        &mut self,
16845        ranges_to_remove: Vec<Range<Anchor>>,
16846        cx: &mut Context<Self>,
16847    ) {
16848        let snapshot = self.buffer().read(cx).snapshot(cx);
16849        let row_highlights = self.highlighted_rows.entry(TypeId::of::<T>()).or_default();
16850        let mut ranges_to_remove = ranges_to_remove.iter().peekable();
16851        row_highlights.retain(|highlight| {
16852            while let Some(range_to_remove) = ranges_to_remove.peek() {
16853                match range_to_remove.end.cmp(&highlight.range.start, &snapshot) {
16854                    Ordering::Less | Ordering::Equal => {
16855                        ranges_to_remove.next();
16856                    }
16857                    Ordering::Greater => {
16858                        match range_to_remove.start.cmp(&highlight.range.end, &snapshot) {
16859                            Ordering::Less | Ordering::Equal => {
16860                                return false;
16861                            }
16862                            Ordering::Greater => break,
16863                        }
16864                    }
16865                }
16866            }
16867
16868            true
16869        })
16870    }
16871
16872    /// Clear all anchor ranges for a certain highlight context type, so no corresponding rows will be highlighted.
16873    pub fn clear_row_highlights<T: 'static>(&mut self) {
16874        self.highlighted_rows.remove(&TypeId::of::<T>());
16875    }
16876
16877    /// For a highlight given context type, gets all anchor ranges that will be used for row highlighting.
16878    pub fn highlighted_rows<T: 'static>(&self) -> impl '_ + Iterator<Item = (Range<Anchor>, Hsla)> {
16879        self.highlighted_rows
16880            .get(&TypeId::of::<T>())
16881            .map_or(&[] as &[_], |vec| vec.as_slice())
16882            .iter()
16883            .map(|highlight| (highlight.range.clone(), highlight.color))
16884    }
16885
16886    /// Merges all anchor ranges for all context types ever set, picking the last highlight added in case of a row conflict.
16887    /// Returns a map of display rows that are highlighted and their corresponding highlight color.
16888    /// Allows to ignore certain kinds of highlights.
16889    pub fn highlighted_display_rows(
16890        &self,
16891        window: &mut Window,
16892        cx: &mut App,
16893    ) -> BTreeMap<DisplayRow, LineHighlight> {
16894        let snapshot = self.snapshot(window, cx);
16895        let mut used_highlight_orders = HashMap::default();
16896        self.highlighted_rows
16897            .iter()
16898            .flat_map(|(_, highlighted_rows)| highlighted_rows.iter())
16899            .fold(
16900                BTreeMap::<DisplayRow, LineHighlight>::new(),
16901                |mut unique_rows, highlight| {
16902                    let start = highlight.range.start.to_display_point(&snapshot);
16903                    let end = highlight.range.end.to_display_point(&snapshot);
16904                    let start_row = start.row().0;
16905                    let end_row = if highlight.range.end.text_anchor != text::Anchor::MAX
16906                        && end.column() == 0
16907                    {
16908                        end.row().0.saturating_sub(1)
16909                    } else {
16910                        end.row().0
16911                    };
16912                    for row in start_row..=end_row {
16913                        let used_index =
16914                            used_highlight_orders.entry(row).or_insert(highlight.index);
16915                        if highlight.index >= *used_index {
16916                            *used_index = highlight.index;
16917                            unique_rows.insert(DisplayRow(row), highlight.color.into());
16918                        }
16919                    }
16920                    unique_rows
16921                },
16922            )
16923    }
16924
16925    pub fn highlighted_display_row_for_autoscroll(
16926        &self,
16927        snapshot: &DisplaySnapshot,
16928    ) -> Option<DisplayRow> {
16929        self.highlighted_rows
16930            .values()
16931            .flat_map(|highlighted_rows| highlighted_rows.iter())
16932            .filter_map(|highlight| {
16933                if highlight.should_autoscroll {
16934                    Some(highlight.range.start.to_display_point(snapshot).row())
16935                } else {
16936                    None
16937                }
16938            })
16939            .min()
16940    }
16941
16942    pub fn set_search_within_ranges(&mut self, ranges: &[Range<Anchor>], cx: &mut Context<Self>) {
16943        self.highlight_background::<SearchWithinRange>(
16944            ranges,
16945            |colors| colors.editor_document_highlight_read_background,
16946            cx,
16947        )
16948    }
16949
16950    pub fn set_breadcrumb_header(&mut self, new_header: String) {
16951        self.breadcrumb_header = Some(new_header);
16952    }
16953
16954    pub fn clear_search_within_ranges(&mut self, cx: &mut Context<Self>) {
16955        self.clear_background_highlights::<SearchWithinRange>(cx);
16956    }
16957
16958    pub fn highlight_background<T: 'static>(
16959        &mut self,
16960        ranges: &[Range<Anchor>],
16961        color_fetcher: fn(&ThemeColors) -> Hsla,
16962        cx: &mut Context<Self>,
16963    ) {
16964        self.background_highlights
16965            .insert(TypeId::of::<T>(), (color_fetcher, Arc::from(ranges)));
16966        self.scrollbar_marker_state.dirty = true;
16967        cx.notify();
16968    }
16969
16970    pub fn clear_background_highlights<T: 'static>(
16971        &mut self,
16972        cx: &mut Context<Self>,
16973    ) -> Option<BackgroundHighlight> {
16974        let text_highlights = self.background_highlights.remove(&TypeId::of::<T>())?;
16975        if !text_highlights.1.is_empty() {
16976            self.scrollbar_marker_state.dirty = true;
16977            cx.notify();
16978        }
16979        Some(text_highlights)
16980    }
16981
16982    pub fn highlight_gutter<T: 'static>(
16983        &mut self,
16984        ranges: &[Range<Anchor>],
16985        color_fetcher: fn(&App) -> Hsla,
16986        cx: &mut Context<Self>,
16987    ) {
16988        self.gutter_highlights
16989            .insert(TypeId::of::<T>(), (color_fetcher, Arc::from(ranges)));
16990        cx.notify();
16991    }
16992
16993    pub fn clear_gutter_highlights<T: 'static>(
16994        &mut self,
16995        cx: &mut Context<Self>,
16996    ) -> Option<GutterHighlight> {
16997        cx.notify();
16998        self.gutter_highlights.remove(&TypeId::of::<T>())
16999    }
17000
17001    #[cfg(feature = "test-support")]
17002    pub fn all_text_background_highlights(
17003        &self,
17004        window: &mut Window,
17005        cx: &mut Context<Self>,
17006    ) -> Vec<(Range<DisplayPoint>, Hsla)> {
17007        let snapshot = self.snapshot(window, cx);
17008        let buffer = &snapshot.buffer_snapshot;
17009        let start = buffer.anchor_before(0);
17010        let end = buffer.anchor_after(buffer.len());
17011        let theme = cx.theme().colors();
17012        self.background_highlights_in_range(start..end, &snapshot, theme)
17013    }
17014
17015    #[cfg(feature = "test-support")]
17016    pub fn search_background_highlights(&mut self, cx: &mut Context<Self>) -> Vec<Range<Point>> {
17017        let snapshot = self.buffer().read(cx).snapshot(cx);
17018
17019        let highlights = self
17020            .background_highlights
17021            .get(&TypeId::of::<items::BufferSearchHighlights>());
17022
17023        if let Some((_color, ranges)) = highlights {
17024            ranges
17025                .iter()
17026                .map(|range| range.start.to_point(&snapshot)..range.end.to_point(&snapshot))
17027                .collect_vec()
17028        } else {
17029            vec![]
17030        }
17031    }
17032
17033    fn document_highlights_for_position<'a>(
17034        &'a self,
17035        position: Anchor,
17036        buffer: &'a MultiBufferSnapshot,
17037    ) -> impl 'a + Iterator<Item = &'a Range<Anchor>> {
17038        let read_highlights = self
17039            .background_highlights
17040            .get(&TypeId::of::<DocumentHighlightRead>())
17041            .map(|h| &h.1);
17042        let write_highlights = self
17043            .background_highlights
17044            .get(&TypeId::of::<DocumentHighlightWrite>())
17045            .map(|h| &h.1);
17046        let left_position = position.bias_left(buffer);
17047        let right_position = position.bias_right(buffer);
17048        read_highlights
17049            .into_iter()
17050            .chain(write_highlights)
17051            .flat_map(move |ranges| {
17052                let start_ix = match ranges.binary_search_by(|probe| {
17053                    let cmp = probe.end.cmp(&left_position, buffer);
17054                    if cmp.is_ge() {
17055                        Ordering::Greater
17056                    } else {
17057                        Ordering::Less
17058                    }
17059                }) {
17060                    Ok(i) | Err(i) => i,
17061                };
17062
17063                ranges[start_ix..]
17064                    .iter()
17065                    .take_while(move |range| range.start.cmp(&right_position, buffer).is_le())
17066            })
17067    }
17068
17069    pub fn has_background_highlights<T: 'static>(&self) -> bool {
17070        self.background_highlights
17071            .get(&TypeId::of::<T>())
17072            .map_or(false, |(_, highlights)| !highlights.is_empty())
17073    }
17074
17075    pub fn background_highlights_in_range(
17076        &self,
17077        search_range: Range<Anchor>,
17078        display_snapshot: &DisplaySnapshot,
17079        theme: &ThemeColors,
17080    ) -> Vec<(Range<DisplayPoint>, Hsla)> {
17081        let mut results = Vec::new();
17082        for (color_fetcher, ranges) in self.background_highlights.values() {
17083            let color = color_fetcher(theme);
17084            let start_ix = match ranges.binary_search_by(|probe| {
17085                let cmp = probe
17086                    .end
17087                    .cmp(&search_range.start, &display_snapshot.buffer_snapshot);
17088                if cmp.is_gt() {
17089                    Ordering::Greater
17090                } else {
17091                    Ordering::Less
17092                }
17093            }) {
17094                Ok(i) | Err(i) => i,
17095            };
17096            for range in &ranges[start_ix..] {
17097                if range
17098                    .start
17099                    .cmp(&search_range.end, &display_snapshot.buffer_snapshot)
17100                    .is_ge()
17101                {
17102                    break;
17103                }
17104
17105                let start = range.start.to_display_point(display_snapshot);
17106                let end = range.end.to_display_point(display_snapshot);
17107                results.push((start..end, color))
17108            }
17109        }
17110        results
17111    }
17112
17113    pub fn background_highlight_row_ranges<T: 'static>(
17114        &self,
17115        search_range: Range<Anchor>,
17116        display_snapshot: &DisplaySnapshot,
17117        count: usize,
17118    ) -> Vec<RangeInclusive<DisplayPoint>> {
17119        let mut results = Vec::new();
17120        let Some((_, ranges)) = self.background_highlights.get(&TypeId::of::<T>()) else {
17121            return vec![];
17122        };
17123
17124        let start_ix = match ranges.binary_search_by(|probe| {
17125            let cmp = probe
17126                .end
17127                .cmp(&search_range.start, &display_snapshot.buffer_snapshot);
17128            if cmp.is_gt() {
17129                Ordering::Greater
17130            } else {
17131                Ordering::Less
17132            }
17133        }) {
17134            Ok(i) | Err(i) => i,
17135        };
17136        let mut push_region = |start: Option<Point>, end: Option<Point>| {
17137            if let (Some(start_display), Some(end_display)) = (start, end) {
17138                results.push(
17139                    start_display.to_display_point(display_snapshot)
17140                        ..=end_display.to_display_point(display_snapshot),
17141                );
17142            }
17143        };
17144        let mut start_row: Option<Point> = None;
17145        let mut end_row: Option<Point> = None;
17146        if ranges.len() > count {
17147            return Vec::new();
17148        }
17149        for range in &ranges[start_ix..] {
17150            if range
17151                .start
17152                .cmp(&search_range.end, &display_snapshot.buffer_snapshot)
17153                .is_ge()
17154            {
17155                break;
17156            }
17157            let end = range.end.to_point(&display_snapshot.buffer_snapshot);
17158            if let Some(current_row) = &end_row {
17159                if end.row == current_row.row {
17160                    continue;
17161                }
17162            }
17163            let start = range.start.to_point(&display_snapshot.buffer_snapshot);
17164            if start_row.is_none() {
17165                assert_eq!(end_row, None);
17166                start_row = Some(start);
17167                end_row = Some(end);
17168                continue;
17169            }
17170            if let Some(current_end) = end_row.as_mut() {
17171                if start.row > current_end.row + 1 {
17172                    push_region(start_row, end_row);
17173                    start_row = Some(start);
17174                    end_row = Some(end);
17175                } else {
17176                    // Merge two hunks.
17177                    *current_end = end;
17178                }
17179            } else {
17180                unreachable!();
17181            }
17182        }
17183        // We might still have a hunk that was not rendered (if there was a search hit on the last line)
17184        push_region(start_row, end_row);
17185        results
17186    }
17187
17188    pub fn gutter_highlights_in_range(
17189        &self,
17190        search_range: Range<Anchor>,
17191        display_snapshot: &DisplaySnapshot,
17192        cx: &App,
17193    ) -> Vec<(Range<DisplayPoint>, Hsla)> {
17194        let mut results = Vec::new();
17195        for (color_fetcher, ranges) in self.gutter_highlights.values() {
17196            let color = color_fetcher(cx);
17197            let start_ix = match ranges.binary_search_by(|probe| {
17198                let cmp = probe
17199                    .end
17200                    .cmp(&search_range.start, &display_snapshot.buffer_snapshot);
17201                if cmp.is_gt() {
17202                    Ordering::Greater
17203                } else {
17204                    Ordering::Less
17205                }
17206            }) {
17207                Ok(i) | Err(i) => i,
17208            };
17209            for range in &ranges[start_ix..] {
17210                if range
17211                    .start
17212                    .cmp(&search_range.end, &display_snapshot.buffer_snapshot)
17213                    .is_ge()
17214                {
17215                    break;
17216                }
17217
17218                let start = range.start.to_display_point(display_snapshot);
17219                let end = range.end.to_display_point(display_snapshot);
17220                results.push((start..end, color))
17221            }
17222        }
17223        results
17224    }
17225
17226    /// Get the text ranges corresponding to the redaction query
17227    pub fn redacted_ranges(
17228        &self,
17229        search_range: Range<Anchor>,
17230        display_snapshot: &DisplaySnapshot,
17231        cx: &App,
17232    ) -> Vec<Range<DisplayPoint>> {
17233        display_snapshot
17234            .buffer_snapshot
17235            .redacted_ranges(search_range, |file| {
17236                if let Some(file) = file {
17237                    file.is_private()
17238                        && EditorSettings::get(
17239                            Some(SettingsLocation {
17240                                worktree_id: file.worktree_id(cx),
17241                                path: file.path().as_ref(),
17242                            }),
17243                            cx,
17244                        )
17245                        .redact_private_values
17246                } else {
17247                    false
17248                }
17249            })
17250            .map(|range| {
17251                range.start.to_display_point(display_snapshot)
17252                    ..range.end.to_display_point(display_snapshot)
17253            })
17254            .collect()
17255    }
17256
17257    pub fn highlight_text<T: 'static>(
17258        &mut self,
17259        ranges: Vec<Range<Anchor>>,
17260        style: HighlightStyle,
17261        cx: &mut Context<Self>,
17262    ) {
17263        self.display_map.update(cx, |map, _| {
17264            map.highlight_text(TypeId::of::<T>(), ranges, style)
17265        });
17266        cx.notify();
17267    }
17268
17269    pub(crate) fn highlight_inlays<T: 'static>(
17270        &mut self,
17271        highlights: Vec<InlayHighlight>,
17272        style: HighlightStyle,
17273        cx: &mut Context<Self>,
17274    ) {
17275        self.display_map.update(cx, |map, _| {
17276            map.highlight_inlays(TypeId::of::<T>(), highlights, style)
17277        });
17278        cx.notify();
17279    }
17280
17281    pub fn text_highlights<'a, T: 'static>(
17282        &'a self,
17283        cx: &'a App,
17284    ) -> Option<(HighlightStyle, &'a [Range<Anchor>])> {
17285        self.display_map.read(cx).text_highlights(TypeId::of::<T>())
17286    }
17287
17288    pub fn clear_highlights<T: 'static>(&mut self, cx: &mut Context<Self>) {
17289        let cleared = self
17290            .display_map
17291            .update(cx, |map, _| map.clear_highlights(TypeId::of::<T>()));
17292        if cleared {
17293            cx.notify();
17294        }
17295    }
17296
17297    pub fn show_local_cursors(&self, window: &mut Window, cx: &mut App) -> bool {
17298        (self.read_only(cx) || self.blink_manager.read(cx).visible())
17299            && self.focus_handle.is_focused(window)
17300    }
17301
17302    pub fn set_show_cursor_when_unfocused(&mut self, is_enabled: bool, cx: &mut Context<Self>) {
17303        self.show_cursor_when_unfocused = is_enabled;
17304        cx.notify();
17305    }
17306
17307    fn on_buffer_changed(&mut self, _: Entity<MultiBuffer>, cx: &mut Context<Self>) {
17308        cx.notify();
17309    }
17310
17311    fn on_buffer_event(
17312        &mut self,
17313        multibuffer: &Entity<MultiBuffer>,
17314        event: &multi_buffer::Event,
17315        window: &mut Window,
17316        cx: &mut Context<Self>,
17317    ) {
17318        match event {
17319            multi_buffer::Event::Edited {
17320                singleton_buffer_edited,
17321                edited_buffer: buffer_edited,
17322            } => {
17323                self.scrollbar_marker_state.dirty = true;
17324                self.active_indent_guides_state.dirty = true;
17325                self.refresh_active_diagnostics(cx);
17326                self.refresh_code_actions(window, cx);
17327                if self.has_active_inline_completion() {
17328                    self.update_visible_inline_completion(window, cx);
17329                }
17330                if let Some(buffer) = buffer_edited {
17331                    let buffer_id = buffer.read(cx).remote_id();
17332                    if !self.registered_buffers.contains_key(&buffer_id) {
17333                        if let Some(project) = self.project.as_ref() {
17334                            project.update(cx, |project, cx| {
17335                                self.registered_buffers.insert(
17336                                    buffer_id,
17337                                    project.register_buffer_with_language_servers(&buffer, cx),
17338                                );
17339                            })
17340                        }
17341                    }
17342                }
17343                cx.emit(EditorEvent::BufferEdited);
17344                cx.emit(SearchEvent::MatchesInvalidated);
17345                if *singleton_buffer_edited {
17346                    if let Some(project) = &self.project {
17347                        #[allow(clippy::mutable_key_type)]
17348                        let languages_affected = multibuffer.update(cx, |multibuffer, cx| {
17349                            multibuffer
17350                                .all_buffers()
17351                                .into_iter()
17352                                .filter_map(|buffer| {
17353                                    buffer.update(cx, |buffer, cx| {
17354                                        let language = buffer.language()?;
17355                                        let should_discard = project.update(cx, |project, cx| {
17356                                            project.is_local()
17357                                                && !project.has_language_servers_for(buffer, cx)
17358                                        });
17359                                        should_discard.not().then_some(language.clone())
17360                                    })
17361                                })
17362                                .collect::<HashSet<_>>()
17363                        });
17364                        if !languages_affected.is_empty() {
17365                            self.refresh_inlay_hints(
17366                                InlayHintRefreshReason::BufferEdited(languages_affected),
17367                                cx,
17368                            );
17369                        }
17370                    }
17371                }
17372
17373                let Some(project) = &self.project else { return };
17374                let (telemetry, is_via_ssh) = {
17375                    let project = project.read(cx);
17376                    let telemetry = project.client().telemetry().clone();
17377                    let is_via_ssh = project.is_via_ssh();
17378                    (telemetry, is_via_ssh)
17379                };
17380                refresh_linked_ranges(self, window, cx);
17381                telemetry.log_edit_event("editor", is_via_ssh);
17382            }
17383            multi_buffer::Event::ExcerptsAdded {
17384                buffer,
17385                predecessor,
17386                excerpts,
17387            } => {
17388                self.tasks_update_task = Some(self.refresh_runnables(window, cx));
17389                let buffer_id = buffer.read(cx).remote_id();
17390                if self.buffer.read(cx).diff_for(buffer_id).is_none() {
17391                    if let Some(project) = &self.project {
17392                        get_uncommitted_diff_for_buffer(
17393                            project,
17394                            [buffer.clone()],
17395                            self.buffer.clone(),
17396                            cx,
17397                        )
17398                        .detach();
17399                    }
17400                }
17401                cx.emit(EditorEvent::ExcerptsAdded {
17402                    buffer: buffer.clone(),
17403                    predecessor: *predecessor,
17404                    excerpts: excerpts.clone(),
17405                });
17406                self.refresh_inlay_hints(InlayHintRefreshReason::NewLinesShown, cx);
17407            }
17408            multi_buffer::Event::ExcerptsRemoved { ids } => {
17409                self.refresh_inlay_hints(InlayHintRefreshReason::ExcerptsRemoved(ids.clone()), cx);
17410                let buffer = self.buffer.read(cx);
17411                self.registered_buffers
17412                    .retain(|buffer_id, _| buffer.buffer(*buffer_id).is_some());
17413                jsx_tag_auto_close::refresh_enabled_in_any_buffer(self, multibuffer, cx);
17414                cx.emit(EditorEvent::ExcerptsRemoved { ids: ids.clone() })
17415            }
17416            multi_buffer::Event::ExcerptsEdited {
17417                excerpt_ids,
17418                buffer_ids,
17419            } => {
17420                self.display_map.update(cx, |map, cx| {
17421                    map.unfold_buffers(buffer_ids.iter().copied(), cx)
17422                });
17423                cx.emit(EditorEvent::ExcerptsEdited {
17424                    ids: excerpt_ids.clone(),
17425                })
17426            }
17427            multi_buffer::Event::ExcerptsExpanded { ids } => {
17428                self.refresh_inlay_hints(InlayHintRefreshReason::NewLinesShown, cx);
17429                cx.emit(EditorEvent::ExcerptsExpanded { ids: ids.clone() })
17430            }
17431            multi_buffer::Event::Reparsed(buffer_id) => {
17432                self.tasks_update_task = Some(self.refresh_runnables(window, cx));
17433                jsx_tag_auto_close::refresh_enabled_in_any_buffer(self, multibuffer, cx);
17434
17435                cx.emit(EditorEvent::Reparsed(*buffer_id));
17436            }
17437            multi_buffer::Event::DiffHunksToggled => {
17438                self.tasks_update_task = Some(self.refresh_runnables(window, cx));
17439            }
17440            multi_buffer::Event::LanguageChanged(buffer_id) => {
17441                linked_editing_ranges::refresh_linked_ranges(self, window, cx);
17442                jsx_tag_auto_close::refresh_enabled_in_any_buffer(self, multibuffer, cx);
17443                cx.emit(EditorEvent::Reparsed(*buffer_id));
17444                cx.notify();
17445            }
17446            multi_buffer::Event::DirtyChanged => cx.emit(EditorEvent::DirtyChanged),
17447            multi_buffer::Event::Saved => cx.emit(EditorEvent::Saved),
17448            multi_buffer::Event::FileHandleChanged
17449            | multi_buffer::Event::Reloaded
17450            | multi_buffer::Event::BufferDiffChanged => cx.emit(EditorEvent::TitleChanged),
17451            multi_buffer::Event::Closed => cx.emit(EditorEvent::Closed),
17452            multi_buffer::Event::DiagnosticsUpdated => {
17453                self.refresh_active_diagnostics(cx);
17454                self.refresh_inline_diagnostics(true, window, cx);
17455                self.scrollbar_marker_state.dirty = true;
17456                cx.notify();
17457            }
17458            _ => {}
17459        };
17460    }
17461
17462    fn on_display_map_changed(
17463        &mut self,
17464        _: Entity<DisplayMap>,
17465        _: &mut Window,
17466        cx: &mut Context<Self>,
17467    ) {
17468        cx.notify();
17469    }
17470
17471    fn settings_changed(&mut self, window: &mut Window, cx: &mut Context<Self>) {
17472        self.tasks_update_task = Some(self.refresh_runnables(window, cx));
17473        self.update_edit_prediction_settings(cx);
17474        self.refresh_inline_completion(true, false, window, cx);
17475        self.refresh_inlay_hints(
17476            InlayHintRefreshReason::SettingsChange(inlay_hint_settings(
17477                self.selections.newest_anchor().head(),
17478                &self.buffer.read(cx).snapshot(cx),
17479                cx,
17480            )),
17481            cx,
17482        );
17483
17484        let old_cursor_shape = self.cursor_shape;
17485
17486        {
17487            let editor_settings = EditorSettings::get_global(cx);
17488            self.scroll_manager.vertical_scroll_margin = editor_settings.vertical_scroll_margin;
17489            self.show_breadcrumbs = editor_settings.toolbar.breadcrumbs;
17490            self.cursor_shape = editor_settings.cursor_shape.unwrap_or_default();
17491            self.hide_mouse_mode = editor_settings.hide_mouse.unwrap_or_default();
17492        }
17493
17494        if old_cursor_shape != self.cursor_shape {
17495            cx.emit(EditorEvent::CursorShapeChanged);
17496        }
17497
17498        let project_settings = ProjectSettings::get_global(cx);
17499        self.serialize_dirty_buffers = project_settings.session.restore_unsaved_buffers;
17500
17501        if self.mode.is_full() {
17502            let show_inline_diagnostics = project_settings.diagnostics.inline.enabled;
17503            let inline_blame_enabled = project_settings.git.inline_blame_enabled();
17504            if self.show_inline_diagnostics != show_inline_diagnostics {
17505                self.show_inline_diagnostics = show_inline_diagnostics;
17506                self.refresh_inline_diagnostics(false, window, cx);
17507            }
17508
17509            if self.git_blame_inline_enabled != inline_blame_enabled {
17510                self.toggle_git_blame_inline_internal(false, window, cx);
17511            }
17512        }
17513
17514        cx.notify();
17515    }
17516
17517    pub fn set_searchable(&mut self, searchable: bool) {
17518        self.searchable = searchable;
17519    }
17520
17521    pub fn searchable(&self) -> bool {
17522        self.searchable
17523    }
17524
17525    fn open_proposed_changes_editor(
17526        &mut self,
17527        _: &OpenProposedChangesEditor,
17528        window: &mut Window,
17529        cx: &mut Context<Self>,
17530    ) {
17531        let Some(workspace) = self.workspace() else {
17532            cx.propagate();
17533            return;
17534        };
17535
17536        let selections = self.selections.all::<usize>(cx);
17537        let multi_buffer = self.buffer.read(cx);
17538        let multi_buffer_snapshot = multi_buffer.snapshot(cx);
17539        let mut new_selections_by_buffer = HashMap::default();
17540        for selection in selections {
17541            for (buffer, range, _) in
17542                multi_buffer_snapshot.range_to_buffer_ranges(selection.start..selection.end)
17543            {
17544                let mut range = range.to_point(buffer);
17545                range.start.column = 0;
17546                range.end.column = buffer.line_len(range.end.row);
17547                new_selections_by_buffer
17548                    .entry(multi_buffer.buffer(buffer.remote_id()).unwrap())
17549                    .or_insert(Vec::new())
17550                    .push(range)
17551            }
17552        }
17553
17554        let proposed_changes_buffers = new_selections_by_buffer
17555            .into_iter()
17556            .map(|(buffer, ranges)| ProposedChangeLocation { buffer, ranges })
17557            .collect::<Vec<_>>();
17558        let proposed_changes_editor = cx.new(|cx| {
17559            ProposedChangesEditor::new(
17560                "Proposed changes",
17561                proposed_changes_buffers,
17562                self.project.clone(),
17563                window,
17564                cx,
17565            )
17566        });
17567
17568        window.defer(cx, move |window, cx| {
17569            workspace.update(cx, |workspace, cx| {
17570                workspace.active_pane().update(cx, |pane, cx| {
17571                    pane.add_item(
17572                        Box::new(proposed_changes_editor),
17573                        true,
17574                        true,
17575                        None,
17576                        window,
17577                        cx,
17578                    );
17579                });
17580            });
17581        });
17582    }
17583
17584    pub fn open_excerpts_in_split(
17585        &mut self,
17586        _: &OpenExcerptsSplit,
17587        window: &mut Window,
17588        cx: &mut Context<Self>,
17589    ) {
17590        self.open_excerpts_common(None, true, window, cx)
17591    }
17592
17593    pub fn open_excerpts(&mut self, _: &OpenExcerpts, window: &mut Window, cx: &mut Context<Self>) {
17594        self.open_excerpts_common(None, false, window, cx)
17595    }
17596
17597    fn open_excerpts_common(
17598        &mut self,
17599        jump_data: Option<JumpData>,
17600        split: bool,
17601        window: &mut Window,
17602        cx: &mut Context<Self>,
17603    ) {
17604        let Some(workspace) = self.workspace() else {
17605            cx.propagate();
17606            return;
17607        };
17608
17609        if self.buffer.read(cx).is_singleton() {
17610            cx.propagate();
17611            return;
17612        }
17613
17614        let mut new_selections_by_buffer = HashMap::default();
17615        match &jump_data {
17616            Some(JumpData::MultiBufferPoint {
17617                excerpt_id,
17618                position,
17619                anchor,
17620                line_offset_from_top,
17621            }) => {
17622                let multi_buffer_snapshot = self.buffer.read(cx).snapshot(cx);
17623                if let Some(buffer) = multi_buffer_snapshot
17624                    .buffer_id_for_excerpt(*excerpt_id)
17625                    .and_then(|buffer_id| self.buffer.read(cx).buffer(buffer_id))
17626                {
17627                    let buffer_snapshot = buffer.read(cx).snapshot();
17628                    let jump_to_point = if buffer_snapshot.can_resolve(anchor) {
17629                        language::ToPoint::to_point(anchor, &buffer_snapshot)
17630                    } else {
17631                        buffer_snapshot.clip_point(*position, Bias::Left)
17632                    };
17633                    let jump_to_offset = buffer_snapshot.point_to_offset(jump_to_point);
17634                    new_selections_by_buffer.insert(
17635                        buffer,
17636                        (
17637                            vec![jump_to_offset..jump_to_offset],
17638                            Some(*line_offset_from_top),
17639                        ),
17640                    );
17641                }
17642            }
17643            Some(JumpData::MultiBufferRow {
17644                row,
17645                line_offset_from_top,
17646            }) => {
17647                let point = MultiBufferPoint::new(row.0, 0);
17648                if let Some((buffer, buffer_point, _)) =
17649                    self.buffer.read(cx).point_to_buffer_point(point, cx)
17650                {
17651                    let buffer_offset = buffer.read(cx).point_to_offset(buffer_point);
17652                    new_selections_by_buffer
17653                        .entry(buffer)
17654                        .or_insert((Vec::new(), Some(*line_offset_from_top)))
17655                        .0
17656                        .push(buffer_offset..buffer_offset)
17657                }
17658            }
17659            None => {
17660                let selections = self.selections.all::<usize>(cx);
17661                let multi_buffer = self.buffer.read(cx);
17662                for selection in selections {
17663                    for (snapshot, range, _, anchor) in multi_buffer
17664                        .snapshot(cx)
17665                        .range_to_buffer_ranges_with_deleted_hunks(selection.range())
17666                    {
17667                        if let Some(anchor) = anchor {
17668                            // selection is in a deleted hunk
17669                            let Some(buffer_id) = anchor.buffer_id else {
17670                                continue;
17671                            };
17672                            let Some(buffer_handle) = multi_buffer.buffer(buffer_id) else {
17673                                continue;
17674                            };
17675                            let offset = text::ToOffset::to_offset(
17676                                &anchor.text_anchor,
17677                                &buffer_handle.read(cx).snapshot(),
17678                            );
17679                            let range = offset..offset;
17680                            new_selections_by_buffer
17681                                .entry(buffer_handle)
17682                                .or_insert((Vec::new(), None))
17683                                .0
17684                                .push(range)
17685                        } else {
17686                            let Some(buffer_handle) = multi_buffer.buffer(snapshot.remote_id())
17687                            else {
17688                                continue;
17689                            };
17690                            new_selections_by_buffer
17691                                .entry(buffer_handle)
17692                                .or_insert((Vec::new(), None))
17693                                .0
17694                                .push(range)
17695                        }
17696                    }
17697                }
17698            }
17699        }
17700
17701        new_selections_by_buffer
17702            .retain(|buffer, _| Self::can_open_excerpts_in_file(buffer.read(cx).file()));
17703
17704        if new_selections_by_buffer.is_empty() {
17705            return;
17706        }
17707
17708        // We defer the pane interaction because we ourselves are a workspace item
17709        // and activating a new item causes the pane to call a method on us reentrantly,
17710        // which panics if we're on the stack.
17711        window.defer(cx, move |window, cx| {
17712            workspace.update(cx, |workspace, cx| {
17713                let pane = if split {
17714                    workspace.adjacent_pane(window, cx)
17715                } else {
17716                    workspace.active_pane().clone()
17717                };
17718
17719                for (buffer, (ranges, scroll_offset)) in new_selections_by_buffer {
17720                    let editor = buffer
17721                        .read(cx)
17722                        .file()
17723                        .is_none()
17724                        .then(|| {
17725                            // Handle file-less buffers separately: those are not really the project items, so won't have a project path or entity id,
17726                            // so `workspace.open_project_item` will never find them, always opening a new editor.
17727                            // Instead, we try to activate the existing editor in the pane first.
17728                            let (editor, pane_item_index) =
17729                                pane.read(cx).items().enumerate().find_map(|(i, item)| {
17730                                    let editor = item.downcast::<Editor>()?;
17731                                    let singleton_buffer =
17732                                        editor.read(cx).buffer().read(cx).as_singleton()?;
17733                                    if singleton_buffer == buffer {
17734                                        Some((editor, i))
17735                                    } else {
17736                                        None
17737                                    }
17738                                })?;
17739                            pane.update(cx, |pane, cx| {
17740                                pane.activate_item(pane_item_index, true, true, window, cx)
17741                            });
17742                            Some(editor)
17743                        })
17744                        .flatten()
17745                        .unwrap_or_else(|| {
17746                            workspace.open_project_item::<Self>(
17747                                pane.clone(),
17748                                buffer,
17749                                true,
17750                                true,
17751                                window,
17752                                cx,
17753                            )
17754                        });
17755
17756                    editor.update(cx, |editor, cx| {
17757                        let autoscroll = match scroll_offset {
17758                            Some(scroll_offset) => Autoscroll::top_relative(scroll_offset as usize),
17759                            None => Autoscroll::newest(),
17760                        };
17761                        let nav_history = editor.nav_history.take();
17762                        editor.change_selections(Some(autoscroll), window, cx, |s| {
17763                            s.select_ranges(ranges);
17764                        });
17765                        editor.nav_history = nav_history;
17766                    });
17767                }
17768            })
17769        });
17770    }
17771
17772    // For now, don't allow opening excerpts in buffers that aren't backed by
17773    // regular project files.
17774    fn can_open_excerpts_in_file(file: Option<&Arc<dyn language::File>>) -> bool {
17775        file.map_or(true, |file| project::File::from_dyn(Some(file)).is_some())
17776    }
17777
17778    fn marked_text_ranges(&self, cx: &App) -> Option<Vec<Range<OffsetUtf16>>> {
17779        let snapshot = self.buffer.read(cx).read(cx);
17780        let (_, ranges) = self.text_highlights::<InputComposition>(cx)?;
17781        Some(
17782            ranges
17783                .iter()
17784                .map(move |range| {
17785                    range.start.to_offset_utf16(&snapshot)..range.end.to_offset_utf16(&snapshot)
17786                })
17787                .collect(),
17788        )
17789    }
17790
17791    fn selection_replacement_ranges(
17792        &self,
17793        range: Range<OffsetUtf16>,
17794        cx: &mut App,
17795    ) -> Vec<Range<OffsetUtf16>> {
17796        let selections = self.selections.all::<OffsetUtf16>(cx);
17797        let newest_selection = selections
17798            .iter()
17799            .max_by_key(|selection| selection.id)
17800            .unwrap();
17801        let start_delta = range.start.0 as isize - newest_selection.start.0 as isize;
17802        let end_delta = range.end.0 as isize - newest_selection.end.0 as isize;
17803        let snapshot = self.buffer.read(cx).read(cx);
17804        selections
17805            .into_iter()
17806            .map(|mut selection| {
17807                selection.start.0 =
17808                    (selection.start.0 as isize).saturating_add(start_delta) as usize;
17809                selection.end.0 = (selection.end.0 as isize).saturating_add(end_delta) as usize;
17810                snapshot.clip_offset_utf16(selection.start, Bias::Left)
17811                    ..snapshot.clip_offset_utf16(selection.end, Bias::Right)
17812            })
17813            .collect()
17814    }
17815
17816    fn report_editor_event(
17817        &self,
17818        event_type: &'static str,
17819        file_extension: Option<String>,
17820        cx: &App,
17821    ) {
17822        if cfg!(any(test, feature = "test-support")) {
17823            return;
17824        }
17825
17826        let Some(project) = &self.project else { return };
17827
17828        // If None, we are in a file without an extension
17829        let file = self
17830            .buffer
17831            .read(cx)
17832            .as_singleton()
17833            .and_then(|b| b.read(cx).file());
17834        let file_extension = file_extension.or(file
17835            .as_ref()
17836            .and_then(|file| Path::new(file.file_name(cx)).extension())
17837            .and_then(|e| e.to_str())
17838            .map(|a| a.to_string()));
17839
17840        let vim_mode = vim_enabled(cx);
17841
17842        let edit_predictions_provider = all_language_settings(file, cx).edit_predictions.provider;
17843        let copilot_enabled = edit_predictions_provider
17844            == language::language_settings::EditPredictionProvider::Copilot;
17845        let copilot_enabled_for_language = self
17846            .buffer
17847            .read(cx)
17848            .language_settings(cx)
17849            .show_edit_predictions;
17850
17851        let project = project.read(cx);
17852        telemetry::event!(
17853            event_type,
17854            file_extension,
17855            vim_mode,
17856            copilot_enabled,
17857            copilot_enabled_for_language,
17858            edit_predictions_provider,
17859            is_via_ssh = project.is_via_ssh(),
17860        );
17861    }
17862
17863    /// Copy the highlighted chunks to the clipboard as JSON. The format is an array of lines,
17864    /// with each line being an array of {text, highlight} objects.
17865    fn copy_highlight_json(
17866        &mut self,
17867        _: &CopyHighlightJson,
17868        window: &mut Window,
17869        cx: &mut Context<Self>,
17870    ) {
17871        #[derive(Serialize)]
17872        struct Chunk<'a> {
17873            text: String,
17874            highlight: Option<&'a str>,
17875        }
17876
17877        let snapshot = self.buffer.read(cx).snapshot(cx);
17878        let range = self
17879            .selected_text_range(false, window, cx)
17880            .and_then(|selection| {
17881                if selection.range.is_empty() {
17882                    None
17883                } else {
17884                    Some(selection.range)
17885                }
17886            })
17887            .unwrap_or_else(|| 0..snapshot.len());
17888
17889        let chunks = snapshot.chunks(range, true);
17890        let mut lines = Vec::new();
17891        let mut line: VecDeque<Chunk> = VecDeque::new();
17892
17893        let Some(style) = self.style.as_ref() else {
17894            return;
17895        };
17896
17897        for chunk in chunks {
17898            let highlight = chunk
17899                .syntax_highlight_id
17900                .and_then(|id| id.name(&style.syntax));
17901            let mut chunk_lines = chunk.text.split('\n').peekable();
17902            while let Some(text) = chunk_lines.next() {
17903                let mut merged_with_last_token = false;
17904                if let Some(last_token) = line.back_mut() {
17905                    if last_token.highlight == highlight {
17906                        last_token.text.push_str(text);
17907                        merged_with_last_token = true;
17908                    }
17909                }
17910
17911                if !merged_with_last_token {
17912                    line.push_back(Chunk {
17913                        text: text.into(),
17914                        highlight,
17915                    });
17916                }
17917
17918                if chunk_lines.peek().is_some() {
17919                    if line.len() > 1 && line.front().unwrap().text.is_empty() {
17920                        line.pop_front();
17921                    }
17922                    if line.len() > 1 && line.back().unwrap().text.is_empty() {
17923                        line.pop_back();
17924                    }
17925
17926                    lines.push(mem::take(&mut line));
17927                }
17928            }
17929        }
17930
17931        let Some(lines) = serde_json::to_string_pretty(&lines).log_err() else {
17932            return;
17933        };
17934        cx.write_to_clipboard(ClipboardItem::new_string(lines));
17935    }
17936
17937    pub fn open_context_menu(
17938        &mut self,
17939        _: &OpenContextMenu,
17940        window: &mut Window,
17941        cx: &mut Context<Self>,
17942    ) {
17943        self.request_autoscroll(Autoscroll::newest(), cx);
17944        let position = self.selections.newest_display(cx).start;
17945        mouse_context_menu::deploy_context_menu(self, None, position, window, cx);
17946    }
17947
17948    pub fn inlay_hint_cache(&self) -> &InlayHintCache {
17949        &self.inlay_hint_cache
17950    }
17951
17952    pub fn replay_insert_event(
17953        &mut self,
17954        text: &str,
17955        relative_utf16_range: Option<Range<isize>>,
17956        window: &mut Window,
17957        cx: &mut Context<Self>,
17958    ) {
17959        if !self.input_enabled {
17960            cx.emit(EditorEvent::InputIgnored { text: text.into() });
17961            return;
17962        }
17963        if let Some(relative_utf16_range) = relative_utf16_range {
17964            let selections = self.selections.all::<OffsetUtf16>(cx);
17965            self.change_selections(None, window, cx, |s| {
17966                let new_ranges = selections.into_iter().map(|range| {
17967                    let start = OffsetUtf16(
17968                        range
17969                            .head()
17970                            .0
17971                            .saturating_add_signed(relative_utf16_range.start),
17972                    );
17973                    let end = OffsetUtf16(
17974                        range
17975                            .head()
17976                            .0
17977                            .saturating_add_signed(relative_utf16_range.end),
17978                    );
17979                    start..end
17980                });
17981                s.select_ranges(new_ranges);
17982            });
17983        }
17984
17985        self.handle_input(text, window, cx);
17986    }
17987
17988    pub fn supports_inlay_hints(&self, cx: &mut App) -> bool {
17989        let Some(provider) = self.semantics_provider.as_ref() else {
17990            return false;
17991        };
17992
17993        let mut supports = false;
17994        self.buffer().update(cx, |this, cx| {
17995            this.for_each_buffer(|buffer| {
17996                supports |= provider.supports_inlay_hints(buffer, cx);
17997            });
17998        });
17999
18000        supports
18001    }
18002
18003    pub fn is_focused(&self, window: &Window) -> bool {
18004        self.focus_handle.is_focused(window)
18005    }
18006
18007    fn handle_focus(&mut self, window: &mut Window, cx: &mut Context<Self>) {
18008        cx.emit(EditorEvent::Focused);
18009
18010        if let Some(descendant) = self
18011            .last_focused_descendant
18012            .take()
18013            .and_then(|descendant| descendant.upgrade())
18014        {
18015            window.focus(&descendant);
18016        } else {
18017            if let Some(blame) = self.blame.as_ref() {
18018                blame.update(cx, GitBlame::focus)
18019            }
18020
18021            self.blink_manager.update(cx, BlinkManager::enable);
18022            self.show_cursor_names(window, cx);
18023            self.buffer.update(cx, |buffer, cx| {
18024                buffer.finalize_last_transaction(cx);
18025                if self.leader_peer_id.is_none() {
18026                    buffer.set_active_selections(
18027                        &self.selections.disjoint_anchors(),
18028                        self.selections.line_mode,
18029                        self.cursor_shape,
18030                        cx,
18031                    );
18032                }
18033            });
18034        }
18035    }
18036
18037    fn handle_focus_in(&mut self, _: &mut Window, cx: &mut Context<Self>) {
18038        cx.emit(EditorEvent::FocusedIn)
18039    }
18040
18041    fn handle_focus_out(
18042        &mut self,
18043        event: FocusOutEvent,
18044        _window: &mut Window,
18045        cx: &mut Context<Self>,
18046    ) {
18047        if event.blurred != self.focus_handle {
18048            self.last_focused_descendant = Some(event.blurred);
18049        }
18050        self.refresh_inlay_hints(InlayHintRefreshReason::ModifiersChanged(false), cx);
18051    }
18052
18053    pub fn handle_blur(&mut self, window: &mut Window, cx: &mut Context<Self>) {
18054        self.blink_manager.update(cx, BlinkManager::disable);
18055        self.buffer
18056            .update(cx, |buffer, cx| buffer.remove_active_selections(cx));
18057
18058        if let Some(blame) = self.blame.as_ref() {
18059            blame.update(cx, GitBlame::blur)
18060        }
18061        if !self.hover_state.focused(window, cx) {
18062            hide_hover(self, cx);
18063        }
18064        if !self
18065            .context_menu
18066            .borrow()
18067            .as_ref()
18068            .is_some_and(|context_menu| context_menu.focused(window, cx))
18069        {
18070            self.hide_context_menu(window, cx);
18071        }
18072        self.discard_inline_completion(false, cx);
18073        cx.emit(EditorEvent::Blurred);
18074        cx.notify();
18075    }
18076
18077    pub fn register_action<A: Action>(
18078        &mut self,
18079        listener: impl Fn(&A, &mut Window, &mut App) + 'static,
18080    ) -> Subscription {
18081        let id = self.next_editor_action_id.post_inc();
18082        let listener = Arc::new(listener);
18083        self.editor_actions.borrow_mut().insert(
18084            id,
18085            Box::new(move |window, _| {
18086                let listener = listener.clone();
18087                window.on_action(TypeId::of::<A>(), move |action, phase, window, cx| {
18088                    let action = action.downcast_ref().unwrap();
18089                    if phase == DispatchPhase::Bubble {
18090                        listener(action, window, cx)
18091                    }
18092                })
18093            }),
18094        );
18095
18096        let editor_actions = self.editor_actions.clone();
18097        Subscription::new(move || {
18098            editor_actions.borrow_mut().remove(&id);
18099        })
18100    }
18101
18102    pub fn file_header_size(&self) -> u32 {
18103        FILE_HEADER_HEIGHT
18104    }
18105
18106    pub fn restore(
18107        &mut self,
18108        revert_changes: HashMap<BufferId, Vec<(Range<text::Anchor>, Rope)>>,
18109        window: &mut Window,
18110        cx: &mut Context<Self>,
18111    ) {
18112        let workspace = self.workspace();
18113        let project = self.project.as_ref();
18114        let save_tasks = self.buffer().update(cx, |multi_buffer, cx| {
18115            let mut tasks = Vec::new();
18116            for (buffer_id, changes) in revert_changes {
18117                if let Some(buffer) = multi_buffer.buffer(buffer_id) {
18118                    buffer.update(cx, |buffer, cx| {
18119                        buffer.edit(
18120                            changes
18121                                .into_iter()
18122                                .map(|(range, text)| (range, text.to_string())),
18123                            None,
18124                            cx,
18125                        );
18126                    });
18127
18128                    if let Some(project) =
18129                        project.filter(|_| multi_buffer.all_diff_hunks_expanded())
18130                    {
18131                        project.update(cx, |project, cx| {
18132                            tasks.push((buffer.clone(), project.save_buffer(buffer, cx)));
18133                        })
18134                    }
18135                }
18136            }
18137            tasks
18138        });
18139        cx.spawn_in(window, async move |_, cx| {
18140            for (buffer, task) in save_tasks {
18141                let result = task.await;
18142                if result.is_err() {
18143                    let Some(path) = buffer
18144                        .read_with(cx, |buffer, cx| buffer.project_path(cx))
18145                        .ok()
18146                    else {
18147                        continue;
18148                    };
18149                    if let Some((workspace, path)) = workspace.as_ref().zip(path) {
18150                        let Some(task) = cx
18151                            .update_window_entity(&workspace, |workspace, window, cx| {
18152                                workspace
18153                                    .open_path_preview(path, None, false, false, false, window, cx)
18154                            })
18155                            .ok()
18156                        else {
18157                            continue;
18158                        };
18159                        task.await.log_err();
18160                    }
18161                }
18162            }
18163        })
18164        .detach();
18165        self.change_selections(None, window, cx, |selections| selections.refresh());
18166    }
18167
18168    pub fn to_pixel_point(
18169        &self,
18170        source: multi_buffer::Anchor,
18171        editor_snapshot: &EditorSnapshot,
18172        window: &mut Window,
18173    ) -> Option<gpui::Point<Pixels>> {
18174        let source_point = source.to_display_point(editor_snapshot);
18175        self.display_to_pixel_point(source_point, editor_snapshot, window)
18176    }
18177
18178    pub fn display_to_pixel_point(
18179        &self,
18180        source: DisplayPoint,
18181        editor_snapshot: &EditorSnapshot,
18182        window: &mut Window,
18183    ) -> Option<gpui::Point<Pixels>> {
18184        let line_height = self.style()?.text.line_height_in_pixels(window.rem_size());
18185        let text_layout_details = self.text_layout_details(window);
18186        let scroll_top = text_layout_details
18187            .scroll_anchor
18188            .scroll_position(editor_snapshot)
18189            .y;
18190
18191        if source.row().as_f32() < scroll_top.floor() {
18192            return None;
18193        }
18194        let source_x = editor_snapshot.x_for_display_point(source, &text_layout_details);
18195        let source_y = line_height * (source.row().as_f32() - scroll_top);
18196        Some(gpui::Point::new(source_x, source_y))
18197    }
18198
18199    pub fn has_visible_completions_menu(&self) -> bool {
18200        !self.edit_prediction_preview_is_active()
18201            && self.context_menu.borrow().as_ref().map_or(false, |menu| {
18202                menu.visible() && matches!(menu, CodeContextMenu::Completions(_))
18203            })
18204    }
18205
18206    pub fn register_addon<T: Addon>(&mut self, instance: T) {
18207        self.addons
18208            .insert(std::any::TypeId::of::<T>(), Box::new(instance));
18209    }
18210
18211    pub fn unregister_addon<T: Addon>(&mut self) {
18212        self.addons.remove(&std::any::TypeId::of::<T>());
18213    }
18214
18215    pub fn addon<T: Addon>(&self) -> Option<&T> {
18216        let type_id = std::any::TypeId::of::<T>();
18217        self.addons
18218            .get(&type_id)
18219            .and_then(|item| item.to_any().downcast_ref::<T>())
18220    }
18221
18222    fn character_size(&self, window: &mut Window) -> gpui::Size<Pixels> {
18223        let text_layout_details = self.text_layout_details(window);
18224        let style = &text_layout_details.editor_style;
18225        let font_id = window.text_system().resolve_font(&style.text.font());
18226        let font_size = style.text.font_size.to_pixels(window.rem_size());
18227        let line_height = style.text.line_height_in_pixels(window.rem_size());
18228        let em_width = window.text_system().em_width(font_id, font_size).unwrap();
18229
18230        gpui::Size::new(em_width, line_height)
18231    }
18232
18233    pub fn wait_for_diff_to_load(&self) -> Option<Shared<Task<()>>> {
18234        self.load_diff_task.clone()
18235    }
18236
18237    fn read_metadata_from_db(
18238        &mut self,
18239        item_id: u64,
18240        workspace_id: WorkspaceId,
18241        window: &mut Window,
18242        cx: &mut Context<Editor>,
18243    ) {
18244        if self.is_singleton(cx)
18245            && WorkspaceSettings::get(None, cx).restore_on_startup != RestoreOnStartupBehavior::None
18246        {
18247            let buffer_snapshot = OnceCell::new();
18248
18249            if let Some(folds) = DB.get_editor_folds(item_id, workspace_id).log_err() {
18250                if !folds.is_empty() {
18251                    let snapshot =
18252                        buffer_snapshot.get_or_init(|| self.buffer.read(cx).snapshot(cx));
18253                    self.fold_ranges(
18254                        folds
18255                            .into_iter()
18256                            .map(|(start, end)| {
18257                                snapshot.clip_offset(start, Bias::Left)
18258                                    ..snapshot.clip_offset(end, Bias::Right)
18259                            })
18260                            .collect(),
18261                        false,
18262                        window,
18263                        cx,
18264                    );
18265                }
18266            }
18267
18268            if let Some(selections) = DB.get_editor_selections(item_id, workspace_id).log_err() {
18269                if !selections.is_empty() {
18270                    let snapshot =
18271                        buffer_snapshot.get_or_init(|| self.buffer.read(cx).snapshot(cx));
18272                    self.change_selections(None, window, cx, |s| {
18273                        s.select_ranges(selections.into_iter().map(|(start, end)| {
18274                            snapshot.clip_offset(start, Bias::Left)
18275                                ..snapshot.clip_offset(end, Bias::Right)
18276                        }));
18277                    });
18278                }
18279            };
18280        }
18281
18282        self.read_scroll_position_from_db(item_id, workspace_id, window, cx);
18283    }
18284}
18285
18286fn vim_enabled(cx: &App) -> bool {
18287    cx.global::<SettingsStore>()
18288        .raw_user_settings()
18289        .get("vim_mode")
18290        == Some(&serde_json::Value::Bool(true))
18291}
18292
18293// Consider user intent and default settings
18294fn choose_completion_range(
18295    completion: &Completion,
18296    intent: CompletionIntent,
18297    buffer: &Entity<Buffer>,
18298    cx: &mut Context<Editor>,
18299) -> Range<usize> {
18300    fn should_replace(
18301        completion: &Completion,
18302        insert_range: &Range<text::Anchor>,
18303        intent: CompletionIntent,
18304        completion_mode_setting: LspInsertMode,
18305        buffer: &Buffer,
18306    ) -> bool {
18307        // specific actions take precedence over settings
18308        match intent {
18309            CompletionIntent::CompleteWithInsert => return false,
18310            CompletionIntent::CompleteWithReplace => return true,
18311            CompletionIntent::Complete | CompletionIntent::Compose => {}
18312        }
18313
18314        match completion_mode_setting {
18315            LspInsertMode::Insert => false,
18316            LspInsertMode::Replace => true,
18317            LspInsertMode::ReplaceSubsequence => {
18318                let mut text_to_replace = buffer.chars_for_range(
18319                    buffer.anchor_before(completion.replace_range.start)
18320                        ..buffer.anchor_after(completion.replace_range.end),
18321                );
18322                let mut completion_text = completion.new_text.chars();
18323
18324                // is `text_to_replace` a subsequence of `completion_text`
18325                text_to_replace
18326                    .all(|needle_ch| completion_text.any(|haystack_ch| haystack_ch == needle_ch))
18327            }
18328            LspInsertMode::ReplaceSuffix => {
18329                let range_after_cursor = insert_range.end..completion.replace_range.end;
18330
18331                let text_after_cursor = buffer
18332                    .text_for_range(
18333                        buffer.anchor_before(range_after_cursor.start)
18334                            ..buffer.anchor_after(range_after_cursor.end),
18335                    )
18336                    .collect::<String>();
18337                completion.new_text.ends_with(&text_after_cursor)
18338            }
18339        }
18340    }
18341
18342    let buffer = buffer.read(cx);
18343
18344    if let CompletionSource::Lsp {
18345        insert_range: Some(insert_range),
18346        ..
18347    } = &completion.source
18348    {
18349        let completion_mode_setting =
18350            language_settings(buffer.language().map(|l| l.name()), buffer.file(), cx)
18351                .completions
18352                .lsp_insert_mode;
18353
18354        if !should_replace(
18355            completion,
18356            &insert_range,
18357            intent,
18358            completion_mode_setting,
18359            buffer,
18360        ) {
18361            return insert_range.to_offset(buffer);
18362        }
18363    }
18364
18365    completion.replace_range.to_offset(buffer)
18366}
18367
18368fn insert_extra_newline_brackets(
18369    buffer: &MultiBufferSnapshot,
18370    range: Range<usize>,
18371    language: &language::LanguageScope,
18372) -> bool {
18373    let leading_whitespace_len = buffer
18374        .reversed_chars_at(range.start)
18375        .take_while(|c| c.is_whitespace() && *c != '\n')
18376        .map(|c| c.len_utf8())
18377        .sum::<usize>();
18378    let trailing_whitespace_len = buffer
18379        .chars_at(range.end)
18380        .take_while(|c| c.is_whitespace() && *c != '\n')
18381        .map(|c| c.len_utf8())
18382        .sum::<usize>();
18383    let range = range.start - leading_whitespace_len..range.end + trailing_whitespace_len;
18384
18385    language.brackets().any(|(pair, enabled)| {
18386        let pair_start = pair.start.trim_end();
18387        let pair_end = pair.end.trim_start();
18388
18389        enabled
18390            && pair.newline
18391            && buffer.contains_str_at(range.end, pair_end)
18392            && buffer.contains_str_at(range.start.saturating_sub(pair_start.len()), pair_start)
18393    })
18394}
18395
18396fn insert_extra_newline_tree_sitter(buffer: &MultiBufferSnapshot, range: Range<usize>) -> bool {
18397    let (buffer, range) = match buffer.range_to_buffer_ranges(range).as_slice() {
18398        [(buffer, range, _)] => (*buffer, range.clone()),
18399        _ => return false,
18400    };
18401    let pair = {
18402        let mut result: Option<BracketMatch> = None;
18403
18404        for pair in buffer
18405            .all_bracket_ranges(range.clone())
18406            .filter(move |pair| {
18407                pair.open_range.start <= range.start && pair.close_range.end >= range.end
18408            })
18409        {
18410            let len = pair.close_range.end - pair.open_range.start;
18411
18412            if let Some(existing) = &result {
18413                let existing_len = existing.close_range.end - existing.open_range.start;
18414                if len > existing_len {
18415                    continue;
18416                }
18417            }
18418
18419            result = Some(pair);
18420        }
18421
18422        result
18423    };
18424    let Some(pair) = pair else {
18425        return false;
18426    };
18427    pair.newline_only
18428        && buffer
18429            .chars_for_range(pair.open_range.end..range.start)
18430            .chain(buffer.chars_for_range(range.end..pair.close_range.start))
18431            .all(|c| c.is_whitespace() && c != '\n')
18432}
18433
18434fn get_uncommitted_diff_for_buffer(
18435    project: &Entity<Project>,
18436    buffers: impl IntoIterator<Item = Entity<Buffer>>,
18437    buffer: Entity<MultiBuffer>,
18438    cx: &mut App,
18439) -> Task<()> {
18440    let mut tasks = Vec::new();
18441    project.update(cx, |project, cx| {
18442        for buffer in buffers {
18443            if project::File::from_dyn(buffer.read(cx).file()).is_some() {
18444                tasks.push(project.open_uncommitted_diff(buffer.clone(), cx))
18445            }
18446        }
18447    });
18448    cx.spawn(async move |cx| {
18449        let diffs = future::join_all(tasks).await;
18450        buffer
18451            .update(cx, |buffer, cx| {
18452                for diff in diffs.into_iter().flatten() {
18453                    buffer.add_diff(diff, cx);
18454                }
18455            })
18456            .ok();
18457    })
18458}
18459
18460fn char_len_with_expanded_tabs(offset: usize, text: &str, tab_size: NonZeroU32) -> usize {
18461    let tab_size = tab_size.get() as usize;
18462    let mut width = offset;
18463
18464    for ch in text.chars() {
18465        width += if ch == '\t' {
18466            tab_size - (width % tab_size)
18467        } else {
18468            1
18469        };
18470    }
18471
18472    width - offset
18473}
18474
18475#[cfg(test)]
18476mod tests {
18477    use super::*;
18478
18479    #[test]
18480    fn test_string_size_with_expanded_tabs() {
18481        let nz = |val| NonZeroU32::new(val).unwrap();
18482        assert_eq!(char_len_with_expanded_tabs(0, "", nz(4)), 0);
18483        assert_eq!(char_len_with_expanded_tabs(0, "hello", nz(4)), 5);
18484        assert_eq!(char_len_with_expanded_tabs(0, "\thello", nz(4)), 9);
18485        assert_eq!(char_len_with_expanded_tabs(0, "abc\tab", nz(4)), 6);
18486        assert_eq!(char_len_with_expanded_tabs(0, "hello\t", nz(4)), 8);
18487        assert_eq!(char_len_with_expanded_tabs(0, "\t\t", nz(8)), 16);
18488        assert_eq!(char_len_with_expanded_tabs(0, "x\t", nz(8)), 8);
18489        assert_eq!(char_len_with_expanded_tabs(7, "x\t", nz(8)), 9);
18490    }
18491}
18492
18493/// Tokenizes a string into runs of text that should stick together, or that is whitespace.
18494struct WordBreakingTokenizer<'a> {
18495    input: &'a str,
18496}
18497
18498impl<'a> WordBreakingTokenizer<'a> {
18499    fn new(input: &'a str) -> Self {
18500        Self { input }
18501    }
18502}
18503
18504fn is_char_ideographic(ch: char) -> bool {
18505    use unicode_script::Script::*;
18506    use unicode_script::UnicodeScript;
18507    matches!(ch.script(), Han | Tangut | Yi)
18508}
18509
18510fn is_grapheme_ideographic(text: &str) -> bool {
18511    text.chars().any(is_char_ideographic)
18512}
18513
18514fn is_grapheme_whitespace(text: &str) -> bool {
18515    text.chars().any(|x| x.is_whitespace())
18516}
18517
18518fn should_stay_with_preceding_ideograph(text: &str) -> bool {
18519    text.chars().next().map_or(false, |ch| {
18520        matches!(ch, '。' | '、' | ',' | '?' | '!' | ':' | ';' | '…')
18521    })
18522}
18523
18524#[derive(PartialEq, Eq, Debug, Clone, Copy)]
18525enum WordBreakToken<'a> {
18526    Word { token: &'a str, grapheme_len: usize },
18527    InlineWhitespace { token: &'a str, grapheme_len: usize },
18528    Newline,
18529}
18530
18531impl<'a> Iterator for WordBreakingTokenizer<'a> {
18532    /// Yields a span, the count of graphemes in the token, and whether it was
18533    /// whitespace. Note that it also breaks at word boundaries.
18534    type Item = WordBreakToken<'a>;
18535
18536    fn next(&mut self) -> Option<Self::Item> {
18537        use unicode_segmentation::UnicodeSegmentation;
18538        if self.input.is_empty() {
18539            return None;
18540        }
18541
18542        let mut iter = self.input.graphemes(true).peekable();
18543        let mut offset = 0;
18544        let mut grapheme_len = 0;
18545        if let Some(first_grapheme) = iter.next() {
18546            let is_newline = first_grapheme == "\n";
18547            let is_whitespace = is_grapheme_whitespace(first_grapheme);
18548            offset += first_grapheme.len();
18549            grapheme_len += 1;
18550            if is_grapheme_ideographic(first_grapheme) && !is_whitespace {
18551                if let Some(grapheme) = iter.peek().copied() {
18552                    if should_stay_with_preceding_ideograph(grapheme) {
18553                        offset += grapheme.len();
18554                        grapheme_len += 1;
18555                    }
18556                }
18557            } else {
18558                let mut words = self.input[offset..].split_word_bound_indices().peekable();
18559                let mut next_word_bound = words.peek().copied();
18560                if next_word_bound.map_or(false, |(i, _)| i == 0) {
18561                    next_word_bound = words.next();
18562                }
18563                while let Some(grapheme) = iter.peek().copied() {
18564                    if next_word_bound.map_or(false, |(i, _)| i == offset) {
18565                        break;
18566                    };
18567                    if is_grapheme_whitespace(grapheme) != is_whitespace
18568                        || (grapheme == "\n") != is_newline
18569                    {
18570                        break;
18571                    };
18572                    offset += grapheme.len();
18573                    grapheme_len += 1;
18574                    iter.next();
18575                }
18576            }
18577            let token = &self.input[..offset];
18578            self.input = &self.input[offset..];
18579            if token == "\n" {
18580                Some(WordBreakToken::Newline)
18581            } else if is_whitespace {
18582                Some(WordBreakToken::InlineWhitespace {
18583                    token,
18584                    grapheme_len,
18585                })
18586            } else {
18587                Some(WordBreakToken::Word {
18588                    token,
18589                    grapheme_len,
18590                })
18591            }
18592        } else {
18593            None
18594        }
18595    }
18596}
18597
18598#[test]
18599fn test_word_breaking_tokenizer() {
18600    let tests: &[(&str, &[WordBreakToken<'static>])] = &[
18601        ("", &[]),
18602        ("  ", &[whitespace("  ", 2)]),
18603        ("Ʒ", &[word("Ʒ", 1)]),
18604        ("Ǽ", &[word("Ǽ", 1)]),
18605        ("", &[word("", 1)]),
18606        ("⋑⋑", &[word("⋑⋑", 2)]),
18607        (
18608            "原理,进而",
18609            &[word("", 1), word("理,", 2), word("", 1), word("", 1)],
18610        ),
18611        (
18612            "hello world",
18613            &[word("hello", 5), whitespace(" ", 1), word("world", 5)],
18614        ),
18615        (
18616            "hello, world",
18617            &[word("hello,", 6), whitespace(" ", 1), word("world", 5)],
18618        ),
18619        (
18620            "  hello world",
18621            &[
18622                whitespace("  ", 2),
18623                word("hello", 5),
18624                whitespace(" ", 1),
18625                word("world", 5),
18626            ],
18627        ),
18628        (
18629            "这是什么 \n 钢笔",
18630            &[
18631                word("", 1),
18632                word("", 1),
18633                word("", 1),
18634                word("", 1),
18635                whitespace(" ", 1),
18636                newline(),
18637                whitespace(" ", 1),
18638                word("", 1),
18639                word("", 1),
18640            ],
18641        ),
18642        (" mutton", &[whitespace("", 1), word("mutton", 6)]),
18643    ];
18644
18645    fn word(token: &'static str, grapheme_len: usize) -> WordBreakToken<'static> {
18646        WordBreakToken::Word {
18647            token,
18648            grapheme_len,
18649        }
18650    }
18651
18652    fn whitespace(token: &'static str, grapheme_len: usize) -> WordBreakToken<'static> {
18653        WordBreakToken::InlineWhitespace {
18654            token,
18655            grapheme_len,
18656        }
18657    }
18658
18659    fn newline() -> WordBreakToken<'static> {
18660        WordBreakToken::Newline
18661    }
18662
18663    for (input, result) in tests {
18664        assert_eq!(
18665            WordBreakingTokenizer::new(input)
18666                .collect::<Vec<_>>()
18667                .as_slice(),
18668            *result,
18669        );
18670    }
18671}
18672
18673fn wrap_with_prefix(
18674    line_prefix: String,
18675    unwrapped_text: String,
18676    wrap_column: usize,
18677    tab_size: NonZeroU32,
18678    preserve_existing_whitespace: bool,
18679) -> String {
18680    let line_prefix_len = char_len_with_expanded_tabs(0, &line_prefix, tab_size);
18681    let mut wrapped_text = String::new();
18682    let mut current_line = line_prefix.clone();
18683
18684    let tokenizer = WordBreakingTokenizer::new(&unwrapped_text);
18685    let mut current_line_len = line_prefix_len;
18686    let mut in_whitespace = false;
18687    for token in tokenizer {
18688        let have_preceding_whitespace = in_whitespace;
18689        match token {
18690            WordBreakToken::Word {
18691                token,
18692                grapheme_len,
18693            } => {
18694                in_whitespace = false;
18695                if current_line_len + grapheme_len > wrap_column
18696                    && current_line_len != line_prefix_len
18697                {
18698                    wrapped_text.push_str(current_line.trim_end());
18699                    wrapped_text.push('\n');
18700                    current_line.truncate(line_prefix.len());
18701                    current_line_len = line_prefix_len;
18702                }
18703                current_line.push_str(token);
18704                current_line_len += grapheme_len;
18705            }
18706            WordBreakToken::InlineWhitespace {
18707                mut token,
18708                mut grapheme_len,
18709            } => {
18710                in_whitespace = true;
18711                if have_preceding_whitespace && !preserve_existing_whitespace {
18712                    continue;
18713                }
18714                if !preserve_existing_whitespace {
18715                    token = " ";
18716                    grapheme_len = 1;
18717                }
18718                if current_line_len + grapheme_len > wrap_column {
18719                    wrapped_text.push_str(current_line.trim_end());
18720                    wrapped_text.push('\n');
18721                    current_line.truncate(line_prefix.len());
18722                    current_line_len = line_prefix_len;
18723                } else if current_line_len != line_prefix_len || preserve_existing_whitespace {
18724                    current_line.push_str(token);
18725                    current_line_len += grapheme_len;
18726                }
18727            }
18728            WordBreakToken::Newline => {
18729                in_whitespace = true;
18730                if preserve_existing_whitespace {
18731                    wrapped_text.push_str(current_line.trim_end());
18732                    wrapped_text.push('\n');
18733                    current_line.truncate(line_prefix.len());
18734                    current_line_len = line_prefix_len;
18735                } else if have_preceding_whitespace {
18736                    continue;
18737                } else if current_line_len + 1 > wrap_column && current_line_len != line_prefix_len
18738                {
18739                    wrapped_text.push_str(current_line.trim_end());
18740                    wrapped_text.push('\n');
18741                    current_line.truncate(line_prefix.len());
18742                    current_line_len = line_prefix_len;
18743                } else if current_line_len != line_prefix_len {
18744                    current_line.push(' ');
18745                    current_line_len += 1;
18746                }
18747            }
18748        }
18749    }
18750
18751    if !current_line.is_empty() {
18752        wrapped_text.push_str(&current_line);
18753    }
18754    wrapped_text
18755}
18756
18757#[test]
18758fn test_wrap_with_prefix() {
18759    assert_eq!(
18760        wrap_with_prefix(
18761            "# ".to_string(),
18762            "abcdefg".to_string(),
18763            4,
18764            NonZeroU32::new(4).unwrap(),
18765            false,
18766        ),
18767        "# abcdefg"
18768    );
18769    assert_eq!(
18770        wrap_with_prefix(
18771            "".to_string(),
18772            "\thello world".to_string(),
18773            8,
18774            NonZeroU32::new(4).unwrap(),
18775            false,
18776        ),
18777        "hello\nworld"
18778    );
18779    assert_eq!(
18780        wrap_with_prefix(
18781            "// ".to_string(),
18782            "xx \nyy zz aa bb cc".to_string(),
18783            12,
18784            NonZeroU32::new(4).unwrap(),
18785            false,
18786        ),
18787        "// xx yy zz\n// aa bb cc"
18788    );
18789    assert_eq!(
18790        wrap_with_prefix(
18791            String::new(),
18792            "这是什么 \n 钢笔".to_string(),
18793            3,
18794            NonZeroU32::new(4).unwrap(),
18795            false,
18796        ),
18797        "这是什\n么 钢\n"
18798    );
18799}
18800
18801pub trait CollaborationHub {
18802    fn collaborators<'a>(&self, cx: &'a App) -> &'a HashMap<PeerId, Collaborator>;
18803    fn user_participant_indices<'a>(&self, cx: &'a App) -> &'a HashMap<u64, ParticipantIndex>;
18804    fn user_names(&self, cx: &App) -> HashMap<u64, SharedString>;
18805}
18806
18807impl CollaborationHub for Entity<Project> {
18808    fn collaborators<'a>(&self, cx: &'a App) -> &'a HashMap<PeerId, Collaborator> {
18809        self.read(cx).collaborators()
18810    }
18811
18812    fn user_participant_indices<'a>(&self, cx: &'a App) -> &'a HashMap<u64, ParticipantIndex> {
18813        self.read(cx).user_store().read(cx).participant_indices()
18814    }
18815
18816    fn user_names(&self, cx: &App) -> HashMap<u64, SharedString> {
18817        let this = self.read(cx);
18818        let user_ids = this.collaborators().values().map(|c| c.user_id);
18819        this.user_store().read_with(cx, |user_store, cx| {
18820            user_store.participant_names(user_ids, cx)
18821        })
18822    }
18823}
18824
18825pub trait SemanticsProvider {
18826    fn hover(
18827        &self,
18828        buffer: &Entity<Buffer>,
18829        position: text::Anchor,
18830        cx: &mut App,
18831    ) -> Option<Task<Vec<project::Hover>>>;
18832
18833    fn inlay_hints(
18834        &self,
18835        buffer_handle: Entity<Buffer>,
18836        range: Range<text::Anchor>,
18837        cx: &mut App,
18838    ) -> Option<Task<anyhow::Result<Vec<InlayHint>>>>;
18839
18840    fn resolve_inlay_hint(
18841        &self,
18842        hint: InlayHint,
18843        buffer_handle: Entity<Buffer>,
18844        server_id: LanguageServerId,
18845        cx: &mut App,
18846    ) -> Option<Task<anyhow::Result<InlayHint>>>;
18847
18848    fn supports_inlay_hints(&self, buffer: &Entity<Buffer>, cx: &mut App) -> bool;
18849
18850    fn document_highlights(
18851        &self,
18852        buffer: &Entity<Buffer>,
18853        position: text::Anchor,
18854        cx: &mut App,
18855    ) -> Option<Task<Result<Vec<DocumentHighlight>>>>;
18856
18857    fn definitions(
18858        &self,
18859        buffer: &Entity<Buffer>,
18860        position: text::Anchor,
18861        kind: GotoDefinitionKind,
18862        cx: &mut App,
18863    ) -> Option<Task<Result<Vec<LocationLink>>>>;
18864
18865    fn range_for_rename(
18866        &self,
18867        buffer: &Entity<Buffer>,
18868        position: text::Anchor,
18869        cx: &mut App,
18870    ) -> Option<Task<Result<Option<Range<text::Anchor>>>>>;
18871
18872    fn perform_rename(
18873        &self,
18874        buffer: &Entity<Buffer>,
18875        position: text::Anchor,
18876        new_name: String,
18877        cx: &mut App,
18878    ) -> Option<Task<Result<ProjectTransaction>>>;
18879}
18880
18881pub trait CompletionProvider {
18882    fn completions(
18883        &self,
18884        excerpt_id: ExcerptId,
18885        buffer: &Entity<Buffer>,
18886        buffer_position: text::Anchor,
18887        trigger: CompletionContext,
18888        window: &mut Window,
18889        cx: &mut Context<Editor>,
18890    ) -> Task<Result<Option<Vec<Completion>>>>;
18891
18892    fn resolve_completions(
18893        &self,
18894        buffer: Entity<Buffer>,
18895        completion_indices: Vec<usize>,
18896        completions: Rc<RefCell<Box<[Completion]>>>,
18897        cx: &mut Context<Editor>,
18898    ) -> Task<Result<bool>>;
18899
18900    fn apply_additional_edits_for_completion(
18901        &self,
18902        _buffer: Entity<Buffer>,
18903        _completions: Rc<RefCell<Box<[Completion]>>>,
18904        _completion_index: usize,
18905        _push_to_history: bool,
18906        _cx: &mut Context<Editor>,
18907    ) -> Task<Result<Option<language::Transaction>>> {
18908        Task::ready(Ok(None))
18909    }
18910
18911    fn is_completion_trigger(
18912        &self,
18913        buffer: &Entity<Buffer>,
18914        position: language::Anchor,
18915        text: &str,
18916        trigger_in_words: bool,
18917        cx: &mut Context<Editor>,
18918    ) -> bool;
18919
18920    fn sort_completions(&self) -> bool {
18921        true
18922    }
18923
18924    fn filter_completions(&self) -> bool {
18925        true
18926    }
18927}
18928
18929pub trait CodeActionProvider {
18930    fn id(&self) -> Arc<str>;
18931
18932    fn code_actions(
18933        &self,
18934        buffer: &Entity<Buffer>,
18935        range: Range<text::Anchor>,
18936        window: &mut Window,
18937        cx: &mut App,
18938    ) -> Task<Result<Vec<CodeAction>>>;
18939
18940    fn apply_code_action(
18941        &self,
18942        buffer_handle: Entity<Buffer>,
18943        action: CodeAction,
18944        excerpt_id: ExcerptId,
18945        push_to_history: bool,
18946        window: &mut Window,
18947        cx: &mut App,
18948    ) -> Task<Result<ProjectTransaction>>;
18949}
18950
18951impl CodeActionProvider for Entity<Project> {
18952    fn id(&self) -> Arc<str> {
18953        "project".into()
18954    }
18955
18956    fn code_actions(
18957        &self,
18958        buffer: &Entity<Buffer>,
18959        range: Range<text::Anchor>,
18960        _window: &mut Window,
18961        cx: &mut App,
18962    ) -> Task<Result<Vec<CodeAction>>> {
18963        self.update(cx, |project, cx| {
18964            let code_lens = project.code_lens(buffer, range.clone(), cx);
18965            let code_actions = project.code_actions(buffer, range, None, cx);
18966            cx.background_spawn(async move {
18967                let (code_lens, code_actions) = join(code_lens, code_actions).await;
18968                Ok(code_lens
18969                    .context("code lens fetch")?
18970                    .into_iter()
18971                    .chain(code_actions.context("code action fetch")?)
18972                    .collect())
18973            })
18974        })
18975    }
18976
18977    fn apply_code_action(
18978        &self,
18979        buffer_handle: Entity<Buffer>,
18980        action: CodeAction,
18981        _excerpt_id: ExcerptId,
18982        push_to_history: bool,
18983        _window: &mut Window,
18984        cx: &mut App,
18985    ) -> Task<Result<ProjectTransaction>> {
18986        self.update(cx, |project, cx| {
18987            project.apply_code_action(buffer_handle, action, push_to_history, cx)
18988        })
18989    }
18990}
18991
18992fn snippet_completions(
18993    project: &Project,
18994    buffer: &Entity<Buffer>,
18995    buffer_position: text::Anchor,
18996    cx: &mut App,
18997) -> Task<Result<Vec<Completion>>> {
18998    let languages = buffer.read(cx).languages_at(buffer_position);
18999    let snippet_store = project.snippets().read(cx);
19000
19001    let scopes: Vec<_> = languages
19002        .iter()
19003        .filter_map(|language| {
19004            let language_name = language.lsp_id();
19005            let snippets = snippet_store.snippets_for(Some(language_name), cx);
19006
19007            if snippets.is_empty() {
19008                None
19009            } else {
19010                Some((language.default_scope(), snippets))
19011            }
19012        })
19013        .collect();
19014
19015    if scopes.is_empty() {
19016        return Task::ready(Ok(vec![]));
19017    }
19018
19019    let snapshot = buffer.read(cx).text_snapshot();
19020    let chars: String = snapshot
19021        .reversed_chars_for_range(text::Anchor::MIN..buffer_position)
19022        .collect();
19023    let executor = cx.background_executor().clone();
19024
19025    cx.background_spawn(async move {
19026        let mut all_results: Vec<Completion> = Vec::new();
19027        for (scope, snippets) in scopes.into_iter() {
19028            let classifier = CharClassifier::new(Some(scope)).for_completion(true);
19029            let mut last_word = chars
19030                .chars()
19031                .take_while(|c| classifier.is_word(*c))
19032                .collect::<String>();
19033            last_word = last_word.chars().rev().collect();
19034
19035            if last_word.is_empty() {
19036                return Ok(vec![]);
19037            }
19038
19039            let as_offset = text::ToOffset::to_offset(&buffer_position, &snapshot);
19040            let to_lsp = |point: &text::Anchor| {
19041                let end = text::ToPointUtf16::to_point_utf16(point, &snapshot);
19042                point_to_lsp(end)
19043            };
19044            let lsp_end = to_lsp(&buffer_position);
19045
19046            let candidates = snippets
19047                .iter()
19048                .enumerate()
19049                .flat_map(|(ix, snippet)| {
19050                    snippet
19051                        .prefix
19052                        .iter()
19053                        .map(move |prefix| StringMatchCandidate::new(ix, &prefix))
19054                })
19055                .collect::<Vec<StringMatchCandidate>>();
19056
19057            let mut matches = fuzzy::match_strings(
19058                &candidates,
19059                &last_word,
19060                last_word.chars().any(|c| c.is_uppercase()),
19061                100,
19062                &Default::default(),
19063                executor.clone(),
19064            )
19065            .await;
19066
19067            // Remove all candidates where the query's start does not match the start of any word in the candidate
19068            if let Some(query_start) = last_word.chars().next() {
19069                matches.retain(|string_match| {
19070                    split_words(&string_match.string).any(|word| {
19071                        // Check that the first codepoint of the word as lowercase matches the first
19072                        // codepoint of the query as lowercase
19073                        word.chars()
19074                            .flat_map(|codepoint| codepoint.to_lowercase())
19075                            .zip(query_start.to_lowercase())
19076                            .all(|(word_cp, query_cp)| word_cp == query_cp)
19077                    })
19078                });
19079            }
19080
19081            let matched_strings = matches
19082                .into_iter()
19083                .map(|m| m.string)
19084                .collect::<HashSet<_>>();
19085
19086            let mut result: Vec<Completion> = snippets
19087                .iter()
19088                .filter_map(|snippet| {
19089                    let matching_prefix = snippet
19090                        .prefix
19091                        .iter()
19092                        .find(|prefix| matched_strings.contains(*prefix))?;
19093                    let start = as_offset - last_word.len();
19094                    let start = snapshot.anchor_before(start);
19095                    let range = start..buffer_position;
19096                    let lsp_start = to_lsp(&start);
19097                    let lsp_range = lsp::Range {
19098                        start: lsp_start,
19099                        end: lsp_end,
19100                    };
19101                    Some(Completion {
19102                        replace_range: range,
19103                        new_text: snippet.body.clone(),
19104                        source: CompletionSource::Lsp {
19105                            insert_range: None,
19106                            server_id: LanguageServerId(usize::MAX),
19107                            resolved: true,
19108                            lsp_completion: Box::new(lsp::CompletionItem {
19109                                label: snippet.prefix.first().unwrap().clone(),
19110                                kind: Some(CompletionItemKind::SNIPPET),
19111                                label_details: snippet.description.as_ref().map(|description| {
19112                                    lsp::CompletionItemLabelDetails {
19113                                        detail: Some(description.clone()),
19114                                        description: None,
19115                                    }
19116                                }),
19117                                insert_text_format: Some(InsertTextFormat::SNIPPET),
19118                                text_edit: Some(lsp::CompletionTextEdit::InsertAndReplace(
19119                                    lsp::InsertReplaceEdit {
19120                                        new_text: snippet.body.clone(),
19121                                        insert: lsp_range,
19122                                        replace: lsp_range,
19123                                    },
19124                                )),
19125                                filter_text: Some(snippet.body.clone()),
19126                                sort_text: Some(char::MAX.to_string()),
19127                                ..lsp::CompletionItem::default()
19128                            }),
19129                            lsp_defaults: None,
19130                        },
19131                        label: CodeLabel {
19132                            text: matching_prefix.clone(),
19133                            runs: Vec::new(),
19134                            filter_range: 0..matching_prefix.len(),
19135                        },
19136                        icon_path: None,
19137                        documentation: snippet.description.clone().map(|description| {
19138                            CompletionDocumentation::SingleLine(description.into())
19139                        }),
19140                        insert_text_mode: None,
19141                        confirm: None,
19142                    })
19143                })
19144                .collect();
19145
19146            all_results.append(&mut result);
19147        }
19148
19149        Ok(all_results)
19150    })
19151}
19152
19153impl CompletionProvider for Entity<Project> {
19154    fn completions(
19155        &self,
19156        _excerpt_id: ExcerptId,
19157        buffer: &Entity<Buffer>,
19158        buffer_position: text::Anchor,
19159        options: CompletionContext,
19160        _window: &mut Window,
19161        cx: &mut Context<Editor>,
19162    ) -> Task<Result<Option<Vec<Completion>>>> {
19163        self.update(cx, |project, cx| {
19164            let snippets = snippet_completions(project, buffer, buffer_position, cx);
19165            let project_completions = project.completions(buffer, buffer_position, options, cx);
19166            cx.background_spawn(async move {
19167                let snippets_completions = snippets.await?;
19168                match project_completions.await? {
19169                    Some(mut completions) => {
19170                        completions.extend(snippets_completions);
19171                        Ok(Some(completions))
19172                    }
19173                    None => {
19174                        if snippets_completions.is_empty() {
19175                            Ok(None)
19176                        } else {
19177                            Ok(Some(snippets_completions))
19178                        }
19179                    }
19180                }
19181            })
19182        })
19183    }
19184
19185    fn resolve_completions(
19186        &self,
19187        buffer: Entity<Buffer>,
19188        completion_indices: Vec<usize>,
19189        completions: Rc<RefCell<Box<[Completion]>>>,
19190        cx: &mut Context<Editor>,
19191    ) -> Task<Result<bool>> {
19192        self.update(cx, |project, cx| {
19193            project.lsp_store().update(cx, |lsp_store, cx| {
19194                lsp_store.resolve_completions(buffer, completion_indices, completions, cx)
19195            })
19196        })
19197    }
19198
19199    fn apply_additional_edits_for_completion(
19200        &self,
19201        buffer: Entity<Buffer>,
19202        completions: Rc<RefCell<Box<[Completion]>>>,
19203        completion_index: usize,
19204        push_to_history: bool,
19205        cx: &mut Context<Editor>,
19206    ) -> Task<Result<Option<language::Transaction>>> {
19207        self.update(cx, |project, cx| {
19208            project.lsp_store().update(cx, |lsp_store, cx| {
19209                lsp_store.apply_additional_edits_for_completion(
19210                    buffer,
19211                    completions,
19212                    completion_index,
19213                    push_to_history,
19214                    cx,
19215                )
19216            })
19217        })
19218    }
19219
19220    fn is_completion_trigger(
19221        &self,
19222        buffer: &Entity<Buffer>,
19223        position: language::Anchor,
19224        text: &str,
19225        trigger_in_words: bool,
19226        cx: &mut Context<Editor>,
19227    ) -> bool {
19228        let mut chars = text.chars();
19229        let char = if let Some(char) = chars.next() {
19230            char
19231        } else {
19232            return false;
19233        };
19234        if chars.next().is_some() {
19235            return false;
19236        }
19237
19238        let buffer = buffer.read(cx);
19239        let snapshot = buffer.snapshot();
19240        if !snapshot.settings_at(position, cx).show_completions_on_input {
19241            return false;
19242        }
19243        let classifier = snapshot.char_classifier_at(position).for_completion(true);
19244        if trigger_in_words && classifier.is_word(char) {
19245            return true;
19246        }
19247
19248        buffer.completion_triggers().contains(text)
19249    }
19250}
19251
19252impl SemanticsProvider for Entity<Project> {
19253    fn hover(
19254        &self,
19255        buffer: &Entity<Buffer>,
19256        position: text::Anchor,
19257        cx: &mut App,
19258    ) -> Option<Task<Vec<project::Hover>>> {
19259        Some(self.update(cx, |project, cx| project.hover(buffer, position, cx)))
19260    }
19261
19262    fn document_highlights(
19263        &self,
19264        buffer: &Entity<Buffer>,
19265        position: text::Anchor,
19266        cx: &mut App,
19267    ) -> Option<Task<Result<Vec<DocumentHighlight>>>> {
19268        Some(self.update(cx, |project, cx| {
19269            project.document_highlights(buffer, position, cx)
19270        }))
19271    }
19272
19273    fn definitions(
19274        &self,
19275        buffer: &Entity<Buffer>,
19276        position: text::Anchor,
19277        kind: GotoDefinitionKind,
19278        cx: &mut App,
19279    ) -> Option<Task<Result<Vec<LocationLink>>>> {
19280        Some(self.update(cx, |project, cx| match kind {
19281            GotoDefinitionKind::Symbol => project.definition(&buffer, position, cx),
19282            GotoDefinitionKind::Declaration => project.declaration(&buffer, position, cx),
19283            GotoDefinitionKind::Type => project.type_definition(&buffer, position, cx),
19284            GotoDefinitionKind::Implementation => project.implementation(&buffer, position, cx),
19285        }))
19286    }
19287
19288    fn supports_inlay_hints(&self, buffer: &Entity<Buffer>, cx: &mut App) -> bool {
19289        // TODO: make this work for remote projects
19290        self.update(cx, |this, cx| {
19291            buffer.update(cx, |buffer, cx| {
19292                this.any_language_server_supports_inlay_hints(buffer, cx)
19293            })
19294        })
19295    }
19296
19297    fn inlay_hints(
19298        &self,
19299        buffer_handle: Entity<Buffer>,
19300        range: Range<text::Anchor>,
19301        cx: &mut App,
19302    ) -> Option<Task<anyhow::Result<Vec<InlayHint>>>> {
19303        Some(self.update(cx, |project, cx| {
19304            project.inlay_hints(buffer_handle, range, cx)
19305        }))
19306    }
19307
19308    fn resolve_inlay_hint(
19309        &self,
19310        hint: InlayHint,
19311        buffer_handle: Entity<Buffer>,
19312        server_id: LanguageServerId,
19313        cx: &mut App,
19314    ) -> Option<Task<anyhow::Result<InlayHint>>> {
19315        Some(self.update(cx, |project, cx| {
19316            project.resolve_inlay_hint(hint, buffer_handle, server_id, cx)
19317        }))
19318    }
19319
19320    fn range_for_rename(
19321        &self,
19322        buffer: &Entity<Buffer>,
19323        position: text::Anchor,
19324        cx: &mut App,
19325    ) -> Option<Task<Result<Option<Range<text::Anchor>>>>> {
19326        Some(self.update(cx, |project, cx| {
19327            let buffer = buffer.clone();
19328            let task = project.prepare_rename(buffer.clone(), position, cx);
19329            cx.spawn(async move |_, cx| {
19330                Ok(match task.await? {
19331                    PrepareRenameResponse::Success(range) => Some(range),
19332                    PrepareRenameResponse::InvalidPosition => None,
19333                    PrepareRenameResponse::OnlyUnpreparedRenameSupported => {
19334                        // Fallback on using TreeSitter info to determine identifier range
19335                        buffer.update(cx, |buffer, _| {
19336                            let snapshot = buffer.snapshot();
19337                            let (range, kind) = snapshot.surrounding_word(position);
19338                            if kind != Some(CharKind::Word) {
19339                                return None;
19340                            }
19341                            Some(
19342                                snapshot.anchor_before(range.start)
19343                                    ..snapshot.anchor_after(range.end),
19344                            )
19345                        })?
19346                    }
19347                })
19348            })
19349        }))
19350    }
19351
19352    fn perform_rename(
19353        &self,
19354        buffer: &Entity<Buffer>,
19355        position: text::Anchor,
19356        new_name: String,
19357        cx: &mut App,
19358    ) -> Option<Task<Result<ProjectTransaction>>> {
19359        Some(self.update(cx, |project, cx| {
19360            project.perform_rename(buffer.clone(), position, new_name, cx)
19361        }))
19362    }
19363}
19364
19365fn inlay_hint_settings(
19366    location: Anchor,
19367    snapshot: &MultiBufferSnapshot,
19368    cx: &mut Context<Editor>,
19369) -> InlayHintSettings {
19370    let file = snapshot.file_at(location);
19371    let language = snapshot.language_at(location).map(|l| l.name());
19372    language_settings(language, file, cx).inlay_hints
19373}
19374
19375fn consume_contiguous_rows(
19376    contiguous_row_selections: &mut Vec<Selection<Point>>,
19377    selection: &Selection<Point>,
19378    display_map: &DisplaySnapshot,
19379    selections: &mut Peekable<std::slice::Iter<Selection<Point>>>,
19380) -> (MultiBufferRow, MultiBufferRow) {
19381    contiguous_row_selections.push(selection.clone());
19382    let start_row = MultiBufferRow(selection.start.row);
19383    let mut end_row = ending_row(selection, display_map);
19384
19385    while let Some(next_selection) = selections.peek() {
19386        if next_selection.start.row <= end_row.0 {
19387            end_row = ending_row(next_selection, display_map);
19388            contiguous_row_selections.push(selections.next().unwrap().clone());
19389        } else {
19390            break;
19391        }
19392    }
19393    (start_row, end_row)
19394}
19395
19396fn ending_row(next_selection: &Selection<Point>, display_map: &DisplaySnapshot) -> MultiBufferRow {
19397    if next_selection.end.column > 0 || next_selection.is_empty() {
19398        MultiBufferRow(display_map.next_line_boundary(next_selection.end).0.row + 1)
19399    } else {
19400        MultiBufferRow(next_selection.end.row)
19401    }
19402}
19403
19404impl EditorSnapshot {
19405    pub fn remote_selections_in_range<'a>(
19406        &'a self,
19407        range: &'a Range<Anchor>,
19408        collaboration_hub: &dyn CollaborationHub,
19409        cx: &'a App,
19410    ) -> impl 'a + Iterator<Item = RemoteSelection> {
19411        let participant_names = collaboration_hub.user_names(cx);
19412        let participant_indices = collaboration_hub.user_participant_indices(cx);
19413        let collaborators_by_peer_id = collaboration_hub.collaborators(cx);
19414        let collaborators_by_replica_id = collaborators_by_peer_id
19415            .iter()
19416            .map(|(_, collaborator)| (collaborator.replica_id, collaborator))
19417            .collect::<HashMap<_, _>>();
19418        self.buffer_snapshot
19419            .selections_in_range(range, false)
19420            .filter_map(move |(replica_id, line_mode, cursor_shape, selection)| {
19421                let collaborator = collaborators_by_replica_id.get(&replica_id)?;
19422                let participant_index = participant_indices.get(&collaborator.user_id).copied();
19423                let user_name = participant_names.get(&collaborator.user_id).cloned();
19424                Some(RemoteSelection {
19425                    replica_id,
19426                    selection,
19427                    cursor_shape,
19428                    line_mode,
19429                    participant_index,
19430                    peer_id: collaborator.peer_id,
19431                    user_name,
19432                })
19433            })
19434    }
19435
19436    pub fn hunks_for_ranges(
19437        &self,
19438        ranges: impl IntoIterator<Item = Range<Point>>,
19439    ) -> Vec<MultiBufferDiffHunk> {
19440        let mut hunks = Vec::new();
19441        let mut processed_buffer_rows: HashMap<BufferId, HashSet<Range<text::Anchor>>> =
19442            HashMap::default();
19443        for query_range in ranges {
19444            let query_rows =
19445                MultiBufferRow(query_range.start.row)..MultiBufferRow(query_range.end.row + 1);
19446            for hunk in self.buffer_snapshot.diff_hunks_in_range(
19447                Point::new(query_rows.start.0, 0)..Point::new(query_rows.end.0, 0),
19448            ) {
19449                // Include deleted hunks that are adjacent to the query range, because
19450                // otherwise they would be missed.
19451                let mut intersects_range = hunk.row_range.overlaps(&query_rows);
19452                if hunk.status().is_deleted() {
19453                    intersects_range |= hunk.row_range.start == query_rows.end;
19454                    intersects_range |= hunk.row_range.end == query_rows.start;
19455                }
19456                if intersects_range {
19457                    if !processed_buffer_rows
19458                        .entry(hunk.buffer_id)
19459                        .or_default()
19460                        .insert(hunk.buffer_range.start..hunk.buffer_range.end)
19461                    {
19462                        continue;
19463                    }
19464                    hunks.push(hunk);
19465                }
19466            }
19467        }
19468
19469        hunks
19470    }
19471
19472    fn display_diff_hunks_for_rows<'a>(
19473        &'a self,
19474        display_rows: Range<DisplayRow>,
19475        folded_buffers: &'a HashSet<BufferId>,
19476    ) -> impl 'a + Iterator<Item = DisplayDiffHunk> {
19477        let buffer_start = DisplayPoint::new(display_rows.start, 0).to_point(self);
19478        let buffer_end = DisplayPoint::new(display_rows.end, 0).to_point(self);
19479
19480        self.buffer_snapshot
19481            .diff_hunks_in_range(buffer_start..buffer_end)
19482            .filter_map(|hunk| {
19483                if folded_buffers.contains(&hunk.buffer_id) {
19484                    return None;
19485                }
19486
19487                let hunk_start_point = Point::new(hunk.row_range.start.0, 0);
19488                let hunk_end_point = Point::new(hunk.row_range.end.0, 0);
19489
19490                let hunk_display_start = self.point_to_display_point(hunk_start_point, Bias::Left);
19491                let hunk_display_end = self.point_to_display_point(hunk_end_point, Bias::Right);
19492
19493                let display_hunk = if hunk_display_start.column() != 0 {
19494                    DisplayDiffHunk::Folded {
19495                        display_row: hunk_display_start.row(),
19496                    }
19497                } else {
19498                    let mut end_row = hunk_display_end.row();
19499                    if hunk_display_end.column() > 0 {
19500                        end_row.0 += 1;
19501                    }
19502                    let is_created_file = hunk.is_created_file();
19503                    DisplayDiffHunk::Unfolded {
19504                        status: hunk.status(),
19505                        diff_base_byte_range: hunk.diff_base_byte_range,
19506                        display_row_range: hunk_display_start.row()..end_row,
19507                        multi_buffer_range: Anchor::range_in_buffer(
19508                            hunk.excerpt_id,
19509                            hunk.buffer_id,
19510                            hunk.buffer_range,
19511                        ),
19512                        is_created_file,
19513                    }
19514                };
19515
19516                Some(display_hunk)
19517            })
19518    }
19519
19520    pub fn language_at<T: ToOffset>(&self, position: T) -> Option<&Arc<Language>> {
19521        self.display_snapshot.buffer_snapshot.language_at(position)
19522    }
19523
19524    pub fn is_focused(&self) -> bool {
19525        self.is_focused
19526    }
19527
19528    pub fn placeholder_text(&self) -> Option<&Arc<str>> {
19529        self.placeholder_text.as_ref()
19530    }
19531
19532    pub fn scroll_position(&self) -> gpui::Point<f32> {
19533        self.scroll_anchor.scroll_position(&self.display_snapshot)
19534    }
19535
19536    fn gutter_dimensions(
19537        &self,
19538        font_id: FontId,
19539        font_size: Pixels,
19540        max_line_number_width: Pixels,
19541        cx: &App,
19542    ) -> Option<GutterDimensions> {
19543        if !self.show_gutter {
19544            return None;
19545        }
19546
19547        let descent = cx.text_system().descent(font_id, font_size);
19548        let em_width = cx.text_system().em_width(font_id, font_size).log_err()?;
19549        let em_advance = cx.text_system().em_advance(font_id, font_size).log_err()?;
19550
19551        let show_git_gutter = self.show_git_diff_gutter.unwrap_or_else(|| {
19552            matches!(
19553                ProjectSettings::get_global(cx).git.git_gutter,
19554                Some(GitGutterSetting::TrackedFiles)
19555            )
19556        });
19557        let gutter_settings = EditorSettings::get_global(cx).gutter;
19558        let show_line_numbers = self
19559            .show_line_numbers
19560            .unwrap_or(gutter_settings.line_numbers);
19561        let line_gutter_width = if show_line_numbers {
19562            // Avoid flicker-like gutter resizes when the line number gains another digit and only resize the gutter on files with N*10^5 lines.
19563            let min_width_for_number_on_gutter = em_advance * MIN_LINE_NUMBER_DIGITS as f32;
19564            max_line_number_width.max(min_width_for_number_on_gutter)
19565        } else {
19566            0.0.into()
19567        };
19568
19569        let show_code_actions = self
19570            .show_code_actions
19571            .unwrap_or(gutter_settings.code_actions);
19572
19573        let show_runnables = self.show_runnables.unwrap_or(gutter_settings.runnables);
19574        let show_breakpoints = self.show_breakpoints.unwrap_or(gutter_settings.breakpoints);
19575
19576        let git_blame_entries_width =
19577            self.git_blame_gutter_max_author_length
19578                .map(|max_author_length| {
19579                    let renderer = cx.global::<GlobalBlameRenderer>().0.clone();
19580                    const MAX_RELATIVE_TIMESTAMP: &str = "60 minutes ago";
19581
19582                    /// The number of characters to dedicate to gaps and margins.
19583                    const SPACING_WIDTH: usize = 4;
19584
19585                    let max_char_count = max_author_length.min(renderer.max_author_length())
19586                        + ::git::SHORT_SHA_LENGTH
19587                        + MAX_RELATIVE_TIMESTAMP.len()
19588                        + SPACING_WIDTH;
19589
19590                    em_advance * max_char_count
19591                });
19592
19593        let is_singleton = self.buffer_snapshot.is_singleton();
19594
19595        let mut left_padding = git_blame_entries_width.unwrap_or(Pixels::ZERO);
19596        left_padding += if !is_singleton {
19597            em_width * 4.0
19598        } else if show_code_actions || show_runnables || show_breakpoints {
19599            em_width * 3.0
19600        } else if show_git_gutter && show_line_numbers {
19601            em_width * 2.0
19602        } else if show_git_gutter || show_line_numbers {
19603            em_width
19604        } else {
19605            px(0.)
19606        };
19607
19608        let shows_folds = is_singleton && gutter_settings.folds;
19609
19610        let right_padding = if shows_folds && show_line_numbers {
19611            em_width * 4.0
19612        } else if shows_folds || (!is_singleton && show_line_numbers) {
19613            em_width * 3.0
19614        } else if show_line_numbers {
19615            em_width
19616        } else {
19617            px(0.)
19618        };
19619
19620        Some(GutterDimensions {
19621            left_padding,
19622            right_padding,
19623            width: line_gutter_width + left_padding + right_padding,
19624            margin: -descent,
19625            git_blame_entries_width,
19626        })
19627    }
19628
19629    pub fn render_crease_toggle(
19630        &self,
19631        buffer_row: MultiBufferRow,
19632        row_contains_cursor: bool,
19633        editor: Entity<Editor>,
19634        window: &mut Window,
19635        cx: &mut App,
19636    ) -> Option<AnyElement> {
19637        let folded = self.is_line_folded(buffer_row);
19638        let mut is_foldable = false;
19639
19640        if let Some(crease) = self
19641            .crease_snapshot
19642            .query_row(buffer_row, &self.buffer_snapshot)
19643        {
19644            is_foldable = true;
19645            match crease {
19646                Crease::Inline { render_toggle, .. } | Crease::Block { render_toggle, .. } => {
19647                    if let Some(render_toggle) = render_toggle {
19648                        let toggle_callback =
19649                            Arc::new(move |folded, window: &mut Window, cx: &mut App| {
19650                                if folded {
19651                                    editor.update(cx, |editor, cx| {
19652                                        editor.fold_at(buffer_row, window, cx)
19653                                    });
19654                                } else {
19655                                    editor.update(cx, |editor, cx| {
19656                                        editor.unfold_at(buffer_row, window, cx)
19657                                    });
19658                                }
19659                            });
19660                        return Some((render_toggle)(
19661                            buffer_row,
19662                            folded,
19663                            toggle_callback,
19664                            window,
19665                            cx,
19666                        ));
19667                    }
19668                }
19669            }
19670        }
19671
19672        is_foldable |= self.starts_indent(buffer_row);
19673
19674        if folded || (is_foldable && (row_contains_cursor || self.gutter_hovered)) {
19675            Some(
19676                Disclosure::new(("gutter_crease", buffer_row.0), !folded)
19677                    .toggle_state(folded)
19678                    .on_click(window.listener_for(&editor, move |this, _e, window, cx| {
19679                        if folded {
19680                            this.unfold_at(buffer_row, window, cx);
19681                        } else {
19682                            this.fold_at(buffer_row, window, cx);
19683                        }
19684                    }))
19685                    .into_any_element(),
19686            )
19687        } else {
19688            None
19689        }
19690    }
19691
19692    pub fn render_crease_trailer(
19693        &self,
19694        buffer_row: MultiBufferRow,
19695        window: &mut Window,
19696        cx: &mut App,
19697    ) -> Option<AnyElement> {
19698        let folded = self.is_line_folded(buffer_row);
19699        if let Crease::Inline { render_trailer, .. } = self
19700            .crease_snapshot
19701            .query_row(buffer_row, &self.buffer_snapshot)?
19702        {
19703            let render_trailer = render_trailer.as_ref()?;
19704            Some(render_trailer(buffer_row, folded, window, cx))
19705        } else {
19706            None
19707        }
19708    }
19709}
19710
19711impl Deref for EditorSnapshot {
19712    type Target = DisplaySnapshot;
19713
19714    fn deref(&self) -> &Self::Target {
19715        &self.display_snapshot
19716    }
19717}
19718
19719#[derive(Clone, Debug, PartialEq, Eq)]
19720pub enum EditorEvent {
19721    InputIgnored {
19722        text: Arc<str>,
19723    },
19724    InputHandled {
19725        utf16_range_to_replace: Option<Range<isize>>,
19726        text: Arc<str>,
19727    },
19728    ExcerptsAdded {
19729        buffer: Entity<Buffer>,
19730        predecessor: ExcerptId,
19731        excerpts: Vec<(ExcerptId, ExcerptRange<language::Anchor>)>,
19732    },
19733    ExcerptsRemoved {
19734        ids: Vec<ExcerptId>,
19735    },
19736    BufferFoldToggled {
19737        ids: Vec<ExcerptId>,
19738        folded: bool,
19739    },
19740    ExcerptsEdited {
19741        ids: Vec<ExcerptId>,
19742    },
19743    ExcerptsExpanded {
19744        ids: Vec<ExcerptId>,
19745    },
19746    BufferEdited,
19747    Edited {
19748        transaction_id: clock::Lamport,
19749    },
19750    Reparsed(BufferId),
19751    Focused,
19752    FocusedIn,
19753    Blurred,
19754    DirtyChanged,
19755    Saved,
19756    TitleChanged,
19757    DiffBaseChanged,
19758    SelectionsChanged {
19759        local: bool,
19760    },
19761    ScrollPositionChanged {
19762        local: bool,
19763        autoscroll: bool,
19764    },
19765    Closed,
19766    TransactionUndone {
19767        transaction_id: clock::Lamport,
19768    },
19769    TransactionBegun {
19770        transaction_id: clock::Lamport,
19771    },
19772    Reloaded,
19773    CursorShapeChanged,
19774    PushedToNavHistory {
19775        anchor: Anchor,
19776        is_deactivate: bool,
19777    },
19778}
19779
19780impl EventEmitter<EditorEvent> for Editor {}
19781
19782impl Focusable for Editor {
19783    fn focus_handle(&self, _cx: &App) -> FocusHandle {
19784        self.focus_handle.clone()
19785    }
19786}
19787
19788impl Render for Editor {
19789    fn render(&mut self, _: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
19790        let settings = ThemeSettings::get_global(cx);
19791
19792        let mut text_style = match self.mode {
19793            EditorMode::SingleLine { .. } | EditorMode::AutoHeight { .. } => TextStyle {
19794                color: cx.theme().colors().editor_foreground,
19795                font_family: settings.ui_font.family.clone(),
19796                font_features: settings.ui_font.features.clone(),
19797                font_fallbacks: settings.ui_font.fallbacks.clone(),
19798                font_size: rems(0.875).into(),
19799                font_weight: settings.ui_font.weight,
19800                line_height: relative(settings.buffer_line_height.value()),
19801                ..Default::default()
19802            },
19803            EditorMode::Full { .. } => TextStyle {
19804                color: cx.theme().colors().editor_foreground,
19805                font_family: settings.buffer_font.family.clone(),
19806                font_features: settings.buffer_font.features.clone(),
19807                font_fallbacks: settings.buffer_font.fallbacks.clone(),
19808                font_size: settings.buffer_font_size(cx).into(),
19809                font_weight: settings.buffer_font.weight,
19810                line_height: relative(settings.buffer_line_height.value()),
19811                ..Default::default()
19812            },
19813        };
19814        if let Some(text_style_refinement) = &self.text_style_refinement {
19815            text_style.refine(text_style_refinement)
19816        }
19817
19818        let background = match self.mode {
19819            EditorMode::SingleLine { .. } => cx.theme().system().transparent,
19820            EditorMode::AutoHeight { max_lines: _ } => cx.theme().system().transparent,
19821            EditorMode::Full { .. } => cx.theme().colors().editor_background,
19822        };
19823
19824        EditorElement::new(
19825            &cx.entity(),
19826            EditorStyle {
19827                background,
19828                local_player: cx.theme().players().local(),
19829                text: text_style,
19830                scrollbar_width: EditorElement::SCROLLBAR_WIDTH,
19831                syntax: cx.theme().syntax().clone(),
19832                status: cx.theme().status().clone(),
19833                inlay_hints_style: make_inlay_hints_style(cx),
19834                inline_completion_styles: make_suggestion_styles(cx),
19835                unnecessary_code_fade: ThemeSettings::get_global(cx).unnecessary_code_fade,
19836            },
19837        )
19838    }
19839}
19840
19841impl EntityInputHandler for Editor {
19842    fn text_for_range(
19843        &mut self,
19844        range_utf16: Range<usize>,
19845        adjusted_range: &mut Option<Range<usize>>,
19846        _: &mut Window,
19847        cx: &mut Context<Self>,
19848    ) -> Option<String> {
19849        let snapshot = self.buffer.read(cx).read(cx);
19850        let start = snapshot.clip_offset_utf16(OffsetUtf16(range_utf16.start), Bias::Left);
19851        let end = snapshot.clip_offset_utf16(OffsetUtf16(range_utf16.end), Bias::Right);
19852        if (start.0..end.0) != range_utf16 {
19853            adjusted_range.replace(start.0..end.0);
19854        }
19855        Some(snapshot.text_for_range(start..end).collect())
19856    }
19857
19858    fn selected_text_range(
19859        &mut self,
19860        ignore_disabled_input: bool,
19861        _: &mut Window,
19862        cx: &mut Context<Self>,
19863    ) -> Option<UTF16Selection> {
19864        // Prevent the IME menu from appearing when holding down an alphabetic key
19865        // while input is disabled.
19866        if !ignore_disabled_input && !self.input_enabled {
19867            return None;
19868        }
19869
19870        let selection = self.selections.newest::<OffsetUtf16>(cx);
19871        let range = selection.range();
19872
19873        Some(UTF16Selection {
19874            range: range.start.0..range.end.0,
19875            reversed: selection.reversed,
19876        })
19877    }
19878
19879    fn marked_text_range(&self, _: &mut Window, cx: &mut Context<Self>) -> Option<Range<usize>> {
19880        let snapshot = self.buffer.read(cx).read(cx);
19881        let range = self.text_highlights::<InputComposition>(cx)?.1.first()?;
19882        Some(range.start.to_offset_utf16(&snapshot).0..range.end.to_offset_utf16(&snapshot).0)
19883    }
19884
19885    fn unmark_text(&mut self, _: &mut Window, cx: &mut Context<Self>) {
19886        self.clear_highlights::<InputComposition>(cx);
19887        self.ime_transaction.take();
19888    }
19889
19890    fn replace_text_in_range(
19891        &mut self,
19892        range_utf16: Option<Range<usize>>,
19893        text: &str,
19894        window: &mut Window,
19895        cx: &mut Context<Self>,
19896    ) {
19897        if !self.input_enabled {
19898            cx.emit(EditorEvent::InputIgnored { text: text.into() });
19899            return;
19900        }
19901
19902        self.transact(window, cx, |this, window, cx| {
19903            let new_selected_ranges = if let Some(range_utf16) = range_utf16 {
19904                let range_utf16 = OffsetUtf16(range_utf16.start)..OffsetUtf16(range_utf16.end);
19905                Some(this.selection_replacement_ranges(range_utf16, cx))
19906            } else {
19907                this.marked_text_ranges(cx)
19908            };
19909
19910            let range_to_replace = new_selected_ranges.as_ref().and_then(|ranges_to_replace| {
19911                let newest_selection_id = this.selections.newest_anchor().id;
19912                this.selections
19913                    .all::<OffsetUtf16>(cx)
19914                    .iter()
19915                    .zip(ranges_to_replace.iter())
19916                    .find_map(|(selection, range)| {
19917                        if selection.id == newest_selection_id {
19918                            Some(
19919                                (range.start.0 as isize - selection.head().0 as isize)
19920                                    ..(range.end.0 as isize - selection.head().0 as isize),
19921                            )
19922                        } else {
19923                            None
19924                        }
19925                    })
19926            });
19927
19928            cx.emit(EditorEvent::InputHandled {
19929                utf16_range_to_replace: range_to_replace,
19930                text: text.into(),
19931            });
19932
19933            if let Some(new_selected_ranges) = new_selected_ranges {
19934                this.change_selections(None, window, cx, |selections| {
19935                    selections.select_ranges(new_selected_ranges)
19936                });
19937                this.backspace(&Default::default(), window, cx);
19938            }
19939
19940            this.handle_input(text, window, cx);
19941        });
19942
19943        if let Some(transaction) = self.ime_transaction {
19944            self.buffer.update(cx, |buffer, cx| {
19945                buffer.group_until_transaction(transaction, cx);
19946            });
19947        }
19948
19949        self.unmark_text(window, cx);
19950    }
19951
19952    fn replace_and_mark_text_in_range(
19953        &mut self,
19954        range_utf16: Option<Range<usize>>,
19955        text: &str,
19956        new_selected_range_utf16: Option<Range<usize>>,
19957        window: &mut Window,
19958        cx: &mut Context<Self>,
19959    ) {
19960        if !self.input_enabled {
19961            return;
19962        }
19963
19964        let transaction = self.transact(window, cx, |this, window, cx| {
19965            let ranges_to_replace = if let Some(mut marked_ranges) = this.marked_text_ranges(cx) {
19966                let snapshot = this.buffer.read(cx).read(cx);
19967                if let Some(relative_range_utf16) = range_utf16.as_ref() {
19968                    for marked_range in &mut marked_ranges {
19969                        marked_range.end.0 = marked_range.start.0 + relative_range_utf16.end;
19970                        marked_range.start.0 += relative_range_utf16.start;
19971                        marked_range.start =
19972                            snapshot.clip_offset_utf16(marked_range.start, Bias::Left);
19973                        marked_range.end =
19974                            snapshot.clip_offset_utf16(marked_range.end, Bias::Right);
19975                    }
19976                }
19977                Some(marked_ranges)
19978            } else if let Some(range_utf16) = range_utf16 {
19979                let range_utf16 = OffsetUtf16(range_utf16.start)..OffsetUtf16(range_utf16.end);
19980                Some(this.selection_replacement_ranges(range_utf16, cx))
19981            } else {
19982                None
19983            };
19984
19985            let range_to_replace = ranges_to_replace.as_ref().and_then(|ranges_to_replace| {
19986                let newest_selection_id = this.selections.newest_anchor().id;
19987                this.selections
19988                    .all::<OffsetUtf16>(cx)
19989                    .iter()
19990                    .zip(ranges_to_replace.iter())
19991                    .find_map(|(selection, range)| {
19992                        if selection.id == newest_selection_id {
19993                            Some(
19994                                (range.start.0 as isize - selection.head().0 as isize)
19995                                    ..(range.end.0 as isize - selection.head().0 as isize),
19996                            )
19997                        } else {
19998                            None
19999                        }
20000                    })
20001            });
20002
20003            cx.emit(EditorEvent::InputHandled {
20004                utf16_range_to_replace: range_to_replace,
20005                text: text.into(),
20006            });
20007
20008            if let Some(ranges) = ranges_to_replace {
20009                this.change_selections(None, window, cx, |s| s.select_ranges(ranges));
20010            }
20011
20012            let marked_ranges = {
20013                let snapshot = this.buffer.read(cx).read(cx);
20014                this.selections
20015                    .disjoint_anchors()
20016                    .iter()
20017                    .map(|selection| {
20018                        selection.start.bias_left(&snapshot)..selection.end.bias_right(&snapshot)
20019                    })
20020                    .collect::<Vec<_>>()
20021            };
20022
20023            if text.is_empty() {
20024                this.unmark_text(window, cx);
20025            } else {
20026                this.highlight_text::<InputComposition>(
20027                    marked_ranges.clone(),
20028                    HighlightStyle {
20029                        underline: Some(UnderlineStyle {
20030                            thickness: px(1.),
20031                            color: None,
20032                            wavy: false,
20033                        }),
20034                        ..Default::default()
20035                    },
20036                    cx,
20037                );
20038            }
20039
20040            // Disable auto-closing when composing text (i.e. typing a `"` on a Brazilian keyboard)
20041            let use_autoclose = this.use_autoclose;
20042            let use_auto_surround = this.use_auto_surround;
20043            this.set_use_autoclose(false);
20044            this.set_use_auto_surround(false);
20045            this.handle_input(text, window, cx);
20046            this.set_use_autoclose(use_autoclose);
20047            this.set_use_auto_surround(use_auto_surround);
20048
20049            if let Some(new_selected_range) = new_selected_range_utf16 {
20050                let snapshot = this.buffer.read(cx).read(cx);
20051                let new_selected_ranges = marked_ranges
20052                    .into_iter()
20053                    .map(|marked_range| {
20054                        let insertion_start = marked_range.start.to_offset_utf16(&snapshot).0;
20055                        let new_start = OffsetUtf16(new_selected_range.start + insertion_start);
20056                        let new_end = OffsetUtf16(new_selected_range.end + insertion_start);
20057                        snapshot.clip_offset_utf16(new_start, Bias::Left)
20058                            ..snapshot.clip_offset_utf16(new_end, Bias::Right)
20059                    })
20060                    .collect::<Vec<_>>();
20061
20062                drop(snapshot);
20063                this.change_selections(None, window, cx, |selections| {
20064                    selections.select_ranges(new_selected_ranges)
20065                });
20066            }
20067        });
20068
20069        self.ime_transaction = self.ime_transaction.or(transaction);
20070        if let Some(transaction) = self.ime_transaction {
20071            self.buffer.update(cx, |buffer, cx| {
20072                buffer.group_until_transaction(transaction, cx);
20073            });
20074        }
20075
20076        if self.text_highlights::<InputComposition>(cx).is_none() {
20077            self.ime_transaction.take();
20078        }
20079    }
20080
20081    fn bounds_for_range(
20082        &mut self,
20083        range_utf16: Range<usize>,
20084        element_bounds: gpui::Bounds<Pixels>,
20085        window: &mut Window,
20086        cx: &mut Context<Self>,
20087    ) -> Option<gpui::Bounds<Pixels>> {
20088        let text_layout_details = self.text_layout_details(window);
20089        let gpui::Size {
20090            width: em_width,
20091            height: line_height,
20092        } = self.character_size(window);
20093
20094        let snapshot = self.snapshot(window, cx);
20095        let scroll_position = snapshot.scroll_position();
20096        let scroll_left = scroll_position.x * em_width;
20097
20098        let start = OffsetUtf16(range_utf16.start).to_display_point(&snapshot);
20099        let x = snapshot.x_for_display_point(start, &text_layout_details) - scroll_left
20100            + self.gutter_dimensions.width
20101            + self.gutter_dimensions.margin;
20102        let y = line_height * (start.row().as_f32() - scroll_position.y);
20103
20104        Some(Bounds {
20105            origin: element_bounds.origin + point(x, y),
20106            size: size(em_width, line_height),
20107        })
20108    }
20109
20110    fn character_index_for_point(
20111        &mut self,
20112        point: gpui::Point<Pixels>,
20113        _window: &mut Window,
20114        _cx: &mut Context<Self>,
20115    ) -> Option<usize> {
20116        let position_map = self.last_position_map.as_ref()?;
20117        if !position_map.text_hitbox.contains(&point) {
20118            return None;
20119        }
20120        let display_point = position_map.point_for_position(point).previous_valid;
20121        let anchor = position_map
20122            .snapshot
20123            .display_point_to_anchor(display_point, Bias::Left);
20124        let utf16_offset = anchor.to_offset_utf16(&position_map.snapshot.buffer_snapshot);
20125        Some(utf16_offset.0)
20126    }
20127}
20128
20129trait SelectionExt {
20130    fn display_range(&self, map: &DisplaySnapshot) -> Range<DisplayPoint>;
20131    fn spanned_rows(
20132        &self,
20133        include_end_if_at_line_start: bool,
20134        map: &DisplaySnapshot,
20135    ) -> Range<MultiBufferRow>;
20136}
20137
20138impl<T: ToPoint + ToOffset> SelectionExt for Selection<T> {
20139    fn display_range(&self, map: &DisplaySnapshot) -> Range<DisplayPoint> {
20140        let start = self
20141            .start
20142            .to_point(&map.buffer_snapshot)
20143            .to_display_point(map);
20144        let end = self
20145            .end
20146            .to_point(&map.buffer_snapshot)
20147            .to_display_point(map);
20148        if self.reversed {
20149            end..start
20150        } else {
20151            start..end
20152        }
20153    }
20154
20155    fn spanned_rows(
20156        &self,
20157        include_end_if_at_line_start: bool,
20158        map: &DisplaySnapshot,
20159    ) -> Range<MultiBufferRow> {
20160        let start = self.start.to_point(&map.buffer_snapshot);
20161        let mut end = self.end.to_point(&map.buffer_snapshot);
20162        if !include_end_if_at_line_start && start.row != end.row && end.column == 0 {
20163            end.row -= 1;
20164        }
20165
20166        let buffer_start = map.prev_line_boundary(start).0;
20167        let buffer_end = map.next_line_boundary(end).0;
20168        MultiBufferRow(buffer_start.row)..MultiBufferRow(buffer_end.row + 1)
20169    }
20170}
20171
20172impl<T: InvalidationRegion> InvalidationStack<T> {
20173    fn invalidate<S>(&mut self, selections: &[Selection<S>], buffer: &MultiBufferSnapshot)
20174    where
20175        S: Clone + ToOffset,
20176    {
20177        while let Some(region) = self.last() {
20178            let all_selections_inside_invalidation_ranges =
20179                if selections.len() == region.ranges().len() {
20180                    selections
20181                        .iter()
20182                        .zip(region.ranges().iter().map(|r| r.to_offset(buffer)))
20183                        .all(|(selection, invalidation_range)| {
20184                            let head = selection.head().to_offset(buffer);
20185                            invalidation_range.start <= head && invalidation_range.end >= head
20186                        })
20187                } else {
20188                    false
20189                };
20190
20191            if all_selections_inside_invalidation_ranges {
20192                break;
20193            } else {
20194                self.pop();
20195            }
20196        }
20197    }
20198}
20199
20200impl<T> Default for InvalidationStack<T> {
20201    fn default() -> Self {
20202        Self(Default::default())
20203    }
20204}
20205
20206impl<T> Deref for InvalidationStack<T> {
20207    type Target = Vec<T>;
20208
20209    fn deref(&self) -> &Self::Target {
20210        &self.0
20211    }
20212}
20213
20214impl<T> DerefMut for InvalidationStack<T> {
20215    fn deref_mut(&mut self) -> &mut Self::Target {
20216        &mut self.0
20217    }
20218}
20219
20220impl InvalidationRegion for SnippetState {
20221    fn ranges(&self) -> &[Range<Anchor>] {
20222        &self.ranges[self.active_index]
20223    }
20224}
20225
20226fn inline_completion_edit_text(
20227    current_snapshot: &BufferSnapshot,
20228    edits: &[(Range<Anchor>, String)],
20229    edit_preview: &EditPreview,
20230    include_deletions: bool,
20231    cx: &App,
20232) -> HighlightedText {
20233    let edits = edits
20234        .iter()
20235        .map(|(anchor, text)| {
20236            (
20237                anchor.start.text_anchor..anchor.end.text_anchor,
20238                text.clone(),
20239            )
20240        })
20241        .collect::<Vec<_>>();
20242
20243    edit_preview.highlight_edits(current_snapshot, &edits, include_deletions, cx)
20244}
20245
20246pub fn diagnostic_style(severity: DiagnosticSeverity, colors: &StatusColors) -> Hsla {
20247    match severity {
20248        DiagnosticSeverity::ERROR => colors.error,
20249        DiagnosticSeverity::WARNING => colors.warning,
20250        DiagnosticSeverity::INFORMATION => colors.info,
20251        DiagnosticSeverity::HINT => colors.info,
20252        _ => colors.ignored,
20253    }
20254}
20255
20256pub fn styled_runs_for_code_label<'a>(
20257    label: &'a CodeLabel,
20258    syntax_theme: &'a theme::SyntaxTheme,
20259) -> impl 'a + Iterator<Item = (Range<usize>, HighlightStyle)> {
20260    let fade_out = HighlightStyle {
20261        fade_out: Some(0.35),
20262        ..Default::default()
20263    };
20264
20265    let mut prev_end = label.filter_range.end;
20266    label
20267        .runs
20268        .iter()
20269        .enumerate()
20270        .flat_map(move |(ix, (range, highlight_id))| {
20271            let style = if let Some(style) = highlight_id.style(syntax_theme) {
20272                style
20273            } else {
20274                return Default::default();
20275            };
20276            let mut muted_style = style;
20277            muted_style.highlight(fade_out);
20278
20279            let mut runs = SmallVec::<[(Range<usize>, HighlightStyle); 3]>::new();
20280            if range.start >= label.filter_range.end {
20281                if range.start > prev_end {
20282                    runs.push((prev_end..range.start, fade_out));
20283                }
20284                runs.push((range.clone(), muted_style));
20285            } else if range.end <= label.filter_range.end {
20286                runs.push((range.clone(), style));
20287            } else {
20288                runs.push((range.start..label.filter_range.end, style));
20289                runs.push((label.filter_range.end..range.end, muted_style));
20290            }
20291            prev_end = cmp::max(prev_end, range.end);
20292
20293            if ix + 1 == label.runs.len() && label.text.len() > prev_end {
20294                runs.push((prev_end..label.text.len(), fade_out));
20295            }
20296
20297            runs
20298        })
20299}
20300
20301pub(crate) fn split_words(text: &str) -> impl std::iter::Iterator<Item = &str> + '_ {
20302    let mut prev_index = 0;
20303    let mut prev_codepoint: Option<char> = None;
20304    text.char_indices()
20305        .chain([(text.len(), '\0')])
20306        .filter_map(move |(index, codepoint)| {
20307            let prev_codepoint = prev_codepoint.replace(codepoint)?;
20308            let is_boundary = index == text.len()
20309                || !prev_codepoint.is_uppercase() && codepoint.is_uppercase()
20310                || !prev_codepoint.is_alphanumeric() && codepoint.is_alphanumeric();
20311            if is_boundary {
20312                let chunk = &text[prev_index..index];
20313                prev_index = index;
20314                Some(chunk)
20315            } else {
20316                None
20317            }
20318        })
20319}
20320
20321pub trait RangeToAnchorExt: Sized {
20322    fn to_anchors(self, snapshot: &MultiBufferSnapshot) -> Range<Anchor>;
20323
20324    fn to_display_points(self, snapshot: &EditorSnapshot) -> Range<DisplayPoint> {
20325        let anchor_range = self.to_anchors(&snapshot.buffer_snapshot);
20326        anchor_range.start.to_display_point(snapshot)..anchor_range.end.to_display_point(snapshot)
20327    }
20328}
20329
20330impl<T: ToOffset> RangeToAnchorExt for Range<T> {
20331    fn to_anchors(self, snapshot: &MultiBufferSnapshot) -> Range<Anchor> {
20332        let start_offset = self.start.to_offset(snapshot);
20333        let end_offset = self.end.to_offset(snapshot);
20334        if start_offset == end_offset {
20335            snapshot.anchor_before(start_offset)..snapshot.anchor_before(end_offset)
20336        } else {
20337            snapshot.anchor_after(self.start)..snapshot.anchor_before(self.end)
20338        }
20339    }
20340}
20341
20342pub trait RowExt {
20343    fn as_f32(&self) -> f32;
20344
20345    fn next_row(&self) -> Self;
20346
20347    fn previous_row(&self) -> Self;
20348
20349    fn minus(&self, other: Self) -> u32;
20350}
20351
20352impl RowExt for DisplayRow {
20353    fn as_f32(&self) -> f32 {
20354        self.0 as f32
20355    }
20356
20357    fn next_row(&self) -> Self {
20358        Self(self.0 + 1)
20359    }
20360
20361    fn previous_row(&self) -> Self {
20362        Self(self.0.saturating_sub(1))
20363    }
20364
20365    fn minus(&self, other: Self) -> u32 {
20366        self.0 - other.0
20367    }
20368}
20369
20370impl RowExt for MultiBufferRow {
20371    fn as_f32(&self) -> f32 {
20372        self.0 as f32
20373    }
20374
20375    fn next_row(&self) -> Self {
20376        Self(self.0 + 1)
20377    }
20378
20379    fn previous_row(&self) -> Self {
20380        Self(self.0.saturating_sub(1))
20381    }
20382
20383    fn minus(&self, other: Self) -> u32 {
20384        self.0 - other.0
20385    }
20386}
20387
20388trait RowRangeExt {
20389    type Row;
20390
20391    fn len(&self) -> usize;
20392
20393    fn iter_rows(&self) -> impl DoubleEndedIterator<Item = Self::Row>;
20394}
20395
20396impl RowRangeExt for Range<MultiBufferRow> {
20397    type Row = MultiBufferRow;
20398
20399    fn len(&self) -> usize {
20400        (self.end.0 - self.start.0) as usize
20401    }
20402
20403    fn iter_rows(&self) -> impl DoubleEndedIterator<Item = MultiBufferRow> {
20404        (self.start.0..self.end.0).map(MultiBufferRow)
20405    }
20406}
20407
20408impl RowRangeExt for Range<DisplayRow> {
20409    type Row = DisplayRow;
20410
20411    fn len(&self) -> usize {
20412        (self.end.0 - self.start.0) as usize
20413    }
20414
20415    fn iter_rows(&self) -> impl DoubleEndedIterator<Item = DisplayRow> {
20416        (self.start.0..self.end.0).map(DisplayRow)
20417    }
20418}
20419
20420/// If select range has more than one line, we
20421/// just point the cursor to range.start.
20422fn collapse_multiline_range(range: Range<Point>) -> Range<Point> {
20423    if range.start.row == range.end.row {
20424        range
20425    } else {
20426        range.start..range.start
20427    }
20428}
20429pub struct KillRing(ClipboardItem);
20430impl Global for KillRing {}
20431
20432const UPDATE_DEBOUNCE: Duration = Duration::from_millis(50);
20433
20434enum BreakpointPromptEditAction {
20435    Log,
20436    Condition,
20437    HitCondition,
20438}
20439
20440struct BreakpointPromptEditor {
20441    pub(crate) prompt: Entity<Editor>,
20442    editor: WeakEntity<Editor>,
20443    breakpoint_anchor: Anchor,
20444    breakpoint: Breakpoint,
20445    edit_action: BreakpointPromptEditAction,
20446    block_ids: HashSet<CustomBlockId>,
20447    gutter_dimensions: Arc<Mutex<GutterDimensions>>,
20448    _subscriptions: Vec<Subscription>,
20449}
20450
20451impl BreakpointPromptEditor {
20452    const MAX_LINES: u8 = 4;
20453
20454    fn new(
20455        editor: WeakEntity<Editor>,
20456        breakpoint_anchor: Anchor,
20457        breakpoint: Breakpoint,
20458        edit_action: BreakpointPromptEditAction,
20459        window: &mut Window,
20460        cx: &mut Context<Self>,
20461    ) -> Self {
20462        let base_text = match edit_action {
20463            BreakpointPromptEditAction::Log => breakpoint.message.as_ref(),
20464            BreakpointPromptEditAction::Condition => breakpoint.condition.as_ref(),
20465            BreakpointPromptEditAction::HitCondition => breakpoint.hit_condition.as_ref(),
20466        }
20467        .map(|msg| msg.to_string())
20468        .unwrap_or_default();
20469
20470        let buffer = cx.new(|cx| Buffer::local(base_text, cx));
20471        let buffer = cx.new(|cx| MultiBuffer::singleton(buffer, cx));
20472
20473        let prompt = cx.new(|cx| {
20474            let mut prompt = Editor::new(
20475                EditorMode::AutoHeight {
20476                    max_lines: Self::MAX_LINES as usize,
20477                },
20478                buffer,
20479                None,
20480                window,
20481                cx,
20482            );
20483            prompt.set_soft_wrap_mode(language::language_settings::SoftWrap::EditorWidth, cx);
20484            prompt.set_show_cursor_when_unfocused(false, cx);
20485            prompt.set_placeholder_text(
20486                match edit_action {
20487                    BreakpointPromptEditAction::Log => "Message to log when a breakpoint is hit. Expressions within {} are interpolated.",
20488                    BreakpointPromptEditAction::Condition => "Condition when a breakpoint is hit. Expressions within {} are interpolated.",
20489                    BreakpointPromptEditAction::HitCondition => "How many breakpoint hits to ignore",
20490                },
20491                cx,
20492            );
20493
20494            prompt
20495        });
20496
20497        Self {
20498            prompt,
20499            editor,
20500            breakpoint_anchor,
20501            breakpoint,
20502            edit_action,
20503            gutter_dimensions: Arc::new(Mutex::new(GutterDimensions::default())),
20504            block_ids: Default::default(),
20505            _subscriptions: vec![],
20506        }
20507    }
20508
20509    pub(crate) fn add_block_ids(&mut self, block_ids: Vec<CustomBlockId>) {
20510        self.block_ids.extend(block_ids)
20511    }
20512
20513    fn confirm(&mut self, _: &menu::Confirm, window: &mut Window, cx: &mut Context<Self>) {
20514        if let Some(editor) = self.editor.upgrade() {
20515            let message = self
20516                .prompt
20517                .read(cx)
20518                .buffer
20519                .read(cx)
20520                .as_singleton()
20521                .expect("A multi buffer in breakpoint prompt isn't possible")
20522                .read(cx)
20523                .as_rope()
20524                .to_string();
20525
20526            editor.update(cx, |editor, cx| {
20527                editor.edit_breakpoint_at_anchor(
20528                    self.breakpoint_anchor,
20529                    self.breakpoint.clone(),
20530                    match self.edit_action {
20531                        BreakpointPromptEditAction::Log => {
20532                            BreakpointEditAction::EditLogMessage(message.into())
20533                        }
20534                        BreakpointPromptEditAction::Condition => {
20535                            BreakpointEditAction::EditCondition(message.into())
20536                        }
20537                        BreakpointPromptEditAction::HitCondition => {
20538                            BreakpointEditAction::EditHitCondition(message.into())
20539                        }
20540                    },
20541                    cx,
20542                );
20543
20544                editor.remove_blocks(self.block_ids.clone(), None, cx);
20545                cx.focus_self(window);
20546            });
20547        }
20548    }
20549
20550    fn cancel(&mut self, _: &menu::Cancel, window: &mut Window, cx: &mut Context<Self>) {
20551        self.editor
20552            .update(cx, |editor, cx| {
20553                editor.remove_blocks(self.block_ids.clone(), None, cx);
20554                window.focus(&editor.focus_handle);
20555            })
20556            .log_err();
20557    }
20558
20559    fn render_prompt_editor(&self, cx: &mut Context<Self>) -> impl IntoElement {
20560        let settings = ThemeSettings::get_global(cx);
20561        let text_style = TextStyle {
20562            color: if self.prompt.read(cx).read_only(cx) {
20563                cx.theme().colors().text_disabled
20564            } else {
20565                cx.theme().colors().text
20566            },
20567            font_family: settings.buffer_font.family.clone(),
20568            font_fallbacks: settings.buffer_font.fallbacks.clone(),
20569            font_size: settings.buffer_font_size(cx).into(),
20570            font_weight: settings.buffer_font.weight,
20571            line_height: relative(settings.buffer_line_height.value()),
20572            ..Default::default()
20573        };
20574        EditorElement::new(
20575            &self.prompt,
20576            EditorStyle {
20577                background: cx.theme().colors().editor_background,
20578                local_player: cx.theme().players().local(),
20579                text: text_style,
20580                ..Default::default()
20581            },
20582        )
20583    }
20584}
20585
20586impl Render for BreakpointPromptEditor {
20587    fn render(&mut self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
20588        let gutter_dimensions = *self.gutter_dimensions.lock();
20589        h_flex()
20590            .key_context("Editor")
20591            .bg(cx.theme().colors().editor_background)
20592            .border_y_1()
20593            .border_color(cx.theme().status().info_border)
20594            .size_full()
20595            .py(window.line_height() / 2.5)
20596            .on_action(cx.listener(Self::confirm))
20597            .on_action(cx.listener(Self::cancel))
20598            .child(h_flex().w(gutter_dimensions.full_width() + (gutter_dimensions.margin / 2.0)))
20599            .child(div().flex_1().child(self.render_prompt_editor(cx)))
20600    }
20601}
20602
20603impl Focusable for BreakpointPromptEditor {
20604    fn focus_handle(&self, cx: &App) -> FocusHandle {
20605        self.prompt.focus_handle(cx)
20606    }
20607}
20608
20609fn all_edits_insertions_or_deletions(
20610    edits: &Vec<(Range<Anchor>, String)>,
20611    snapshot: &MultiBufferSnapshot,
20612) -> bool {
20613    let mut all_insertions = true;
20614    let mut all_deletions = true;
20615
20616    for (range, new_text) in edits.iter() {
20617        let range_is_empty = range.to_offset(&snapshot).is_empty();
20618        let text_is_empty = new_text.is_empty();
20619
20620        if range_is_empty != text_is_empty {
20621            if range_is_empty {
20622                all_deletions = false;
20623            } else {
20624                all_insertions = false;
20625            }
20626        } else {
20627            return false;
20628        }
20629
20630        if !all_insertions && !all_deletions {
20631            return false;
20632        }
20633    }
20634    all_insertions || all_deletions
20635}
20636
20637struct MissingEditPredictionKeybindingTooltip;
20638
20639impl Render for MissingEditPredictionKeybindingTooltip {
20640    fn render(&mut self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
20641        ui::tooltip_container(window, cx, |container, _, cx| {
20642            container
20643                .flex_shrink_0()
20644                .max_w_80()
20645                .min_h(rems_from_px(124.))
20646                .justify_between()
20647                .child(
20648                    v_flex()
20649                        .flex_1()
20650                        .text_ui_sm(cx)
20651                        .child(Label::new("Conflict with Accept Keybinding"))
20652                        .child("Your keymap currently overrides the default accept keybinding. To continue, assign one keybinding for the `editor::AcceptEditPrediction` action.")
20653                )
20654                .child(
20655                    h_flex()
20656                        .pb_1()
20657                        .gap_1()
20658                        .items_end()
20659                        .w_full()
20660                        .child(Button::new("open-keymap", "Assign Keybinding").size(ButtonSize::Compact).on_click(|_ev, window, cx| {
20661                            window.dispatch_action(zed_actions::OpenKeymap.boxed_clone(), cx)
20662                        }))
20663                        .child(Button::new("see-docs", "See Docs").size(ButtonSize::Compact).on_click(|_ev, _window, cx| {
20664                            cx.open_url("https://zed.dev/docs/completions#edit-predictions-missing-keybinding");
20665                        })),
20666                )
20667        })
20668    }
20669}
20670
20671#[derive(Debug, Clone, Copy, PartialEq)]
20672pub struct LineHighlight {
20673    pub background: Background,
20674    pub border: Option<gpui::Hsla>,
20675}
20676
20677impl From<Hsla> for LineHighlight {
20678    fn from(hsla: Hsla) -> Self {
20679        Self {
20680            background: hsla.into(),
20681            border: None,
20682        }
20683    }
20684}
20685
20686impl From<Background> for LineHighlight {
20687    fn from(background: Background) -> Self {
20688        Self {
20689            background,
20690            border: None,
20691        }
20692    }
20693}
20694
20695fn render_diff_hunk_controls(
20696    row: u32,
20697    status: &DiffHunkStatus,
20698    hunk_range: Range<Anchor>,
20699    is_created_file: bool,
20700    line_height: Pixels,
20701    editor: &Entity<Editor>,
20702    _window: &mut Window,
20703    cx: &mut App,
20704) -> AnyElement {
20705    h_flex()
20706        .h(line_height)
20707        .mr_1()
20708        .gap_1()
20709        .px_0p5()
20710        .pb_1()
20711        .border_x_1()
20712        .border_b_1()
20713        .border_color(cx.theme().colors().border_variant)
20714        .rounded_b_lg()
20715        .bg(cx.theme().colors().editor_background)
20716        .gap_1()
20717        .occlude()
20718        .shadow_md()
20719        .child(if status.has_secondary_hunk() {
20720            Button::new(("stage", row as u64), "Stage")
20721                .alpha(if status.is_pending() { 0.66 } else { 1.0 })
20722                .tooltip({
20723                    let focus_handle = editor.focus_handle(cx);
20724                    move |window, cx| {
20725                        Tooltip::for_action_in(
20726                            "Stage Hunk",
20727                            &::git::ToggleStaged,
20728                            &focus_handle,
20729                            window,
20730                            cx,
20731                        )
20732                    }
20733                })
20734                .on_click({
20735                    let editor = editor.clone();
20736                    move |_event, _window, cx| {
20737                        editor.update(cx, |editor, cx| {
20738                            editor.stage_or_unstage_diff_hunks(
20739                                true,
20740                                vec![hunk_range.start..hunk_range.start],
20741                                cx,
20742                            );
20743                        });
20744                    }
20745                })
20746        } else {
20747            Button::new(("unstage", row as u64), "Unstage")
20748                .alpha(if status.is_pending() { 0.66 } else { 1.0 })
20749                .tooltip({
20750                    let focus_handle = editor.focus_handle(cx);
20751                    move |window, cx| {
20752                        Tooltip::for_action_in(
20753                            "Unstage Hunk",
20754                            &::git::ToggleStaged,
20755                            &focus_handle,
20756                            window,
20757                            cx,
20758                        )
20759                    }
20760                })
20761                .on_click({
20762                    let editor = editor.clone();
20763                    move |_event, _window, cx| {
20764                        editor.update(cx, |editor, cx| {
20765                            editor.stage_or_unstage_diff_hunks(
20766                                false,
20767                                vec![hunk_range.start..hunk_range.start],
20768                                cx,
20769                            );
20770                        });
20771                    }
20772                })
20773        })
20774        .child(
20775            Button::new(("restore", row as u64), "Restore")
20776                .tooltip({
20777                    let focus_handle = editor.focus_handle(cx);
20778                    move |window, cx| {
20779                        Tooltip::for_action_in(
20780                            "Restore Hunk",
20781                            &::git::Restore,
20782                            &focus_handle,
20783                            window,
20784                            cx,
20785                        )
20786                    }
20787                })
20788                .on_click({
20789                    let editor = editor.clone();
20790                    move |_event, window, cx| {
20791                        editor.update(cx, |editor, cx| {
20792                            let snapshot = editor.snapshot(window, cx);
20793                            let point = hunk_range.start.to_point(&snapshot.buffer_snapshot);
20794                            editor.restore_hunks_in_ranges(vec![point..point], window, cx);
20795                        });
20796                    }
20797                })
20798                .disabled(is_created_file),
20799        )
20800        .when(
20801            !editor.read(cx).buffer().read(cx).all_diff_hunks_expanded(),
20802            |el| {
20803                el.child(
20804                    IconButton::new(("next-hunk", row as u64), IconName::ArrowDown)
20805                        .shape(IconButtonShape::Square)
20806                        .icon_size(IconSize::Small)
20807                        // .disabled(!has_multiple_hunks)
20808                        .tooltip({
20809                            let focus_handle = editor.focus_handle(cx);
20810                            move |window, cx| {
20811                                Tooltip::for_action_in(
20812                                    "Next Hunk",
20813                                    &GoToHunk,
20814                                    &focus_handle,
20815                                    window,
20816                                    cx,
20817                                )
20818                            }
20819                        })
20820                        .on_click({
20821                            let editor = editor.clone();
20822                            move |_event, window, cx| {
20823                                editor.update(cx, |editor, cx| {
20824                                    let snapshot = editor.snapshot(window, cx);
20825                                    let position =
20826                                        hunk_range.end.to_point(&snapshot.buffer_snapshot);
20827                                    editor.go_to_hunk_before_or_after_position(
20828                                        &snapshot,
20829                                        position,
20830                                        Direction::Next,
20831                                        window,
20832                                        cx,
20833                                    );
20834                                    editor.expand_selected_diff_hunks(cx);
20835                                });
20836                            }
20837                        }),
20838                )
20839                .child(
20840                    IconButton::new(("prev-hunk", row as u64), IconName::ArrowUp)
20841                        .shape(IconButtonShape::Square)
20842                        .icon_size(IconSize::Small)
20843                        // .disabled(!has_multiple_hunks)
20844                        .tooltip({
20845                            let focus_handle = editor.focus_handle(cx);
20846                            move |window, cx| {
20847                                Tooltip::for_action_in(
20848                                    "Previous Hunk",
20849                                    &GoToPreviousHunk,
20850                                    &focus_handle,
20851                                    window,
20852                                    cx,
20853                                )
20854                            }
20855                        })
20856                        .on_click({
20857                            let editor = editor.clone();
20858                            move |_event, window, cx| {
20859                                editor.update(cx, |editor, cx| {
20860                                    let snapshot = editor.snapshot(window, cx);
20861                                    let point =
20862                                        hunk_range.start.to_point(&snapshot.buffer_snapshot);
20863                                    editor.go_to_hunk_before_or_after_position(
20864                                        &snapshot,
20865                                        point,
20866                                        Direction::Prev,
20867                                        window,
20868                                        cx,
20869                                    );
20870                                    editor.expand_selected_diff_hunks(cx);
20871                                });
20872                            }
20873                        }),
20874                )
20875            },
20876        )
20877        .into_any_element()
20878}