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 editor_tests;
   44#[cfg(test)]
   45mod inline_completion_tests;
   46mod signature_help;
   47#[cfg(any(test, feature = "test-support"))]
   48pub mod test;
   49
   50pub(crate) use actions::*;
   51pub use actions::{AcceptEditPrediction, OpenExcerpts, OpenExcerptsSplit};
   52use aho_corasick::AhoCorasick;
   53use anyhow::{Context as _, Result, anyhow};
   54use blink_manager::BlinkManager;
   55use buffer_diff::DiffHunkStatus;
   56use client::{Collaborator, ParticipantIndex};
   57use clock::ReplicaId;
   58use collections::{BTreeMap, HashMap, HashSet, VecDeque};
   59use convert_case::{Case, Casing};
   60use display_map::*;
   61pub use display_map::{ChunkRenderer, ChunkRendererContext, DisplayPoint, FoldPlaceholder};
   62use editor_settings::GoToDefinitionFallback;
   63pub use editor_settings::{
   64    CurrentLineHighlight, EditorSettings, HideMouseMode, ScrollBeyondLastLine, SearchSettings,
   65    ShowScrollbar,
   66};
   67pub use editor_settings_controls::*;
   68use element::{AcceptEditPredictionBinding, LineWithInvisibles, PositionMap, layout_line};
   69pub use element::{
   70    CursorLayout, EditorElement, HighlightedRange, HighlightedRangeLine, PointForPosition,
   71};
   72use feature_flags::{Debugger, FeatureFlagAppExt};
   73use futures::{
   74    FutureExt,
   75    future::{self, Shared, join},
   76};
   77use fuzzy::StringMatchCandidate;
   78
   79use ::git::Restore;
   80use code_context_menus::{
   81    AvailableCodeAction, CodeActionContents, CodeActionsItem, CodeActionsMenu, CodeContextMenu,
   82    CompletionsMenu, ContextMenuOrigin,
   83};
   84use git::blame::{GitBlame, GlobalBlameRenderer};
   85use gpui::{
   86    Action, Animation, AnimationExt, AnyElement, AnyWeakEntity, App, AppContext,
   87    AsyncWindowContext, AvailableSpace, Background, Bounds, ClickEvent, ClipboardEntry,
   88    ClipboardItem, Context, DispatchPhase, Edges, Entity, EntityInputHandler, EventEmitter,
   89    FocusHandle, FocusOutEvent, Focusable, FontId, FontWeight, Global, HighlightStyle, Hsla,
   90    KeyContext, Modifiers, MouseButton, MouseDownEvent, PaintQuad, ParentElement, Pixels, Render,
   91    SharedString, Size, Stateful, Styled, Subscription, Task, TextStyle, TextStyleRefinement,
   92    UTF16Selection, UnderlineStyle, UniformListScrollHandle, WeakEntity, WeakFocusHandle, Window,
   93    div, impl_actions, point, prelude::*, pulsating_between, px, relative, size,
   94};
   95use highlight_matching_bracket::refresh_matching_bracket_highlights;
   96use hover_links::{HoverLink, HoveredLinkState, InlayHighlight, find_file};
   97pub use hover_popover::hover_markdown_style;
   98use hover_popover::{HoverState, hide_hover};
   99use indent_guides::ActiveIndentGuidesState;
  100use inlay_hint_cache::{InlayHintCache, InlaySplice, InvalidationStrategy};
  101pub use inline_completion::Direction;
  102use inline_completion::{EditPredictionProvider, InlineCompletionProviderHandle};
  103pub use items::MAX_TAB_TITLE_LEN;
  104use itertools::Itertools;
  105use language::{
  106    AutoindentMode, BracketMatch, BracketPair, Buffer, Capability, CharKind, CodeLabel,
  107    CursorShape, DiagnosticEntry, DiffOptions, EditPredictionsMode, EditPreview, HighlightedText,
  108    IndentKind, IndentSize, Language, OffsetRangeExt, Point, Selection, SelectionGoal, TextObject,
  109    TransactionId, TreeSitterOptions, WordsQuery,
  110    language_settings::{
  111        self, InlayHintSettings, LspInsertMode, RewrapBehavior, WordsCompletionMode,
  112        all_language_settings, language_settings,
  113    },
  114    point_from_lsp, text_diff_with_options,
  115};
  116use language::{BufferRow, CharClassifier, Runnable, RunnableRange, point_to_lsp};
  117use linked_editing_ranges::refresh_linked_ranges;
  118use mouse_context_menu::MouseContextMenu;
  119use persistence::DB;
  120use project::{
  121    ProjectPath,
  122    debugger::breakpoint_store::{
  123        BreakpointEditAction, BreakpointState, BreakpointStore, BreakpointStoreEvent,
  124    },
  125};
  126
  127pub use git::blame::BlameRenderer;
  128pub use proposed_changes_editor::{
  129    ProposedChangeLocation, ProposedChangesEditor, ProposedChangesEditorToolbar,
  130};
  131use smallvec::smallvec;
  132use std::{cell::OnceCell, iter::Peekable};
  133use task::{ResolvedTask, RunnableTag, TaskTemplate, TaskVariables};
  134
  135pub use lsp::CompletionContext;
  136use lsp::{
  137    CodeActionKind, CompletionItemKind, CompletionTriggerKind, DiagnosticSeverity,
  138    InsertTextFormat, InsertTextMode, LanguageServerId, LanguageServerName,
  139};
  140
  141use language::BufferSnapshot;
  142pub use lsp_ext::lsp_tasks;
  143use movement::TextLayoutDetails;
  144pub use multi_buffer::{
  145    Anchor, AnchorRangeExt, ExcerptId, ExcerptRange, MultiBuffer, MultiBufferSnapshot, PathKey,
  146    RowInfo, ToOffset, ToPoint,
  147};
  148use multi_buffer::{
  149    ExcerptInfo, ExpandExcerptDirection, MultiBufferDiffHunk, MultiBufferPoint, MultiBufferRow,
  150    MultiOrSingleBufferOffsetRange, ToOffsetUtf16,
  151};
  152use parking_lot::Mutex;
  153use project::{
  154    CodeAction, Completion, CompletionIntent, CompletionSource, DocumentHighlight, InlayHint,
  155    Location, LocationLink, PrepareRenameResponse, Project, ProjectItem, ProjectTransaction,
  156    TaskSourceKind,
  157    debugger::breakpoint_store::Breakpoint,
  158    lsp_store::{CompletionDocumentation, FormatTrigger, LspFormatTarget, OpenLspBufferHandle},
  159    project_settings::{GitGutterSetting, ProjectSettings},
  160};
  161use rand::prelude::*;
  162use rpc::{ErrorExt, proto::*};
  163use scroll::{Autoscroll, OngoingScroll, ScrollAnchor, ScrollManager, ScrollbarAutoHide};
  164use selections_collection::{
  165    MutableSelectionsCollection, SelectionsCollection, resolve_selections,
  166};
  167use serde::{Deserialize, Serialize};
  168use settings::{Settings, SettingsLocation, SettingsStore, update_settings_file};
  169use smallvec::SmallVec;
  170use snippet::Snippet;
  171use std::sync::Arc;
  172use std::{
  173    any::TypeId,
  174    borrow::Cow,
  175    cell::RefCell,
  176    cmp::{self, Ordering, Reverse},
  177    mem,
  178    num::NonZeroU32,
  179    ops::{ControlFlow, Deref, DerefMut, Not as _, Range, RangeInclusive},
  180    path::{Path, PathBuf},
  181    rc::Rc,
  182    time::{Duration, Instant},
  183};
  184pub use sum_tree::Bias;
  185use sum_tree::TreeMap;
  186use text::{BufferId, FromAnchor, OffsetUtf16, Rope};
  187use theme::{
  188    ActiveTheme, PlayerColor, StatusColors, SyntaxTheme, ThemeColors, ThemeSettings,
  189    observe_buffer_font_size_adjustment,
  190};
  191use ui::{
  192    ButtonSize, ButtonStyle, ContextMenu, Disclosure, IconButton, IconButtonShape, IconName,
  193    IconSize, Key, Tooltip, h_flex, prelude::*,
  194};
  195use util::{RangeExt, ResultExt, TryFutureExt, maybe, post_inc};
  196use workspace::{
  197    Item as WorkspaceItem, ItemId, ItemNavHistory, OpenInTerminal, OpenTerminal,
  198    RestoreOnStartupBehavior, SERIALIZATION_THROTTLE_TIME, SplitDirection, TabBarSettings, Toast,
  199    ViewId, Workspace, WorkspaceId, WorkspaceSettings,
  200    item::{ItemHandle, PreviewTabsSettings},
  201    notifications::{DetachAndPromptErr, NotificationId, NotifyTaskExt},
  202    searchable::SearchEvent,
  203};
  204
  205use crate::hover_links::{find_url, find_url_from_range};
  206use crate::signature_help::{SignatureHelpHiddenBy, SignatureHelpState};
  207
  208pub const FILE_HEADER_HEIGHT: u32 = 2;
  209pub const MULTI_BUFFER_EXCERPT_HEADER_HEIGHT: u32 = 1;
  210pub const DEFAULT_MULTIBUFFER_CONTEXT: u32 = 2;
  211const CURSOR_BLINK_INTERVAL: Duration = Duration::from_millis(500);
  212const MAX_LINE_LEN: usize = 1024;
  213const MIN_NAVIGATION_HISTORY_ROW_DELTA: i64 = 10;
  214const MAX_SELECTION_HISTORY_LEN: usize = 1024;
  215pub(crate) const CURSORS_VISIBLE_FOR: Duration = Duration::from_millis(2000);
  216#[doc(hidden)]
  217pub const CODE_ACTIONS_DEBOUNCE_TIMEOUT: Duration = Duration::from_millis(250);
  218
  219pub(crate) const CODE_ACTION_TIMEOUT: Duration = Duration::from_secs(5);
  220pub(crate) const FORMAT_TIMEOUT: Duration = Duration::from_secs(5);
  221pub(crate) const SCROLL_CENTER_TOP_BOTTOM_DEBOUNCE_TIMEOUT: Duration = Duration::from_secs(1);
  222
  223pub(crate) const EDIT_PREDICTION_KEY_CONTEXT: &str = "edit_prediction";
  224pub(crate) const EDIT_PREDICTION_CONFLICT_KEY_CONTEXT: &str = "edit_prediction_conflict";
  225pub(crate) const MIN_LINE_NUMBER_DIGITS: u32 = 4;
  226
  227pub type RenderDiffHunkControlsFn = Arc<
  228    dyn Fn(
  229        u32,
  230        &DiffHunkStatus,
  231        Range<Anchor>,
  232        bool,
  233        Pixels,
  234        &Entity<Editor>,
  235        &mut Window,
  236        &mut App,
  237    ) -> AnyElement,
  238>;
  239
  240const COLUMNAR_SELECTION_MODIFIERS: Modifiers = Modifiers {
  241    alt: true,
  242    shift: true,
  243    control: false,
  244    platform: false,
  245    function: false,
  246};
  247
  248#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
  249pub enum InlayId {
  250    InlineCompletion(usize),
  251    Hint(usize),
  252}
  253
  254impl InlayId {
  255    fn id(&self) -> usize {
  256        match self {
  257            Self::InlineCompletion(id) => *id,
  258            Self::Hint(id) => *id,
  259        }
  260    }
  261}
  262
  263pub enum DebugCurrentRowHighlight {}
  264enum DocumentHighlightRead {}
  265enum DocumentHighlightWrite {}
  266enum InputComposition {}
  267enum SelectedTextHighlight {}
  268
  269#[derive(Debug, Copy, Clone, PartialEq, Eq)]
  270pub enum Navigated {
  271    Yes,
  272    No,
  273}
  274
  275impl Navigated {
  276    pub fn from_bool(yes: bool) -> Navigated {
  277        if yes { Navigated::Yes } else { Navigated::No }
  278    }
  279}
  280
  281#[derive(Debug, Clone, PartialEq, Eq)]
  282enum DisplayDiffHunk {
  283    Folded {
  284        display_row: DisplayRow,
  285    },
  286    Unfolded {
  287        is_created_file: bool,
  288        diff_base_byte_range: Range<usize>,
  289        display_row_range: Range<DisplayRow>,
  290        multi_buffer_range: Range<Anchor>,
  291        status: DiffHunkStatus,
  292    },
  293}
  294
  295pub enum HideMouseCursorOrigin {
  296    TypingAction,
  297    MovementAction,
  298}
  299
  300pub fn init_settings(cx: &mut App) {
  301    EditorSettings::register(cx);
  302}
  303
  304pub fn init(cx: &mut App) {
  305    init_settings(cx);
  306
  307    cx.set_global(GlobalBlameRenderer(Arc::new(())));
  308
  309    workspace::register_project_item::<Editor>(cx);
  310    workspace::FollowableViewRegistry::register::<Editor>(cx);
  311    workspace::register_serializable_item::<Editor>(cx);
  312
  313    cx.observe_new(
  314        |workspace: &mut Workspace, _: Option<&mut Window>, _cx: &mut Context<Workspace>| {
  315            workspace.register_action(Editor::new_file);
  316            workspace.register_action(Editor::new_file_vertical);
  317            workspace.register_action(Editor::new_file_horizontal);
  318            workspace.register_action(Editor::cancel_language_server_work);
  319        },
  320    )
  321    .detach();
  322
  323    cx.on_action(move |_: &workspace::NewFile, cx| {
  324        let app_state = workspace::AppState::global(cx);
  325        if let Some(app_state) = app_state.upgrade() {
  326            workspace::open_new(
  327                Default::default(),
  328                app_state,
  329                cx,
  330                |workspace, window, cx| {
  331                    Editor::new_file(workspace, &Default::default(), window, cx)
  332                },
  333            )
  334            .detach();
  335        }
  336    });
  337    cx.on_action(move |_: &workspace::NewWindow, cx| {
  338        let app_state = workspace::AppState::global(cx);
  339        if let Some(app_state) = app_state.upgrade() {
  340            workspace::open_new(
  341                Default::default(),
  342                app_state,
  343                cx,
  344                |workspace, window, cx| {
  345                    cx.activate(true);
  346                    Editor::new_file(workspace, &Default::default(), window, cx)
  347                },
  348            )
  349            .detach();
  350        }
  351    });
  352}
  353
  354pub fn set_blame_renderer(renderer: impl BlameRenderer + 'static, cx: &mut App) {
  355    cx.set_global(GlobalBlameRenderer(Arc::new(renderer)));
  356}
  357
  358pub trait DiagnosticRenderer {
  359    fn render_group(
  360        &self,
  361        diagnostic_group: Vec<DiagnosticEntry<Point>>,
  362        buffer_id: BufferId,
  363        snapshot: EditorSnapshot,
  364        editor: WeakEntity<Editor>,
  365        cx: &mut App,
  366    ) -> Vec<BlockProperties<Anchor>>;
  367}
  368
  369pub(crate) struct GlobalDiagnosticRenderer(pub Arc<dyn DiagnosticRenderer>);
  370
  371impl gpui::Global for GlobalDiagnosticRenderer {}
  372pub fn set_diagnostic_renderer(renderer: impl DiagnosticRenderer + 'static, cx: &mut App) {
  373    cx.set_global(GlobalDiagnosticRenderer(Arc::new(renderer)));
  374}
  375
  376pub struct SearchWithinRange;
  377
  378trait InvalidationRegion {
  379    fn ranges(&self) -> &[Range<Anchor>];
  380}
  381
  382#[derive(Clone, Debug, PartialEq)]
  383pub enum SelectPhase {
  384    Begin {
  385        position: DisplayPoint,
  386        add: bool,
  387        click_count: usize,
  388    },
  389    BeginColumnar {
  390        position: DisplayPoint,
  391        reset: bool,
  392        goal_column: u32,
  393    },
  394    Extend {
  395        position: DisplayPoint,
  396        click_count: usize,
  397    },
  398    Update {
  399        position: DisplayPoint,
  400        goal_column: u32,
  401        scroll_delta: gpui::Point<f32>,
  402    },
  403    End,
  404}
  405
  406#[derive(Clone, Debug)]
  407pub enum SelectMode {
  408    Character,
  409    Word(Range<Anchor>),
  410    Line(Range<Anchor>),
  411    All,
  412}
  413
  414#[derive(Copy, Clone, PartialEq, Eq, Debug)]
  415pub enum EditorMode {
  416    SingleLine {
  417        auto_width: bool,
  418    },
  419    AutoHeight {
  420        max_lines: usize,
  421    },
  422    Full {
  423        /// When set to `true`, the editor will scale its UI elements with the buffer font size.
  424        scale_ui_elements_with_buffer_font_size: bool,
  425        /// When set to `true`, the editor will render a background for the active line.
  426        show_active_line_background: bool,
  427    },
  428}
  429
  430impl EditorMode {
  431    pub fn full() -> Self {
  432        Self::Full {
  433            scale_ui_elements_with_buffer_font_size: true,
  434            show_active_line_background: true,
  435        }
  436    }
  437
  438    pub fn is_full(&self) -> bool {
  439        matches!(self, Self::Full { .. })
  440    }
  441}
  442
  443#[derive(Copy, Clone, Debug)]
  444pub enum SoftWrap {
  445    /// Prefer not to wrap at all.
  446    ///
  447    /// Note: this is currently internal, as actually limited by [`crate::MAX_LINE_LEN`] until it wraps.
  448    /// The mode is used inside git diff hunks, where it's seems currently more useful to not wrap as much as possible.
  449    GitDiff,
  450    /// Prefer a single line generally, unless an overly long line is encountered.
  451    None,
  452    /// Soft wrap lines that exceed the editor width.
  453    EditorWidth,
  454    /// Soft wrap lines at the preferred line length.
  455    Column(u32),
  456    /// Soft wrap line at the preferred line length or the editor width (whichever is smaller).
  457    Bounded(u32),
  458}
  459
  460#[derive(Clone)]
  461pub struct EditorStyle {
  462    pub background: Hsla,
  463    pub local_player: PlayerColor,
  464    pub text: TextStyle,
  465    pub scrollbar_width: Pixels,
  466    pub syntax: Arc<SyntaxTheme>,
  467    pub status: StatusColors,
  468    pub inlay_hints_style: HighlightStyle,
  469    pub inline_completion_styles: InlineCompletionStyles,
  470    pub unnecessary_code_fade: f32,
  471}
  472
  473impl Default for EditorStyle {
  474    fn default() -> Self {
  475        Self {
  476            background: Hsla::default(),
  477            local_player: PlayerColor::default(),
  478            text: TextStyle::default(),
  479            scrollbar_width: Pixels::default(),
  480            syntax: Default::default(),
  481            // HACK: Status colors don't have a real default.
  482            // We should look into removing the status colors from the editor
  483            // style and retrieve them directly from the theme.
  484            status: StatusColors::dark(),
  485            inlay_hints_style: HighlightStyle::default(),
  486            inline_completion_styles: InlineCompletionStyles {
  487                insertion: HighlightStyle::default(),
  488                whitespace: HighlightStyle::default(),
  489            },
  490            unnecessary_code_fade: Default::default(),
  491        }
  492    }
  493}
  494
  495pub fn make_inlay_hints_style(cx: &mut App) -> HighlightStyle {
  496    let show_background = language_settings::language_settings(None, None, cx)
  497        .inlay_hints
  498        .show_background;
  499
  500    HighlightStyle {
  501        color: Some(cx.theme().status().hint),
  502        background_color: show_background.then(|| cx.theme().status().hint_background),
  503        ..HighlightStyle::default()
  504    }
  505}
  506
  507pub fn make_suggestion_styles(cx: &mut App) -> InlineCompletionStyles {
  508    InlineCompletionStyles {
  509        insertion: HighlightStyle {
  510            color: Some(cx.theme().status().predictive),
  511            ..HighlightStyle::default()
  512        },
  513        whitespace: HighlightStyle {
  514            background_color: Some(cx.theme().status().created_background),
  515            ..HighlightStyle::default()
  516        },
  517    }
  518}
  519
  520type CompletionId = usize;
  521
  522pub(crate) enum EditDisplayMode {
  523    TabAccept,
  524    DiffPopover,
  525    Inline,
  526}
  527
  528enum InlineCompletion {
  529    Edit {
  530        edits: Vec<(Range<Anchor>, String)>,
  531        edit_preview: Option<EditPreview>,
  532        display_mode: EditDisplayMode,
  533        snapshot: BufferSnapshot,
  534    },
  535    Move {
  536        target: Anchor,
  537        snapshot: BufferSnapshot,
  538    },
  539}
  540
  541struct InlineCompletionState {
  542    inlay_ids: Vec<InlayId>,
  543    completion: InlineCompletion,
  544    completion_id: Option<SharedString>,
  545    invalidation_range: Range<Anchor>,
  546}
  547
  548enum EditPredictionSettings {
  549    Disabled,
  550    Enabled {
  551        show_in_menu: bool,
  552        preview_requires_modifier: bool,
  553    },
  554}
  555
  556enum InlineCompletionHighlight {}
  557
  558#[derive(Debug, Clone)]
  559struct InlineDiagnostic {
  560    message: SharedString,
  561    group_id: usize,
  562    is_primary: bool,
  563    start: Point,
  564    severity: DiagnosticSeverity,
  565}
  566
  567pub enum MenuInlineCompletionsPolicy {
  568    Never,
  569    ByProvider,
  570}
  571
  572pub enum EditPredictionPreview {
  573    /// Modifier is not pressed
  574    Inactive { released_too_fast: bool },
  575    /// Modifier pressed
  576    Active {
  577        since: Instant,
  578        previous_scroll_position: Option<ScrollAnchor>,
  579    },
  580}
  581
  582impl EditPredictionPreview {
  583    pub fn released_too_fast(&self) -> bool {
  584        match self {
  585            EditPredictionPreview::Inactive { released_too_fast } => *released_too_fast,
  586            EditPredictionPreview::Active { .. } => false,
  587        }
  588    }
  589
  590    pub fn set_previous_scroll_position(&mut self, scroll_position: Option<ScrollAnchor>) {
  591        if let EditPredictionPreview::Active {
  592            previous_scroll_position,
  593            ..
  594        } = self
  595        {
  596            *previous_scroll_position = scroll_position;
  597        }
  598    }
  599}
  600
  601pub struct ContextMenuOptions {
  602    pub min_entries_visible: usize,
  603    pub max_entries_visible: usize,
  604    pub placement: Option<ContextMenuPlacement>,
  605}
  606
  607#[derive(Debug, Clone, PartialEq, Eq)]
  608pub enum ContextMenuPlacement {
  609    Above,
  610    Below,
  611}
  612
  613#[derive(Copy, Clone, Eq, PartialEq, PartialOrd, Ord, Debug, Default)]
  614struct EditorActionId(usize);
  615
  616impl EditorActionId {
  617    pub fn post_inc(&mut self) -> Self {
  618        let answer = self.0;
  619
  620        *self = Self(answer + 1);
  621
  622        Self(answer)
  623    }
  624}
  625
  626// type GetFieldEditorTheme = dyn Fn(&theme::Theme) -> theme::FieldEditor;
  627// type OverrideTextStyle = dyn Fn(&EditorStyle) -> Option<HighlightStyle>;
  628
  629type BackgroundHighlight = (fn(&ThemeColors) -> Hsla, Arc<[Range<Anchor>]>);
  630type GutterHighlight = (fn(&App) -> Hsla, Arc<[Range<Anchor>]>);
  631
  632#[derive(Default)]
  633struct ScrollbarMarkerState {
  634    scrollbar_size: Size<Pixels>,
  635    dirty: bool,
  636    markers: Arc<[PaintQuad]>,
  637    pending_refresh: Option<Task<Result<()>>>,
  638}
  639
  640impl ScrollbarMarkerState {
  641    fn should_refresh(&self, scrollbar_size: Size<Pixels>) -> bool {
  642        self.pending_refresh.is_none() && (self.scrollbar_size != scrollbar_size || self.dirty)
  643    }
  644}
  645
  646#[derive(Clone, Debug)]
  647struct RunnableTasks {
  648    templates: Vec<(TaskSourceKind, TaskTemplate)>,
  649    offset: multi_buffer::Anchor,
  650    // We need the column at which the task context evaluation should take place (when we're spawning it via gutter).
  651    column: u32,
  652    // Values of all named captures, including those starting with '_'
  653    extra_variables: HashMap<String, String>,
  654    // Full range of the tagged region. We use it to determine which `extra_variables` to grab for context resolution in e.g. a modal.
  655    context_range: Range<BufferOffset>,
  656}
  657
  658impl RunnableTasks {
  659    fn resolve<'a>(
  660        &'a self,
  661        cx: &'a task::TaskContext,
  662    ) -> impl Iterator<Item = (TaskSourceKind, ResolvedTask)> + 'a {
  663        self.templates.iter().filter_map(|(kind, template)| {
  664            template
  665                .resolve_task(&kind.to_id_base(), cx)
  666                .map(|task| (kind.clone(), task))
  667        })
  668    }
  669}
  670
  671#[derive(Clone)]
  672struct ResolvedTasks {
  673    templates: SmallVec<[(TaskSourceKind, ResolvedTask); 1]>,
  674    position: Anchor,
  675}
  676
  677#[derive(Copy, Clone, Debug, PartialEq, PartialOrd)]
  678struct BufferOffset(usize);
  679
  680// Addons allow storing per-editor state in other crates (e.g. Vim)
  681pub trait Addon: 'static {
  682    fn extend_key_context(&self, _: &mut KeyContext, _: &App) {}
  683
  684    fn render_buffer_header_controls(
  685        &self,
  686        _: &ExcerptInfo,
  687        _: &Window,
  688        _: &App,
  689    ) -> Option<AnyElement> {
  690        None
  691    }
  692
  693    fn to_any(&self) -> &dyn std::any::Any;
  694}
  695
  696/// A set of caret positions, registered when the editor was edited.
  697pub struct ChangeList {
  698    changes: Vec<Vec<Anchor>>,
  699    /// Currently "selected" change.
  700    position: Option<usize>,
  701}
  702
  703impl ChangeList {
  704    pub fn new() -> Self {
  705        Self {
  706            changes: Vec::new(),
  707            position: None,
  708        }
  709    }
  710
  711    /// Moves to the next change in the list (based on the direction given) and returns the caret positions for the next change.
  712    /// If reaches the end of the list in the direction, returns the corresponding change until called for a different direction.
  713    pub fn next_change(&mut self, count: usize, direction: Direction) -> Option<&[Anchor]> {
  714        if self.changes.is_empty() {
  715            return None;
  716        }
  717
  718        let prev = self.position.unwrap_or(self.changes.len());
  719        let next = if direction == Direction::Prev {
  720            prev.saturating_sub(count)
  721        } else {
  722            (prev + count).min(self.changes.len() - 1)
  723        };
  724        self.position = Some(next);
  725        self.changes.get(next).map(|anchors| anchors.as_slice())
  726    }
  727
  728    /// Adds a new change to the list, resetting the change list position.
  729    pub fn push_to_change_list(&mut self, pop_state: bool, new_positions: Vec<Anchor>) {
  730        self.position.take();
  731        if pop_state {
  732            self.changes.pop();
  733        }
  734        self.changes.push(new_positions.clone());
  735    }
  736
  737    pub fn last(&self) -> Option<&[Anchor]> {
  738        self.changes.last().map(|anchors| anchors.as_slice())
  739    }
  740}
  741
  742/// Zed's primary implementation of text input, allowing users to edit a [`MultiBuffer`].
  743///
  744/// See the [module level documentation](self) for more information.
  745pub struct Editor {
  746    focus_handle: FocusHandle,
  747    last_focused_descendant: Option<WeakFocusHandle>,
  748    /// The text buffer being edited
  749    buffer: Entity<MultiBuffer>,
  750    /// Map of how text in the buffer should be displayed.
  751    /// Handles soft wraps, folds, fake inlay text insertions, etc.
  752    pub display_map: Entity<DisplayMap>,
  753    pub selections: SelectionsCollection,
  754    pub scroll_manager: ScrollManager,
  755    /// When inline assist editors are linked, they all render cursors because
  756    /// typing enters text into each of them, even the ones that aren't focused.
  757    pub(crate) show_cursor_when_unfocused: bool,
  758    columnar_selection_tail: Option<Anchor>,
  759    add_selections_state: Option<AddSelectionsState>,
  760    select_next_state: Option<SelectNextState>,
  761    select_prev_state: Option<SelectNextState>,
  762    selection_history: SelectionHistory,
  763    autoclose_regions: Vec<AutocloseRegion>,
  764    snippet_stack: InvalidationStack<SnippetState>,
  765    select_syntax_node_history: SelectSyntaxNodeHistory,
  766    ime_transaction: Option<TransactionId>,
  767    active_diagnostics: ActiveDiagnostic,
  768    show_inline_diagnostics: bool,
  769    inline_diagnostics_update: Task<()>,
  770    inline_diagnostics_enabled: bool,
  771    inline_diagnostics: Vec<(Anchor, InlineDiagnostic)>,
  772    soft_wrap_mode_override: Option<language_settings::SoftWrap>,
  773    hard_wrap: Option<usize>,
  774
  775    // TODO: make this a access method
  776    pub project: Option<Entity<Project>>,
  777    semantics_provider: Option<Rc<dyn SemanticsProvider>>,
  778    completion_provider: Option<Box<dyn CompletionProvider>>,
  779    collaboration_hub: Option<Box<dyn CollaborationHub>>,
  780    blink_manager: Entity<BlinkManager>,
  781    show_cursor_names: bool,
  782    hovered_cursors: HashMap<HoveredCursor, Task<()>>,
  783    pub show_local_selections: bool,
  784    mode: EditorMode,
  785    show_breadcrumbs: bool,
  786    show_gutter: bool,
  787    show_scrollbars: bool,
  788    show_line_numbers: Option<bool>,
  789    use_relative_line_numbers: Option<bool>,
  790    show_git_diff_gutter: Option<bool>,
  791    show_code_actions: Option<bool>,
  792    show_runnables: Option<bool>,
  793    show_breakpoints: Option<bool>,
  794    show_wrap_guides: Option<bool>,
  795    show_indent_guides: Option<bool>,
  796    placeholder_text: Option<Arc<str>>,
  797    highlight_order: usize,
  798    highlighted_rows: HashMap<TypeId, Vec<RowHighlight>>,
  799    background_highlights: TreeMap<TypeId, BackgroundHighlight>,
  800    gutter_highlights: TreeMap<TypeId, GutterHighlight>,
  801    scrollbar_marker_state: ScrollbarMarkerState,
  802    active_indent_guides_state: ActiveIndentGuidesState,
  803    nav_history: Option<ItemNavHistory>,
  804    context_menu: RefCell<Option<CodeContextMenu>>,
  805    context_menu_options: Option<ContextMenuOptions>,
  806    mouse_context_menu: Option<MouseContextMenu>,
  807    completion_tasks: Vec<(CompletionId, Task<Option<()>>)>,
  808    signature_help_state: SignatureHelpState,
  809    auto_signature_help: Option<bool>,
  810    find_all_references_task_sources: Vec<Anchor>,
  811    next_completion_id: CompletionId,
  812    available_code_actions: Option<(Location, Rc<[AvailableCodeAction]>)>,
  813    code_actions_task: Option<Task<Result<()>>>,
  814    selection_highlight_task: Option<Task<()>>,
  815    document_highlights_task: Option<Task<()>>,
  816    linked_editing_range_task: Option<Task<Option<()>>>,
  817    linked_edit_ranges: linked_editing_ranges::LinkedEditingRanges,
  818    pending_rename: Option<RenameState>,
  819    searchable: bool,
  820    cursor_shape: CursorShape,
  821    current_line_highlight: Option<CurrentLineHighlight>,
  822    collapse_matches: bool,
  823    autoindent_mode: Option<AutoindentMode>,
  824    workspace: Option<(WeakEntity<Workspace>, Option<WorkspaceId>)>,
  825    input_enabled: bool,
  826    use_modal_editing: bool,
  827    read_only: bool,
  828    leader_peer_id: Option<PeerId>,
  829    remote_id: Option<ViewId>,
  830    hover_state: HoverState,
  831    pending_mouse_down: Option<Rc<RefCell<Option<MouseDownEvent>>>>,
  832    gutter_hovered: bool,
  833    hovered_link_state: Option<HoveredLinkState>,
  834    edit_prediction_provider: Option<RegisteredInlineCompletionProvider>,
  835    code_action_providers: Vec<Rc<dyn CodeActionProvider>>,
  836    active_inline_completion: Option<InlineCompletionState>,
  837    /// Used to prevent flickering as the user types while the menu is open
  838    stale_inline_completion_in_menu: Option<InlineCompletionState>,
  839    edit_prediction_settings: EditPredictionSettings,
  840    inline_completions_hidden_for_vim_mode: bool,
  841    show_inline_completions_override: Option<bool>,
  842    menu_inline_completions_policy: MenuInlineCompletionsPolicy,
  843    edit_prediction_preview: EditPredictionPreview,
  844    edit_prediction_indent_conflict: bool,
  845    edit_prediction_requires_modifier_in_indent_conflict: bool,
  846    inlay_hint_cache: InlayHintCache,
  847    next_inlay_id: usize,
  848    _subscriptions: Vec<Subscription>,
  849    pixel_position_of_newest_cursor: Option<gpui::Point<Pixels>>,
  850    gutter_dimensions: GutterDimensions,
  851    style: Option<EditorStyle>,
  852    text_style_refinement: Option<TextStyleRefinement>,
  853    next_editor_action_id: EditorActionId,
  854    editor_actions:
  855        Rc<RefCell<BTreeMap<EditorActionId, Box<dyn Fn(&mut Window, &mut Context<Self>)>>>>,
  856    use_autoclose: bool,
  857    use_auto_surround: bool,
  858    auto_replace_emoji_shortcode: bool,
  859    jsx_tag_auto_close_enabled_in_any_buffer: bool,
  860    show_git_blame_gutter: bool,
  861    show_git_blame_inline: bool,
  862    show_git_blame_inline_delay_task: Option<Task<()>>,
  863    pub git_blame_inline_tooltip: Option<AnyWeakEntity>,
  864    git_blame_inline_enabled: bool,
  865    render_diff_hunk_controls: RenderDiffHunkControlsFn,
  866    serialize_dirty_buffers: bool,
  867    show_selection_menu: Option<bool>,
  868    blame: Option<Entity<GitBlame>>,
  869    blame_subscription: Option<Subscription>,
  870    custom_context_menu: Option<
  871        Box<
  872            dyn 'static
  873                + Fn(
  874                    &mut Self,
  875                    DisplayPoint,
  876                    &mut Window,
  877                    &mut Context<Self>,
  878                ) -> Option<Entity<ui::ContextMenu>>,
  879        >,
  880    >,
  881    last_bounds: Option<Bounds<Pixels>>,
  882    last_position_map: Option<Rc<PositionMap>>,
  883    expect_bounds_change: Option<Bounds<Pixels>>,
  884    tasks: BTreeMap<(BufferId, BufferRow), RunnableTasks>,
  885    tasks_update_task: Option<Task<()>>,
  886    breakpoint_store: Option<Entity<BreakpointStore>>,
  887    /// Allow's a user to create a breakpoint by selecting this indicator
  888    /// It should be None while a user is not hovering over the gutter
  889    /// Otherwise it represents the point that the breakpoint will be shown
  890    gutter_breakpoint_indicator: (Option<(DisplayPoint, bool)>, Option<Task<()>>),
  891    in_project_search: bool,
  892    previous_search_ranges: Option<Arc<[Range<Anchor>]>>,
  893    breadcrumb_header: Option<String>,
  894    focused_block: Option<FocusedBlock>,
  895    next_scroll_position: NextScrollCursorCenterTopBottom,
  896    addons: HashMap<TypeId, Box<dyn Addon>>,
  897    registered_buffers: HashMap<BufferId, OpenLspBufferHandle>,
  898    load_diff_task: Option<Shared<Task<()>>>,
  899    selection_mark_mode: bool,
  900    toggle_fold_multiple_buffers: Task<()>,
  901    _scroll_cursor_center_top_bottom_task: Task<()>,
  902    serialize_selections: Task<()>,
  903    serialize_folds: Task<()>,
  904    mouse_cursor_hidden: bool,
  905    hide_mouse_mode: HideMouseMode,
  906    pub change_list: ChangeList,
  907}
  908
  909#[derive(Copy, Clone, Debug, PartialEq, Eq, Default)]
  910enum NextScrollCursorCenterTopBottom {
  911    #[default]
  912    Center,
  913    Top,
  914    Bottom,
  915}
  916
  917impl NextScrollCursorCenterTopBottom {
  918    fn next(&self) -> Self {
  919        match self {
  920            Self::Center => Self::Top,
  921            Self::Top => Self::Bottom,
  922            Self::Bottom => Self::Center,
  923        }
  924    }
  925}
  926
  927#[derive(Clone)]
  928pub struct EditorSnapshot {
  929    pub mode: EditorMode,
  930    show_gutter: bool,
  931    show_line_numbers: Option<bool>,
  932    show_git_diff_gutter: Option<bool>,
  933    show_code_actions: Option<bool>,
  934    show_runnables: Option<bool>,
  935    show_breakpoints: Option<bool>,
  936    git_blame_gutter_max_author_length: Option<usize>,
  937    pub display_snapshot: DisplaySnapshot,
  938    pub placeholder_text: Option<Arc<str>>,
  939    is_focused: bool,
  940    scroll_anchor: ScrollAnchor,
  941    ongoing_scroll: OngoingScroll,
  942    current_line_highlight: CurrentLineHighlight,
  943    gutter_hovered: bool,
  944}
  945
  946#[derive(Default, Debug, Clone, Copy)]
  947pub struct GutterDimensions {
  948    pub left_padding: Pixels,
  949    pub right_padding: Pixels,
  950    pub width: Pixels,
  951    pub margin: Pixels,
  952    pub git_blame_entries_width: Option<Pixels>,
  953}
  954
  955impl GutterDimensions {
  956    /// The full width of the space taken up by the gutter.
  957    pub fn full_width(&self) -> Pixels {
  958        self.margin + self.width
  959    }
  960
  961    /// The width of the space reserved for the fold indicators,
  962    /// use alongside 'justify_end' and `gutter_width` to
  963    /// right align content with the line numbers
  964    pub fn fold_area_width(&self) -> Pixels {
  965        self.margin + self.right_padding
  966    }
  967}
  968
  969#[derive(Debug)]
  970pub struct RemoteSelection {
  971    pub replica_id: ReplicaId,
  972    pub selection: Selection<Anchor>,
  973    pub cursor_shape: CursorShape,
  974    pub peer_id: PeerId,
  975    pub line_mode: bool,
  976    pub participant_index: Option<ParticipantIndex>,
  977    pub user_name: Option<SharedString>,
  978}
  979
  980#[derive(Clone, Debug)]
  981struct SelectionHistoryEntry {
  982    selections: Arc<[Selection<Anchor>]>,
  983    select_next_state: Option<SelectNextState>,
  984    select_prev_state: Option<SelectNextState>,
  985    add_selections_state: Option<AddSelectionsState>,
  986}
  987
  988enum SelectionHistoryMode {
  989    Normal,
  990    Undoing,
  991    Redoing,
  992}
  993
  994#[derive(Clone, PartialEq, Eq, Hash)]
  995struct HoveredCursor {
  996    replica_id: u16,
  997    selection_id: usize,
  998}
  999
 1000impl Default for SelectionHistoryMode {
 1001    fn default() -> Self {
 1002        Self::Normal
 1003    }
 1004}
 1005
 1006#[derive(Default)]
 1007struct SelectionHistory {
 1008    #[allow(clippy::type_complexity)]
 1009    selections_by_transaction:
 1010        HashMap<TransactionId, (Arc<[Selection<Anchor>]>, Option<Arc<[Selection<Anchor>]>>)>,
 1011    mode: SelectionHistoryMode,
 1012    undo_stack: VecDeque<SelectionHistoryEntry>,
 1013    redo_stack: VecDeque<SelectionHistoryEntry>,
 1014}
 1015
 1016impl SelectionHistory {
 1017    fn insert_transaction(
 1018        &mut self,
 1019        transaction_id: TransactionId,
 1020        selections: Arc<[Selection<Anchor>]>,
 1021    ) {
 1022        self.selections_by_transaction
 1023            .insert(transaction_id, (selections, None));
 1024    }
 1025
 1026    #[allow(clippy::type_complexity)]
 1027    fn transaction(
 1028        &self,
 1029        transaction_id: TransactionId,
 1030    ) -> Option<&(Arc<[Selection<Anchor>]>, Option<Arc<[Selection<Anchor>]>>)> {
 1031        self.selections_by_transaction.get(&transaction_id)
 1032    }
 1033
 1034    #[allow(clippy::type_complexity)]
 1035    fn transaction_mut(
 1036        &mut self,
 1037        transaction_id: TransactionId,
 1038    ) -> Option<&mut (Arc<[Selection<Anchor>]>, Option<Arc<[Selection<Anchor>]>>)> {
 1039        self.selections_by_transaction.get_mut(&transaction_id)
 1040    }
 1041
 1042    fn push(&mut self, entry: SelectionHistoryEntry) {
 1043        if !entry.selections.is_empty() {
 1044            match self.mode {
 1045                SelectionHistoryMode::Normal => {
 1046                    self.push_undo(entry);
 1047                    self.redo_stack.clear();
 1048                }
 1049                SelectionHistoryMode::Undoing => self.push_redo(entry),
 1050                SelectionHistoryMode::Redoing => self.push_undo(entry),
 1051            }
 1052        }
 1053    }
 1054
 1055    fn push_undo(&mut self, entry: SelectionHistoryEntry) {
 1056        if self
 1057            .undo_stack
 1058            .back()
 1059            .map_or(true, |e| e.selections != entry.selections)
 1060        {
 1061            self.undo_stack.push_back(entry);
 1062            if self.undo_stack.len() > MAX_SELECTION_HISTORY_LEN {
 1063                self.undo_stack.pop_front();
 1064            }
 1065        }
 1066    }
 1067
 1068    fn push_redo(&mut self, entry: SelectionHistoryEntry) {
 1069        if self
 1070            .redo_stack
 1071            .back()
 1072            .map_or(true, |e| e.selections != entry.selections)
 1073        {
 1074            self.redo_stack.push_back(entry);
 1075            if self.redo_stack.len() > MAX_SELECTION_HISTORY_LEN {
 1076                self.redo_stack.pop_front();
 1077            }
 1078        }
 1079    }
 1080}
 1081
 1082struct RowHighlight {
 1083    index: usize,
 1084    range: Range<Anchor>,
 1085    color: Hsla,
 1086    should_autoscroll: bool,
 1087}
 1088
 1089#[derive(Clone, Debug)]
 1090struct AddSelectionsState {
 1091    above: bool,
 1092    stack: Vec<usize>,
 1093}
 1094
 1095#[derive(Clone)]
 1096struct SelectNextState {
 1097    query: AhoCorasick,
 1098    wordwise: bool,
 1099    done: bool,
 1100}
 1101
 1102impl std::fmt::Debug for SelectNextState {
 1103    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
 1104        f.debug_struct(std::any::type_name::<Self>())
 1105            .field("wordwise", &self.wordwise)
 1106            .field("done", &self.done)
 1107            .finish()
 1108    }
 1109}
 1110
 1111#[derive(Debug)]
 1112struct AutocloseRegion {
 1113    selection_id: usize,
 1114    range: Range<Anchor>,
 1115    pair: BracketPair,
 1116}
 1117
 1118#[derive(Debug)]
 1119struct SnippetState {
 1120    ranges: Vec<Vec<Range<Anchor>>>,
 1121    active_index: usize,
 1122    choices: Vec<Option<Vec<String>>>,
 1123}
 1124
 1125#[doc(hidden)]
 1126pub struct RenameState {
 1127    pub range: Range<Anchor>,
 1128    pub old_name: Arc<str>,
 1129    pub editor: Entity<Editor>,
 1130    block_id: CustomBlockId,
 1131}
 1132
 1133struct InvalidationStack<T>(Vec<T>);
 1134
 1135struct RegisteredInlineCompletionProvider {
 1136    provider: Arc<dyn InlineCompletionProviderHandle>,
 1137    _subscription: Subscription,
 1138}
 1139
 1140#[derive(Debug, PartialEq, Eq)]
 1141pub struct ActiveDiagnosticGroup {
 1142    pub active_range: Range<Anchor>,
 1143    pub active_message: String,
 1144    pub group_id: usize,
 1145    pub blocks: HashSet<CustomBlockId>,
 1146}
 1147
 1148#[derive(Debug, PartialEq, Eq)]
 1149#[allow(clippy::large_enum_variant)]
 1150pub(crate) enum ActiveDiagnostic {
 1151    None,
 1152    All,
 1153    Group(ActiveDiagnosticGroup),
 1154}
 1155
 1156#[derive(Serialize, Deserialize, Clone, Debug)]
 1157pub struct ClipboardSelection {
 1158    /// The number of bytes in this selection.
 1159    pub len: usize,
 1160    /// Whether this was a full-line selection.
 1161    pub is_entire_line: bool,
 1162    /// The indentation of the first line when this content was originally copied.
 1163    pub first_line_indent: u32,
 1164}
 1165
 1166// selections, scroll behavior, was newest selection reversed
 1167type SelectSyntaxNodeHistoryState = (
 1168    Box<[Selection<usize>]>,
 1169    SelectSyntaxNodeScrollBehavior,
 1170    bool,
 1171);
 1172
 1173#[derive(Default)]
 1174struct SelectSyntaxNodeHistory {
 1175    stack: Vec<SelectSyntaxNodeHistoryState>,
 1176    // disable temporarily to allow changing selections without losing the stack
 1177    pub disable_clearing: bool,
 1178}
 1179
 1180impl SelectSyntaxNodeHistory {
 1181    pub fn try_clear(&mut self) {
 1182        if !self.disable_clearing {
 1183            self.stack.clear();
 1184        }
 1185    }
 1186
 1187    pub fn push(&mut self, selection: SelectSyntaxNodeHistoryState) {
 1188        self.stack.push(selection);
 1189    }
 1190
 1191    pub fn pop(&mut self) -> Option<SelectSyntaxNodeHistoryState> {
 1192        self.stack.pop()
 1193    }
 1194}
 1195
 1196enum SelectSyntaxNodeScrollBehavior {
 1197    CursorTop,
 1198    FitSelection,
 1199    CursorBottom,
 1200}
 1201
 1202#[derive(Debug)]
 1203pub(crate) struct NavigationData {
 1204    cursor_anchor: Anchor,
 1205    cursor_position: Point,
 1206    scroll_anchor: ScrollAnchor,
 1207    scroll_top_row: u32,
 1208}
 1209
 1210#[derive(Debug, Clone, Copy, PartialEq, Eq)]
 1211pub enum GotoDefinitionKind {
 1212    Symbol,
 1213    Declaration,
 1214    Type,
 1215    Implementation,
 1216}
 1217
 1218#[derive(Debug, Clone)]
 1219enum InlayHintRefreshReason {
 1220    ModifiersChanged(bool),
 1221    Toggle(bool),
 1222    SettingsChange(InlayHintSettings),
 1223    NewLinesShown,
 1224    BufferEdited(HashSet<Arc<Language>>),
 1225    RefreshRequested,
 1226    ExcerptsRemoved(Vec<ExcerptId>),
 1227}
 1228
 1229impl InlayHintRefreshReason {
 1230    fn description(&self) -> &'static str {
 1231        match self {
 1232            Self::ModifiersChanged(_) => "modifiers changed",
 1233            Self::Toggle(_) => "toggle",
 1234            Self::SettingsChange(_) => "settings change",
 1235            Self::NewLinesShown => "new lines shown",
 1236            Self::BufferEdited(_) => "buffer edited",
 1237            Self::RefreshRequested => "refresh requested",
 1238            Self::ExcerptsRemoved(_) => "excerpts removed",
 1239        }
 1240    }
 1241}
 1242
 1243pub enum FormatTarget {
 1244    Buffers,
 1245    Ranges(Vec<Range<MultiBufferPoint>>),
 1246}
 1247
 1248pub(crate) struct FocusedBlock {
 1249    id: BlockId,
 1250    focus_handle: WeakFocusHandle,
 1251}
 1252
 1253#[derive(Clone)]
 1254enum JumpData {
 1255    MultiBufferRow {
 1256        row: MultiBufferRow,
 1257        line_offset_from_top: u32,
 1258    },
 1259    MultiBufferPoint {
 1260        excerpt_id: ExcerptId,
 1261        position: Point,
 1262        anchor: text::Anchor,
 1263        line_offset_from_top: u32,
 1264    },
 1265}
 1266
 1267pub enum MultibufferSelectionMode {
 1268    First,
 1269    All,
 1270}
 1271
 1272#[derive(Clone, Copy, Debug, Default)]
 1273pub struct RewrapOptions {
 1274    pub override_language_settings: bool,
 1275    pub preserve_existing_whitespace: bool,
 1276}
 1277
 1278impl Editor {
 1279    pub fn single_line(window: &mut Window, cx: &mut Context<Self>) -> Self {
 1280        let buffer = cx.new(|cx| Buffer::local("", cx));
 1281        let buffer = cx.new(|cx| MultiBuffer::singleton(buffer, cx));
 1282        Self::new(
 1283            EditorMode::SingleLine { auto_width: false },
 1284            buffer,
 1285            None,
 1286            window,
 1287            cx,
 1288        )
 1289    }
 1290
 1291    pub fn multi_line(window: &mut Window, cx: &mut Context<Self>) -> Self {
 1292        let buffer = cx.new(|cx| Buffer::local("", cx));
 1293        let buffer = cx.new(|cx| MultiBuffer::singleton(buffer, cx));
 1294        Self::new(EditorMode::full(), buffer, None, window, cx)
 1295    }
 1296
 1297    pub fn auto_width(window: &mut Window, cx: &mut Context<Self>) -> Self {
 1298        let buffer = cx.new(|cx| Buffer::local("", cx));
 1299        let buffer = cx.new(|cx| MultiBuffer::singleton(buffer, cx));
 1300        Self::new(
 1301            EditorMode::SingleLine { auto_width: true },
 1302            buffer,
 1303            None,
 1304            window,
 1305            cx,
 1306        )
 1307    }
 1308
 1309    pub fn auto_height(max_lines: usize, window: &mut Window, cx: &mut Context<Self>) -> Self {
 1310        let buffer = cx.new(|cx| Buffer::local("", cx));
 1311        let buffer = cx.new(|cx| MultiBuffer::singleton(buffer, cx));
 1312        Self::new(
 1313            EditorMode::AutoHeight { max_lines },
 1314            buffer,
 1315            None,
 1316            window,
 1317            cx,
 1318        )
 1319    }
 1320
 1321    pub fn for_buffer(
 1322        buffer: Entity<Buffer>,
 1323        project: Option<Entity<Project>>,
 1324        window: &mut Window,
 1325        cx: &mut Context<Self>,
 1326    ) -> Self {
 1327        let buffer = cx.new(|cx| MultiBuffer::singleton(buffer, cx));
 1328        Self::new(EditorMode::full(), buffer, project, window, cx)
 1329    }
 1330
 1331    pub fn for_multibuffer(
 1332        buffer: Entity<MultiBuffer>,
 1333        project: Option<Entity<Project>>,
 1334        window: &mut Window,
 1335        cx: &mut Context<Self>,
 1336    ) -> Self {
 1337        Self::new(EditorMode::full(), buffer, project, window, cx)
 1338    }
 1339
 1340    pub fn clone(&self, window: &mut Window, cx: &mut Context<Self>) -> Self {
 1341        let mut clone = Self::new(
 1342            self.mode,
 1343            self.buffer.clone(),
 1344            self.project.clone(),
 1345            window,
 1346            cx,
 1347        );
 1348        self.display_map.update(cx, |display_map, cx| {
 1349            let snapshot = display_map.snapshot(cx);
 1350            clone.display_map.update(cx, |display_map, cx| {
 1351                display_map.set_state(&snapshot, cx);
 1352            });
 1353        });
 1354        clone.folds_did_change(cx);
 1355        clone.selections.clone_state(&self.selections);
 1356        clone.scroll_manager.clone_state(&self.scroll_manager);
 1357        clone.searchable = self.searchable;
 1358        clone.read_only = self.read_only;
 1359        clone
 1360    }
 1361
 1362    pub fn new(
 1363        mode: EditorMode,
 1364        buffer: Entity<MultiBuffer>,
 1365        project: Option<Entity<Project>>,
 1366        window: &mut Window,
 1367        cx: &mut Context<Self>,
 1368    ) -> Self {
 1369        let style = window.text_style();
 1370        let font_size = style.font_size.to_pixels(window.rem_size());
 1371        let editor = cx.entity().downgrade();
 1372        let fold_placeholder = FoldPlaceholder {
 1373            constrain_width: true,
 1374            render: Arc::new(move |fold_id, fold_range, cx| {
 1375                let editor = editor.clone();
 1376                div()
 1377                    .id(fold_id)
 1378                    .bg(cx.theme().colors().ghost_element_background)
 1379                    .hover(|style| style.bg(cx.theme().colors().ghost_element_hover))
 1380                    .active(|style| style.bg(cx.theme().colors().ghost_element_active))
 1381                    .rounded_xs()
 1382                    .size_full()
 1383                    .cursor_pointer()
 1384                    .child("")
 1385                    .on_mouse_down(MouseButton::Left, |_, _, cx| cx.stop_propagation())
 1386                    .on_click(move |_, _window, cx| {
 1387                        editor
 1388                            .update(cx, |editor, cx| {
 1389                                editor.unfold_ranges(
 1390                                    &[fold_range.start..fold_range.end],
 1391                                    true,
 1392                                    false,
 1393                                    cx,
 1394                                );
 1395                                cx.stop_propagation();
 1396                            })
 1397                            .ok();
 1398                    })
 1399                    .into_any()
 1400            }),
 1401            merge_adjacent: true,
 1402            ..Default::default()
 1403        };
 1404        let display_map = cx.new(|cx| {
 1405            DisplayMap::new(
 1406                buffer.clone(),
 1407                style.font(),
 1408                font_size,
 1409                None,
 1410                FILE_HEADER_HEIGHT,
 1411                MULTI_BUFFER_EXCERPT_HEADER_HEIGHT,
 1412                fold_placeholder,
 1413                cx,
 1414            )
 1415        });
 1416
 1417        let selections = SelectionsCollection::new(display_map.clone(), buffer.clone());
 1418
 1419        let blink_manager = cx.new(|cx| BlinkManager::new(CURSOR_BLINK_INTERVAL, cx));
 1420
 1421        let soft_wrap_mode_override = matches!(mode, EditorMode::SingleLine { .. })
 1422            .then(|| language_settings::SoftWrap::None);
 1423
 1424        let mut project_subscriptions = Vec::new();
 1425        if mode.is_full() {
 1426            if let Some(project) = project.as_ref() {
 1427                project_subscriptions.push(cx.subscribe_in(
 1428                    project,
 1429                    window,
 1430                    |editor, _, event, window, cx| match event {
 1431                        project::Event::RefreshCodeLens => {
 1432                            // we always query lens with actions, without storing them, always refreshing them
 1433                        }
 1434                        project::Event::RefreshInlayHints => {
 1435                            editor
 1436                                .refresh_inlay_hints(InlayHintRefreshReason::RefreshRequested, cx);
 1437                        }
 1438                        project::Event::SnippetEdit(id, snippet_edits) => {
 1439                            if let Some(buffer) = editor.buffer.read(cx).buffer(*id) {
 1440                                let focus_handle = editor.focus_handle(cx);
 1441                                if focus_handle.is_focused(window) {
 1442                                    let snapshot = buffer.read(cx).snapshot();
 1443                                    for (range, snippet) in snippet_edits {
 1444                                        let editor_range =
 1445                                            language::range_from_lsp(*range).to_offset(&snapshot);
 1446                                        editor
 1447                                            .insert_snippet(
 1448                                                &[editor_range],
 1449                                                snippet.clone(),
 1450                                                window,
 1451                                                cx,
 1452                                            )
 1453                                            .ok();
 1454                                    }
 1455                                }
 1456                            }
 1457                        }
 1458                        _ => {}
 1459                    },
 1460                ));
 1461                if let Some(task_inventory) = project
 1462                    .read(cx)
 1463                    .task_store()
 1464                    .read(cx)
 1465                    .task_inventory()
 1466                    .cloned()
 1467                {
 1468                    project_subscriptions.push(cx.observe_in(
 1469                        &task_inventory,
 1470                        window,
 1471                        |editor, _, window, cx| {
 1472                            editor.tasks_update_task = Some(editor.refresh_runnables(window, cx));
 1473                        },
 1474                    ));
 1475                };
 1476
 1477                project_subscriptions.push(cx.subscribe_in(
 1478                    &project.read(cx).breakpoint_store(),
 1479                    window,
 1480                    |editor, _, event, window, cx| match event {
 1481                        BreakpointStoreEvent::ActiveDebugLineChanged => {
 1482                            if editor.go_to_active_debug_line(window, cx) {
 1483                                cx.stop_propagation();
 1484                            }
 1485                        }
 1486                        _ => {}
 1487                    },
 1488                ));
 1489            }
 1490        }
 1491
 1492        let buffer_snapshot = buffer.read(cx).snapshot(cx);
 1493
 1494        let inlay_hint_settings =
 1495            inlay_hint_settings(selections.newest_anchor().head(), &buffer_snapshot, cx);
 1496        let focus_handle = cx.focus_handle();
 1497        cx.on_focus(&focus_handle, window, Self::handle_focus)
 1498            .detach();
 1499        cx.on_focus_in(&focus_handle, window, Self::handle_focus_in)
 1500            .detach();
 1501        cx.on_focus_out(&focus_handle, window, Self::handle_focus_out)
 1502            .detach();
 1503        cx.on_blur(&focus_handle, window, Self::handle_blur)
 1504            .detach();
 1505
 1506        let show_indent_guides = if matches!(mode, EditorMode::SingleLine { .. }) {
 1507            Some(false)
 1508        } else {
 1509            None
 1510        };
 1511
 1512        let breakpoint_store = match (mode, project.as_ref()) {
 1513            (EditorMode::Full { .. }, Some(project)) => Some(project.read(cx).breakpoint_store()),
 1514            _ => None,
 1515        };
 1516
 1517        let mut code_action_providers = Vec::new();
 1518        let mut load_uncommitted_diff = None;
 1519        if let Some(project) = project.clone() {
 1520            load_uncommitted_diff = Some(
 1521                get_uncommitted_diff_for_buffer(
 1522                    &project,
 1523                    buffer.read(cx).all_buffers(),
 1524                    buffer.clone(),
 1525                    cx,
 1526                )
 1527                .shared(),
 1528            );
 1529            code_action_providers.push(Rc::new(project) as Rc<_>);
 1530        }
 1531
 1532        let mut this = Self {
 1533            focus_handle,
 1534            show_cursor_when_unfocused: false,
 1535            last_focused_descendant: None,
 1536            buffer: buffer.clone(),
 1537            display_map: display_map.clone(),
 1538            selections,
 1539            scroll_manager: ScrollManager::new(cx),
 1540            columnar_selection_tail: None,
 1541            add_selections_state: None,
 1542            select_next_state: None,
 1543            select_prev_state: None,
 1544            selection_history: Default::default(),
 1545            autoclose_regions: Default::default(),
 1546            snippet_stack: Default::default(),
 1547            select_syntax_node_history: SelectSyntaxNodeHistory::default(),
 1548            ime_transaction: Default::default(),
 1549            active_diagnostics: ActiveDiagnostic::None,
 1550            show_inline_diagnostics: ProjectSettings::get_global(cx).diagnostics.inline.enabled,
 1551            inline_diagnostics_update: Task::ready(()),
 1552            inline_diagnostics: Vec::new(),
 1553            soft_wrap_mode_override,
 1554            hard_wrap: None,
 1555            completion_provider: project.clone().map(|project| Box::new(project) as _),
 1556            semantics_provider: project.clone().map(|project| Rc::new(project) as _),
 1557            collaboration_hub: project.clone().map(|project| Box::new(project) as _),
 1558            project,
 1559            blink_manager: blink_manager.clone(),
 1560            show_local_selections: true,
 1561            show_scrollbars: true,
 1562            mode,
 1563            show_breadcrumbs: EditorSettings::get_global(cx).toolbar.breadcrumbs,
 1564            show_gutter: mode.is_full(),
 1565            show_line_numbers: None,
 1566            use_relative_line_numbers: None,
 1567            show_git_diff_gutter: None,
 1568            show_code_actions: None,
 1569            show_runnables: None,
 1570            show_breakpoints: None,
 1571            show_wrap_guides: None,
 1572            show_indent_guides,
 1573            placeholder_text: None,
 1574            highlight_order: 0,
 1575            highlighted_rows: HashMap::default(),
 1576            background_highlights: Default::default(),
 1577            gutter_highlights: TreeMap::default(),
 1578            scrollbar_marker_state: ScrollbarMarkerState::default(),
 1579            active_indent_guides_state: ActiveIndentGuidesState::default(),
 1580            nav_history: None,
 1581            context_menu: RefCell::new(None),
 1582            context_menu_options: None,
 1583            mouse_context_menu: None,
 1584            completion_tasks: Default::default(),
 1585            signature_help_state: SignatureHelpState::default(),
 1586            auto_signature_help: None,
 1587            find_all_references_task_sources: Vec::new(),
 1588            next_completion_id: 0,
 1589            next_inlay_id: 0,
 1590            code_action_providers,
 1591            available_code_actions: Default::default(),
 1592            code_actions_task: Default::default(),
 1593            selection_highlight_task: Default::default(),
 1594            document_highlights_task: Default::default(),
 1595            linked_editing_range_task: Default::default(),
 1596            pending_rename: Default::default(),
 1597            searchable: true,
 1598            cursor_shape: EditorSettings::get_global(cx)
 1599                .cursor_shape
 1600                .unwrap_or_default(),
 1601            current_line_highlight: None,
 1602            autoindent_mode: Some(AutoindentMode::EachLine),
 1603            collapse_matches: false,
 1604            workspace: None,
 1605            input_enabled: true,
 1606            use_modal_editing: mode.is_full(),
 1607            read_only: false,
 1608            use_autoclose: true,
 1609            use_auto_surround: true,
 1610            auto_replace_emoji_shortcode: false,
 1611            jsx_tag_auto_close_enabled_in_any_buffer: false,
 1612            leader_peer_id: None,
 1613            remote_id: None,
 1614            hover_state: Default::default(),
 1615            pending_mouse_down: None,
 1616            hovered_link_state: Default::default(),
 1617            edit_prediction_provider: None,
 1618            active_inline_completion: None,
 1619            stale_inline_completion_in_menu: None,
 1620            edit_prediction_preview: EditPredictionPreview::Inactive {
 1621                released_too_fast: false,
 1622            },
 1623            inline_diagnostics_enabled: mode.is_full(),
 1624            inlay_hint_cache: InlayHintCache::new(inlay_hint_settings),
 1625
 1626            gutter_hovered: false,
 1627            pixel_position_of_newest_cursor: None,
 1628            last_bounds: None,
 1629            last_position_map: None,
 1630            expect_bounds_change: None,
 1631            gutter_dimensions: GutterDimensions::default(),
 1632            style: None,
 1633            show_cursor_names: false,
 1634            hovered_cursors: Default::default(),
 1635            next_editor_action_id: EditorActionId::default(),
 1636            editor_actions: Rc::default(),
 1637            inline_completions_hidden_for_vim_mode: false,
 1638            show_inline_completions_override: None,
 1639            menu_inline_completions_policy: MenuInlineCompletionsPolicy::ByProvider,
 1640            edit_prediction_settings: EditPredictionSettings::Disabled,
 1641            edit_prediction_indent_conflict: false,
 1642            edit_prediction_requires_modifier_in_indent_conflict: true,
 1643            custom_context_menu: None,
 1644            show_git_blame_gutter: false,
 1645            show_git_blame_inline: false,
 1646            show_selection_menu: None,
 1647            show_git_blame_inline_delay_task: None,
 1648            git_blame_inline_tooltip: None,
 1649            git_blame_inline_enabled: ProjectSettings::get_global(cx).git.inline_blame_enabled(),
 1650            render_diff_hunk_controls: Arc::new(render_diff_hunk_controls),
 1651            serialize_dirty_buffers: ProjectSettings::get_global(cx)
 1652                .session
 1653                .restore_unsaved_buffers,
 1654            blame: None,
 1655            blame_subscription: None,
 1656            tasks: Default::default(),
 1657
 1658            breakpoint_store,
 1659            gutter_breakpoint_indicator: (None, None),
 1660            _subscriptions: vec![
 1661                cx.observe(&buffer, Self::on_buffer_changed),
 1662                cx.subscribe_in(&buffer, window, Self::on_buffer_event),
 1663                cx.observe_in(&display_map, window, Self::on_display_map_changed),
 1664                cx.observe(&blink_manager, |_, _, cx| cx.notify()),
 1665                cx.observe_global_in::<SettingsStore>(window, Self::settings_changed),
 1666                observe_buffer_font_size_adjustment(cx, |_, cx| cx.notify()),
 1667                cx.observe_window_activation(window, |editor, window, cx| {
 1668                    let active = window.is_window_active();
 1669                    editor.blink_manager.update(cx, |blink_manager, cx| {
 1670                        if active {
 1671                            blink_manager.enable(cx);
 1672                        } else {
 1673                            blink_manager.disable(cx);
 1674                        }
 1675                    });
 1676                }),
 1677            ],
 1678            tasks_update_task: None,
 1679            linked_edit_ranges: Default::default(),
 1680            in_project_search: false,
 1681            previous_search_ranges: None,
 1682            breadcrumb_header: None,
 1683            focused_block: None,
 1684            next_scroll_position: NextScrollCursorCenterTopBottom::default(),
 1685            addons: HashMap::default(),
 1686            registered_buffers: HashMap::default(),
 1687            _scroll_cursor_center_top_bottom_task: Task::ready(()),
 1688            selection_mark_mode: false,
 1689            toggle_fold_multiple_buffers: Task::ready(()),
 1690            serialize_selections: Task::ready(()),
 1691            serialize_folds: Task::ready(()),
 1692            text_style_refinement: None,
 1693            load_diff_task: load_uncommitted_diff,
 1694            mouse_cursor_hidden: false,
 1695            hide_mouse_mode: EditorSettings::get_global(cx)
 1696                .hide_mouse
 1697                .unwrap_or_default(),
 1698            change_list: ChangeList::new(),
 1699        };
 1700        if let Some(breakpoints) = this.breakpoint_store.as_ref() {
 1701            this._subscriptions
 1702                .push(cx.observe(breakpoints, |_, _, cx| {
 1703                    cx.notify();
 1704                }));
 1705        }
 1706        this.tasks_update_task = Some(this.refresh_runnables(window, cx));
 1707        this._subscriptions.extend(project_subscriptions);
 1708
 1709        this._subscriptions.push(cx.subscribe_in(
 1710            &cx.entity(),
 1711            window,
 1712            |editor, _, e: &EditorEvent, window, cx| match e {
 1713                EditorEvent::ScrollPositionChanged { local, .. } => {
 1714                    if *local {
 1715                        let new_anchor = editor.scroll_manager.anchor();
 1716                        let snapshot = editor.snapshot(window, cx);
 1717                        editor.update_restoration_data(cx, move |data| {
 1718                            data.scroll_position = (
 1719                                new_anchor.top_row(&snapshot.buffer_snapshot),
 1720                                new_anchor.offset,
 1721                            );
 1722                        });
 1723                    }
 1724                }
 1725                EditorEvent::Edited { .. } => {
 1726                    if !vim_enabled(cx) {
 1727                        let (map, selections) = editor.selections.all_adjusted_display(cx);
 1728                        let pop_state = editor
 1729                            .change_list
 1730                            .last()
 1731                            .map(|previous| {
 1732                                previous.len() == selections.len()
 1733                                    && previous.iter().enumerate().all(|(ix, p)| {
 1734                                        p.to_display_point(&map).row()
 1735                                            == selections[ix].head().row()
 1736                                    })
 1737                            })
 1738                            .unwrap_or(false);
 1739                        let new_positions = selections
 1740                            .into_iter()
 1741                            .map(|s| map.display_point_to_anchor(s.head(), Bias::Left))
 1742                            .collect();
 1743                        editor
 1744                            .change_list
 1745                            .push_to_change_list(pop_state, new_positions);
 1746                    }
 1747                }
 1748                _ => (),
 1749            },
 1750        ));
 1751
 1752        this.end_selection(window, cx);
 1753        this.scroll_manager.show_scrollbars(window, cx);
 1754        jsx_tag_auto_close::refresh_enabled_in_any_buffer(&mut this, &buffer, cx);
 1755
 1756        if mode.is_full() {
 1757            let should_auto_hide_scrollbars = cx.should_auto_hide_scrollbars();
 1758            cx.set_global(ScrollbarAutoHide(should_auto_hide_scrollbars));
 1759
 1760            if this.git_blame_inline_enabled {
 1761                this.git_blame_inline_enabled = true;
 1762                this.start_git_blame_inline(false, window, cx);
 1763            }
 1764
 1765            this.go_to_active_debug_line(window, cx);
 1766
 1767            if let Some(buffer) = buffer.read(cx).as_singleton() {
 1768                if let Some(project) = this.project.as_ref() {
 1769                    let handle = project.update(cx, |project, cx| {
 1770                        project.register_buffer_with_language_servers(&buffer, cx)
 1771                    });
 1772                    this.registered_buffers
 1773                        .insert(buffer.read(cx).remote_id(), handle);
 1774                }
 1775            }
 1776        }
 1777
 1778        this.report_editor_event("Editor Opened", None, cx);
 1779        this
 1780    }
 1781
 1782    pub fn deploy_mouse_context_menu(
 1783        &mut self,
 1784        position: gpui::Point<Pixels>,
 1785        context_menu: Entity<ContextMenu>,
 1786        window: &mut Window,
 1787        cx: &mut Context<Self>,
 1788    ) {
 1789        self.mouse_context_menu = Some(MouseContextMenu::new(
 1790            self,
 1791            crate::mouse_context_menu::MenuPosition::PinnedToScreen(position),
 1792            context_menu,
 1793            window,
 1794            cx,
 1795        ));
 1796    }
 1797
 1798    pub fn mouse_menu_is_focused(&self, window: &Window, cx: &App) -> bool {
 1799        self.mouse_context_menu
 1800            .as_ref()
 1801            .is_some_and(|menu| menu.context_menu.focus_handle(cx).is_focused(window))
 1802    }
 1803
 1804    fn key_context(&self, window: &Window, cx: &App) -> KeyContext {
 1805        self.key_context_internal(self.has_active_inline_completion(), window, cx)
 1806    }
 1807
 1808    fn key_context_internal(
 1809        &self,
 1810        has_active_edit_prediction: bool,
 1811        window: &Window,
 1812        cx: &App,
 1813    ) -> KeyContext {
 1814        let mut key_context = KeyContext::new_with_defaults();
 1815        key_context.add("Editor");
 1816        let mode = match self.mode {
 1817            EditorMode::SingleLine { .. } => "single_line",
 1818            EditorMode::AutoHeight { .. } => "auto_height",
 1819            EditorMode::Full { .. } => "full",
 1820        };
 1821
 1822        if EditorSettings::jupyter_enabled(cx) {
 1823            key_context.add("jupyter");
 1824        }
 1825
 1826        key_context.set("mode", mode);
 1827        if self.pending_rename.is_some() {
 1828            key_context.add("renaming");
 1829        }
 1830
 1831        match self.context_menu.borrow().as_ref() {
 1832            Some(CodeContextMenu::Completions(_)) => {
 1833                key_context.add("menu");
 1834                key_context.add("showing_completions");
 1835            }
 1836            Some(CodeContextMenu::CodeActions(_)) => {
 1837                key_context.add("menu");
 1838                key_context.add("showing_code_actions")
 1839            }
 1840            None => {}
 1841        }
 1842
 1843        // Disable vim contexts when a sub-editor (e.g. rename/inline assistant) is focused.
 1844        if !self.focus_handle(cx).contains_focused(window, cx)
 1845            || (self.is_focused(window) || self.mouse_menu_is_focused(window, cx))
 1846        {
 1847            for addon in self.addons.values() {
 1848                addon.extend_key_context(&mut key_context, cx)
 1849            }
 1850        }
 1851
 1852        if let Some(singleton_buffer) = self.buffer.read(cx).as_singleton() {
 1853            if let Some(extension) = singleton_buffer
 1854                .read(cx)
 1855                .file()
 1856                .and_then(|file| file.path().extension()?.to_str())
 1857            {
 1858                key_context.set("extension", extension.to_string());
 1859            }
 1860        } else {
 1861            key_context.add("multibuffer");
 1862        }
 1863
 1864        if has_active_edit_prediction {
 1865            if self.edit_prediction_in_conflict() {
 1866                key_context.add(EDIT_PREDICTION_CONFLICT_KEY_CONTEXT);
 1867            } else {
 1868                key_context.add(EDIT_PREDICTION_KEY_CONTEXT);
 1869                key_context.add("copilot_suggestion");
 1870            }
 1871        }
 1872
 1873        if self.selection_mark_mode {
 1874            key_context.add("selection_mode");
 1875        }
 1876
 1877        key_context
 1878    }
 1879
 1880    pub fn hide_mouse_cursor(&mut self, origin: &HideMouseCursorOrigin) {
 1881        self.mouse_cursor_hidden = match origin {
 1882            HideMouseCursorOrigin::TypingAction => {
 1883                matches!(
 1884                    self.hide_mouse_mode,
 1885                    HideMouseMode::OnTyping | HideMouseMode::OnTypingAndMovement
 1886                )
 1887            }
 1888            HideMouseCursorOrigin::MovementAction => {
 1889                matches!(self.hide_mouse_mode, HideMouseMode::OnTypingAndMovement)
 1890            }
 1891        };
 1892    }
 1893
 1894    pub fn edit_prediction_in_conflict(&self) -> bool {
 1895        if !self.show_edit_predictions_in_menu() {
 1896            return false;
 1897        }
 1898
 1899        let showing_completions = self
 1900            .context_menu
 1901            .borrow()
 1902            .as_ref()
 1903            .map_or(false, |context| {
 1904                matches!(context, CodeContextMenu::Completions(_))
 1905            });
 1906
 1907        showing_completions
 1908            || self.edit_prediction_requires_modifier()
 1909            // Require modifier key when the cursor is on leading whitespace, to allow `tab`
 1910            // bindings to insert tab characters.
 1911            || (self.edit_prediction_requires_modifier_in_indent_conflict && self.edit_prediction_indent_conflict)
 1912    }
 1913
 1914    pub fn accept_edit_prediction_keybind(
 1915        &self,
 1916        window: &Window,
 1917        cx: &App,
 1918    ) -> AcceptEditPredictionBinding {
 1919        let key_context = self.key_context_internal(true, window, cx);
 1920        let in_conflict = self.edit_prediction_in_conflict();
 1921
 1922        AcceptEditPredictionBinding(
 1923            window
 1924                .bindings_for_action_in_context(&AcceptEditPrediction, key_context)
 1925                .into_iter()
 1926                .filter(|binding| {
 1927                    !in_conflict
 1928                        || binding
 1929                            .keystrokes()
 1930                            .first()
 1931                            .map_or(false, |keystroke| keystroke.modifiers.modified())
 1932                })
 1933                .rev()
 1934                .min_by_key(|binding| {
 1935                    binding
 1936                        .keystrokes()
 1937                        .first()
 1938                        .map_or(u8::MAX, |k| k.modifiers.number_of_modifiers())
 1939                }),
 1940        )
 1941    }
 1942
 1943    pub fn new_file(
 1944        workspace: &mut Workspace,
 1945        _: &workspace::NewFile,
 1946        window: &mut Window,
 1947        cx: &mut Context<Workspace>,
 1948    ) {
 1949        Self::new_in_workspace(workspace, window, cx).detach_and_prompt_err(
 1950            "Failed to create buffer",
 1951            window,
 1952            cx,
 1953            |e, _, _| match e.error_code() {
 1954                ErrorCode::RemoteUpgradeRequired => Some(format!(
 1955                "The remote instance of Zed does not support this yet. It must be upgraded to {}",
 1956                e.error_tag("required").unwrap_or("the latest version")
 1957            )),
 1958                _ => None,
 1959            },
 1960        );
 1961    }
 1962
 1963    pub fn new_in_workspace(
 1964        workspace: &mut Workspace,
 1965        window: &mut Window,
 1966        cx: &mut Context<Workspace>,
 1967    ) -> Task<Result<Entity<Editor>>> {
 1968        let project = workspace.project().clone();
 1969        let create = project.update(cx, |project, cx| project.create_buffer(cx));
 1970
 1971        cx.spawn_in(window, async move |workspace, cx| {
 1972            let buffer = create.await?;
 1973            workspace.update_in(cx, |workspace, window, cx| {
 1974                let editor =
 1975                    cx.new(|cx| Editor::for_buffer(buffer, Some(project.clone()), window, cx));
 1976                workspace.add_item_to_active_pane(Box::new(editor.clone()), None, true, window, cx);
 1977                editor
 1978            })
 1979        })
 1980    }
 1981
 1982    fn new_file_vertical(
 1983        workspace: &mut Workspace,
 1984        _: &workspace::NewFileSplitVertical,
 1985        window: &mut Window,
 1986        cx: &mut Context<Workspace>,
 1987    ) {
 1988        Self::new_file_in_direction(workspace, SplitDirection::vertical(cx), window, cx)
 1989    }
 1990
 1991    fn new_file_horizontal(
 1992        workspace: &mut Workspace,
 1993        _: &workspace::NewFileSplitHorizontal,
 1994        window: &mut Window,
 1995        cx: &mut Context<Workspace>,
 1996    ) {
 1997        Self::new_file_in_direction(workspace, SplitDirection::horizontal(cx), window, cx)
 1998    }
 1999
 2000    fn new_file_in_direction(
 2001        workspace: &mut Workspace,
 2002        direction: SplitDirection,
 2003        window: &mut Window,
 2004        cx: &mut Context<Workspace>,
 2005    ) {
 2006        let project = workspace.project().clone();
 2007        let create = project.update(cx, |project, cx| project.create_buffer(cx));
 2008
 2009        cx.spawn_in(window, async move |workspace, cx| {
 2010            let buffer = create.await?;
 2011            workspace.update_in(cx, move |workspace, window, cx| {
 2012                workspace.split_item(
 2013                    direction,
 2014                    Box::new(
 2015                        cx.new(|cx| Editor::for_buffer(buffer, Some(project.clone()), window, cx)),
 2016                    ),
 2017                    window,
 2018                    cx,
 2019                )
 2020            })?;
 2021            anyhow::Ok(())
 2022        })
 2023        .detach_and_prompt_err("Failed to create buffer", window, cx, |e, _, _| {
 2024            match e.error_code() {
 2025                ErrorCode::RemoteUpgradeRequired => Some(format!(
 2026                "The remote instance of Zed does not support this yet. It must be upgraded to {}",
 2027                e.error_tag("required").unwrap_or("the latest version")
 2028            )),
 2029                _ => None,
 2030            }
 2031        });
 2032    }
 2033
 2034    pub fn leader_peer_id(&self) -> Option<PeerId> {
 2035        self.leader_peer_id
 2036    }
 2037
 2038    pub fn buffer(&self) -> &Entity<MultiBuffer> {
 2039        &self.buffer
 2040    }
 2041
 2042    pub fn workspace(&self) -> Option<Entity<Workspace>> {
 2043        self.workspace.as_ref()?.0.upgrade()
 2044    }
 2045
 2046    pub fn title<'a>(&self, cx: &'a App) -> Cow<'a, str> {
 2047        self.buffer().read(cx).title(cx)
 2048    }
 2049
 2050    pub fn snapshot(&self, window: &mut Window, cx: &mut App) -> EditorSnapshot {
 2051        let git_blame_gutter_max_author_length = self
 2052            .render_git_blame_gutter(cx)
 2053            .then(|| {
 2054                if let Some(blame) = self.blame.as_ref() {
 2055                    let max_author_length =
 2056                        blame.update(cx, |blame, cx| blame.max_author_length(cx));
 2057                    Some(max_author_length)
 2058                } else {
 2059                    None
 2060                }
 2061            })
 2062            .flatten();
 2063
 2064        EditorSnapshot {
 2065            mode: self.mode,
 2066            show_gutter: self.show_gutter,
 2067            show_line_numbers: self.show_line_numbers,
 2068            show_git_diff_gutter: self.show_git_diff_gutter,
 2069            show_code_actions: self.show_code_actions,
 2070            show_runnables: self.show_runnables,
 2071            show_breakpoints: self.show_breakpoints,
 2072            git_blame_gutter_max_author_length,
 2073            display_snapshot: self.display_map.update(cx, |map, cx| map.snapshot(cx)),
 2074            scroll_anchor: self.scroll_manager.anchor(),
 2075            ongoing_scroll: self.scroll_manager.ongoing_scroll(),
 2076            placeholder_text: self.placeholder_text.clone(),
 2077            is_focused: self.focus_handle.is_focused(window),
 2078            current_line_highlight: self
 2079                .current_line_highlight
 2080                .unwrap_or_else(|| EditorSettings::get_global(cx).current_line_highlight),
 2081            gutter_hovered: self.gutter_hovered,
 2082        }
 2083    }
 2084
 2085    pub fn language_at<T: ToOffset>(&self, point: T, cx: &App) -> Option<Arc<Language>> {
 2086        self.buffer.read(cx).language_at(point, cx)
 2087    }
 2088
 2089    pub fn file_at<T: ToOffset>(&self, point: T, cx: &App) -> Option<Arc<dyn language::File>> {
 2090        self.buffer.read(cx).read(cx).file_at(point).cloned()
 2091    }
 2092
 2093    pub fn active_excerpt(
 2094        &self,
 2095        cx: &App,
 2096    ) -> Option<(ExcerptId, Entity<Buffer>, Range<text::Anchor>)> {
 2097        self.buffer
 2098            .read(cx)
 2099            .excerpt_containing(self.selections.newest_anchor().head(), cx)
 2100    }
 2101
 2102    pub fn mode(&self) -> EditorMode {
 2103        self.mode
 2104    }
 2105
 2106    pub fn set_mode(&mut self, mode: EditorMode) {
 2107        self.mode = mode;
 2108    }
 2109
 2110    pub fn collaboration_hub(&self) -> Option<&dyn CollaborationHub> {
 2111        self.collaboration_hub.as_deref()
 2112    }
 2113
 2114    pub fn set_collaboration_hub(&mut self, hub: Box<dyn CollaborationHub>) {
 2115        self.collaboration_hub = Some(hub);
 2116    }
 2117
 2118    pub fn set_in_project_search(&mut self, in_project_search: bool) {
 2119        self.in_project_search = in_project_search;
 2120    }
 2121
 2122    pub fn set_custom_context_menu(
 2123        &mut self,
 2124        f: impl 'static
 2125        + Fn(
 2126            &mut Self,
 2127            DisplayPoint,
 2128            &mut Window,
 2129            &mut Context<Self>,
 2130        ) -> Option<Entity<ui::ContextMenu>>,
 2131    ) {
 2132        self.custom_context_menu = Some(Box::new(f))
 2133    }
 2134
 2135    pub fn set_completion_provider(&mut self, provider: Option<Box<dyn CompletionProvider>>) {
 2136        self.completion_provider = provider;
 2137    }
 2138
 2139    pub fn semantics_provider(&self) -> Option<Rc<dyn SemanticsProvider>> {
 2140        self.semantics_provider.clone()
 2141    }
 2142
 2143    pub fn set_semantics_provider(&mut self, provider: Option<Rc<dyn SemanticsProvider>>) {
 2144        self.semantics_provider = provider;
 2145    }
 2146
 2147    pub fn set_edit_prediction_provider<T>(
 2148        &mut self,
 2149        provider: Option<Entity<T>>,
 2150        window: &mut Window,
 2151        cx: &mut Context<Self>,
 2152    ) where
 2153        T: EditPredictionProvider,
 2154    {
 2155        self.edit_prediction_provider =
 2156            provider.map(|provider| RegisteredInlineCompletionProvider {
 2157                _subscription: cx.observe_in(&provider, window, |this, _, window, cx| {
 2158                    if this.focus_handle.is_focused(window) {
 2159                        this.update_visible_inline_completion(window, cx);
 2160                    }
 2161                }),
 2162                provider: Arc::new(provider),
 2163            });
 2164        self.update_edit_prediction_settings(cx);
 2165        self.refresh_inline_completion(false, false, window, cx);
 2166    }
 2167
 2168    pub fn placeholder_text(&self) -> Option<&str> {
 2169        self.placeholder_text.as_deref()
 2170    }
 2171
 2172    pub fn set_placeholder_text(
 2173        &mut self,
 2174        placeholder_text: impl Into<Arc<str>>,
 2175        cx: &mut Context<Self>,
 2176    ) {
 2177        let placeholder_text = Some(placeholder_text.into());
 2178        if self.placeholder_text != placeholder_text {
 2179            self.placeholder_text = placeholder_text;
 2180            cx.notify();
 2181        }
 2182    }
 2183
 2184    pub fn set_cursor_shape(&mut self, cursor_shape: CursorShape, cx: &mut Context<Self>) {
 2185        self.cursor_shape = cursor_shape;
 2186
 2187        // Disrupt blink for immediate user feedback that the cursor shape has changed
 2188        self.blink_manager.update(cx, BlinkManager::show_cursor);
 2189
 2190        cx.notify();
 2191    }
 2192
 2193    pub fn set_current_line_highlight(
 2194        &mut self,
 2195        current_line_highlight: Option<CurrentLineHighlight>,
 2196    ) {
 2197        self.current_line_highlight = current_line_highlight;
 2198    }
 2199
 2200    pub fn set_collapse_matches(&mut self, collapse_matches: bool) {
 2201        self.collapse_matches = collapse_matches;
 2202    }
 2203
 2204    fn register_buffers_with_language_servers(&mut self, cx: &mut Context<Self>) {
 2205        let buffers = self.buffer.read(cx).all_buffers();
 2206        let Some(project) = self.project.as_ref() else {
 2207            return;
 2208        };
 2209        project.update(cx, |project, cx| {
 2210            for buffer in buffers {
 2211                self.registered_buffers
 2212                    .entry(buffer.read(cx).remote_id())
 2213                    .or_insert_with(|| project.register_buffer_with_language_servers(&buffer, cx));
 2214            }
 2215        })
 2216    }
 2217
 2218    pub fn range_for_match<T: std::marker::Copy>(&self, range: &Range<T>) -> Range<T> {
 2219        if self.collapse_matches {
 2220            return range.start..range.start;
 2221        }
 2222        range.clone()
 2223    }
 2224
 2225    pub fn set_clip_at_line_ends(&mut self, clip: bool, cx: &mut Context<Self>) {
 2226        if self.display_map.read(cx).clip_at_line_ends != clip {
 2227            self.display_map
 2228                .update(cx, |map, _| map.clip_at_line_ends = clip);
 2229        }
 2230    }
 2231
 2232    pub fn set_input_enabled(&mut self, input_enabled: bool) {
 2233        self.input_enabled = input_enabled;
 2234    }
 2235
 2236    pub fn set_inline_completions_hidden_for_vim_mode(
 2237        &mut self,
 2238        hidden: bool,
 2239        window: &mut Window,
 2240        cx: &mut Context<Self>,
 2241    ) {
 2242        if hidden != self.inline_completions_hidden_for_vim_mode {
 2243            self.inline_completions_hidden_for_vim_mode = hidden;
 2244            if hidden {
 2245                self.update_visible_inline_completion(window, cx);
 2246            } else {
 2247                self.refresh_inline_completion(true, false, window, cx);
 2248            }
 2249        }
 2250    }
 2251
 2252    pub fn set_menu_inline_completions_policy(&mut self, value: MenuInlineCompletionsPolicy) {
 2253        self.menu_inline_completions_policy = value;
 2254    }
 2255
 2256    pub fn set_autoindent(&mut self, autoindent: bool) {
 2257        if autoindent {
 2258            self.autoindent_mode = Some(AutoindentMode::EachLine);
 2259        } else {
 2260            self.autoindent_mode = None;
 2261        }
 2262    }
 2263
 2264    pub fn read_only(&self, cx: &App) -> bool {
 2265        self.read_only || self.buffer.read(cx).read_only()
 2266    }
 2267
 2268    pub fn set_read_only(&mut self, read_only: bool) {
 2269        self.read_only = read_only;
 2270    }
 2271
 2272    pub fn set_use_autoclose(&mut self, autoclose: bool) {
 2273        self.use_autoclose = autoclose;
 2274    }
 2275
 2276    pub fn set_use_auto_surround(&mut self, auto_surround: bool) {
 2277        self.use_auto_surround = auto_surround;
 2278    }
 2279
 2280    pub fn set_auto_replace_emoji_shortcode(&mut self, auto_replace: bool) {
 2281        self.auto_replace_emoji_shortcode = auto_replace;
 2282    }
 2283
 2284    pub fn toggle_edit_predictions(
 2285        &mut self,
 2286        _: &ToggleEditPrediction,
 2287        window: &mut Window,
 2288        cx: &mut Context<Self>,
 2289    ) {
 2290        if self.show_inline_completions_override.is_some() {
 2291            self.set_show_edit_predictions(None, window, cx);
 2292        } else {
 2293            let show_edit_predictions = !self.edit_predictions_enabled();
 2294            self.set_show_edit_predictions(Some(show_edit_predictions), window, cx);
 2295        }
 2296    }
 2297
 2298    pub fn set_show_edit_predictions(
 2299        &mut self,
 2300        show_edit_predictions: Option<bool>,
 2301        window: &mut Window,
 2302        cx: &mut Context<Self>,
 2303    ) {
 2304        self.show_inline_completions_override = show_edit_predictions;
 2305        self.update_edit_prediction_settings(cx);
 2306
 2307        if let Some(false) = show_edit_predictions {
 2308            self.discard_inline_completion(false, cx);
 2309        } else {
 2310            self.refresh_inline_completion(false, true, window, cx);
 2311        }
 2312    }
 2313
 2314    fn inline_completions_disabled_in_scope(
 2315        &self,
 2316        buffer: &Entity<Buffer>,
 2317        buffer_position: language::Anchor,
 2318        cx: &App,
 2319    ) -> bool {
 2320        let snapshot = buffer.read(cx).snapshot();
 2321        let settings = snapshot.settings_at(buffer_position, cx);
 2322
 2323        let Some(scope) = snapshot.language_scope_at(buffer_position) else {
 2324            return false;
 2325        };
 2326
 2327        scope.override_name().map_or(false, |scope_name| {
 2328            settings
 2329                .edit_predictions_disabled_in
 2330                .iter()
 2331                .any(|s| s == scope_name)
 2332        })
 2333    }
 2334
 2335    pub fn set_use_modal_editing(&mut self, to: bool) {
 2336        self.use_modal_editing = to;
 2337    }
 2338
 2339    pub fn use_modal_editing(&self) -> bool {
 2340        self.use_modal_editing
 2341    }
 2342
 2343    fn selections_did_change(
 2344        &mut self,
 2345        local: bool,
 2346        old_cursor_position: &Anchor,
 2347        show_completions: bool,
 2348        window: &mut Window,
 2349        cx: &mut Context<Self>,
 2350    ) {
 2351        window.invalidate_character_coordinates();
 2352
 2353        // Copy selections to primary selection buffer
 2354        #[cfg(any(target_os = "linux", target_os = "freebsd"))]
 2355        if local {
 2356            let selections = self.selections.all::<usize>(cx);
 2357            let buffer_handle = self.buffer.read(cx).read(cx);
 2358
 2359            let mut text = String::new();
 2360            for (index, selection) in selections.iter().enumerate() {
 2361                let text_for_selection = buffer_handle
 2362                    .text_for_range(selection.start..selection.end)
 2363                    .collect::<String>();
 2364
 2365                text.push_str(&text_for_selection);
 2366                if index != selections.len() - 1 {
 2367                    text.push('\n');
 2368                }
 2369            }
 2370
 2371            if !text.is_empty() {
 2372                cx.write_to_primary(ClipboardItem::new_string(text));
 2373            }
 2374        }
 2375
 2376        if self.focus_handle.is_focused(window) && self.leader_peer_id.is_none() {
 2377            self.buffer.update(cx, |buffer, cx| {
 2378                buffer.set_active_selections(
 2379                    &self.selections.disjoint_anchors(),
 2380                    self.selections.line_mode,
 2381                    self.cursor_shape,
 2382                    cx,
 2383                )
 2384            });
 2385        }
 2386        let display_map = self
 2387            .display_map
 2388            .update(cx, |display_map, cx| display_map.snapshot(cx));
 2389        let buffer = &display_map.buffer_snapshot;
 2390        self.add_selections_state = None;
 2391        self.select_next_state = None;
 2392        self.select_prev_state = None;
 2393        self.select_syntax_node_history.try_clear();
 2394        self.invalidate_autoclose_regions(&self.selections.disjoint_anchors(), buffer);
 2395        self.snippet_stack
 2396            .invalidate(&self.selections.disjoint_anchors(), buffer);
 2397        self.take_rename(false, window, cx);
 2398
 2399        let new_cursor_position = self.selections.newest_anchor().head();
 2400
 2401        self.push_to_nav_history(
 2402            *old_cursor_position,
 2403            Some(new_cursor_position.to_point(buffer)),
 2404            false,
 2405            cx,
 2406        );
 2407
 2408        if local {
 2409            let new_cursor_position = self.selections.newest_anchor().head();
 2410            let mut context_menu = self.context_menu.borrow_mut();
 2411            let completion_menu = match context_menu.as_ref() {
 2412                Some(CodeContextMenu::Completions(menu)) => Some(menu),
 2413                _ => {
 2414                    *context_menu = None;
 2415                    None
 2416                }
 2417            };
 2418            if let Some(buffer_id) = new_cursor_position.buffer_id {
 2419                if !self.registered_buffers.contains_key(&buffer_id) {
 2420                    if let Some(project) = self.project.as_ref() {
 2421                        project.update(cx, |project, cx| {
 2422                            let Some(buffer) = self.buffer.read(cx).buffer(buffer_id) else {
 2423                                return;
 2424                            };
 2425                            self.registered_buffers.insert(
 2426                                buffer_id,
 2427                                project.register_buffer_with_language_servers(&buffer, cx),
 2428                            );
 2429                        })
 2430                    }
 2431                }
 2432            }
 2433
 2434            if let Some(completion_menu) = completion_menu {
 2435                let cursor_position = new_cursor_position.to_offset(buffer);
 2436                let (word_range, kind) =
 2437                    buffer.surrounding_word(completion_menu.initial_position, true);
 2438                if kind == Some(CharKind::Word)
 2439                    && word_range.to_inclusive().contains(&cursor_position)
 2440                {
 2441                    let mut completion_menu = completion_menu.clone();
 2442                    drop(context_menu);
 2443
 2444                    let query = Self::completion_query(buffer, cursor_position);
 2445                    cx.spawn(async move |this, cx| {
 2446                        completion_menu
 2447                            .filter(query.as_deref(), cx.background_executor().clone())
 2448                            .await;
 2449
 2450                        this.update(cx, |this, cx| {
 2451                            let mut context_menu = this.context_menu.borrow_mut();
 2452                            let Some(CodeContextMenu::Completions(menu)) = context_menu.as_ref()
 2453                            else {
 2454                                return;
 2455                            };
 2456
 2457                            if menu.id > completion_menu.id {
 2458                                return;
 2459                            }
 2460
 2461                            *context_menu = Some(CodeContextMenu::Completions(completion_menu));
 2462                            drop(context_menu);
 2463                            cx.notify();
 2464                        })
 2465                    })
 2466                    .detach();
 2467
 2468                    if show_completions {
 2469                        self.show_completions(&ShowCompletions { trigger: None }, window, cx);
 2470                    }
 2471                } else {
 2472                    drop(context_menu);
 2473                    self.hide_context_menu(window, cx);
 2474                }
 2475            } else {
 2476                drop(context_menu);
 2477            }
 2478
 2479            hide_hover(self, cx);
 2480
 2481            if old_cursor_position.to_display_point(&display_map).row()
 2482                != new_cursor_position.to_display_point(&display_map).row()
 2483            {
 2484                self.available_code_actions.take();
 2485            }
 2486            self.refresh_code_actions(window, cx);
 2487            self.refresh_document_highlights(cx);
 2488            self.refresh_selected_text_highlights(window, cx);
 2489            refresh_matching_bracket_highlights(self, window, cx);
 2490            self.update_visible_inline_completion(window, cx);
 2491            self.edit_prediction_requires_modifier_in_indent_conflict = true;
 2492            linked_editing_ranges::refresh_linked_ranges(self, window, cx);
 2493            if self.git_blame_inline_enabled {
 2494                self.start_inline_blame_timer(window, cx);
 2495            }
 2496        }
 2497
 2498        self.blink_manager.update(cx, BlinkManager::pause_blinking);
 2499        cx.emit(EditorEvent::SelectionsChanged { local });
 2500
 2501        let selections = &self.selections.disjoint;
 2502        if selections.len() == 1 {
 2503            cx.emit(SearchEvent::ActiveMatchChanged)
 2504        }
 2505        if local {
 2506            if let Some((_, _, buffer_snapshot)) = buffer.as_singleton() {
 2507                let inmemory_selections = selections
 2508                    .iter()
 2509                    .map(|s| {
 2510                        text::ToPoint::to_point(&s.range().start.text_anchor, buffer_snapshot)
 2511                            ..text::ToPoint::to_point(&s.range().end.text_anchor, buffer_snapshot)
 2512                    })
 2513                    .collect();
 2514                self.update_restoration_data(cx, |data| {
 2515                    data.selections = inmemory_selections;
 2516                });
 2517
 2518                if WorkspaceSettings::get(None, cx).restore_on_startup
 2519                    != RestoreOnStartupBehavior::None
 2520                {
 2521                    if let Some(workspace_id) =
 2522                        self.workspace.as_ref().and_then(|workspace| workspace.1)
 2523                    {
 2524                        let snapshot = self.buffer().read(cx).snapshot(cx);
 2525                        let selections = selections.clone();
 2526                        let background_executor = cx.background_executor().clone();
 2527                        let editor_id = cx.entity().entity_id().as_u64() as ItemId;
 2528                        self.serialize_selections = cx.background_spawn(async move {
 2529                    background_executor.timer(SERIALIZATION_THROTTLE_TIME).await;
 2530                    let db_selections = selections
 2531                        .iter()
 2532                        .map(|selection| {
 2533                            (
 2534                                selection.start.to_offset(&snapshot),
 2535                                selection.end.to_offset(&snapshot),
 2536                            )
 2537                        })
 2538                        .collect();
 2539
 2540                    DB.save_editor_selections(editor_id, workspace_id, db_selections)
 2541                        .await
 2542                        .with_context(|| format!("persisting editor selections for editor {editor_id}, workspace {workspace_id:?}"))
 2543                        .log_err();
 2544                });
 2545                    }
 2546                }
 2547            }
 2548        }
 2549
 2550        cx.notify();
 2551    }
 2552
 2553    fn folds_did_change(&mut self, cx: &mut Context<Self>) {
 2554        use text::ToOffset as _;
 2555        use text::ToPoint as _;
 2556
 2557        if WorkspaceSettings::get(None, cx).restore_on_startup == RestoreOnStartupBehavior::None {
 2558            return;
 2559        }
 2560
 2561        let Some(singleton) = self.buffer().read(cx).as_singleton() else {
 2562            return;
 2563        };
 2564
 2565        let snapshot = singleton.read(cx).snapshot();
 2566        let inmemory_folds = self.display_map.update(cx, |display_map, cx| {
 2567            let display_snapshot = display_map.snapshot(cx);
 2568
 2569            display_snapshot
 2570                .folds_in_range(0..display_snapshot.buffer_snapshot.len())
 2571                .map(|fold| {
 2572                    fold.range.start.text_anchor.to_point(&snapshot)
 2573                        ..fold.range.end.text_anchor.to_point(&snapshot)
 2574                })
 2575                .collect()
 2576        });
 2577        self.update_restoration_data(cx, |data| {
 2578            data.folds = inmemory_folds;
 2579        });
 2580
 2581        let Some(workspace_id) = self.workspace.as_ref().and_then(|workspace| workspace.1) else {
 2582            return;
 2583        };
 2584        let background_executor = cx.background_executor().clone();
 2585        let editor_id = cx.entity().entity_id().as_u64() as ItemId;
 2586        let db_folds = self.display_map.update(cx, |display_map, cx| {
 2587            display_map
 2588                .snapshot(cx)
 2589                .folds_in_range(0..snapshot.len())
 2590                .map(|fold| {
 2591                    (
 2592                        fold.range.start.text_anchor.to_offset(&snapshot),
 2593                        fold.range.end.text_anchor.to_offset(&snapshot),
 2594                    )
 2595                })
 2596                .collect()
 2597        });
 2598        self.serialize_folds = cx.background_spawn(async move {
 2599            background_executor.timer(SERIALIZATION_THROTTLE_TIME).await;
 2600            DB.save_editor_folds(editor_id, workspace_id, db_folds)
 2601                .await
 2602                .with_context(|| {
 2603                    format!(
 2604                        "persisting editor folds for editor {editor_id}, workspace {workspace_id:?}"
 2605                    )
 2606                })
 2607                .log_err();
 2608        });
 2609    }
 2610
 2611    pub fn sync_selections(
 2612        &mut self,
 2613        other: Entity<Editor>,
 2614        cx: &mut Context<Self>,
 2615    ) -> gpui::Subscription {
 2616        let other_selections = other.read(cx).selections.disjoint.to_vec();
 2617        self.selections.change_with(cx, |selections| {
 2618            selections.select_anchors(other_selections);
 2619        });
 2620
 2621        let other_subscription =
 2622            cx.subscribe(&other, |this, other, other_evt, cx| match other_evt {
 2623                EditorEvent::SelectionsChanged { local: true } => {
 2624                    let other_selections = other.read(cx).selections.disjoint.to_vec();
 2625                    if other_selections.is_empty() {
 2626                        return;
 2627                    }
 2628                    this.selections.change_with(cx, |selections| {
 2629                        selections.select_anchors(other_selections);
 2630                    });
 2631                }
 2632                _ => {}
 2633            });
 2634
 2635        let this_subscription =
 2636            cx.subscribe_self::<EditorEvent>(move |this, this_evt, cx| match this_evt {
 2637                EditorEvent::SelectionsChanged { local: true } => {
 2638                    let these_selections = this.selections.disjoint.to_vec();
 2639                    if these_selections.is_empty() {
 2640                        return;
 2641                    }
 2642                    other.update(cx, |other_editor, cx| {
 2643                        other_editor.selections.change_with(cx, |selections| {
 2644                            selections.select_anchors(these_selections);
 2645                        })
 2646                    });
 2647                }
 2648                _ => {}
 2649            });
 2650
 2651        Subscription::join(other_subscription, this_subscription)
 2652    }
 2653
 2654    pub fn change_selections<R>(
 2655        &mut self,
 2656        autoscroll: Option<Autoscroll>,
 2657        window: &mut Window,
 2658        cx: &mut Context<Self>,
 2659        change: impl FnOnce(&mut MutableSelectionsCollection<'_>) -> R,
 2660    ) -> R {
 2661        self.change_selections_inner(autoscroll, true, window, cx, change)
 2662    }
 2663
 2664    fn change_selections_inner<R>(
 2665        &mut self,
 2666        autoscroll: Option<Autoscroll>,
 2667        request_completions: bool,
 2668        window: &mut Window,
 2669        cx: &mut Context<Self>,
 2670        change: impl FnOnce(&mut MutableSelectionsCollection<'_>) -> R,
 2671    ) -> R {
 2672        let old_cursor_position = self.selections.newest_anchor().head();
 2673        self.push_to_selection_history();
 2674
 2675        let (changed, result) = self.selections.change_with(cx, change);
 2676
 2677        if changed {
 2678            if let Some(autoscroll) = autoscroll {
 2679                self.request_autoscroll(autoscroll, cx);
 2680            }
 2681            self.selections_did_change(true, &old_cursor_position, request_completions, window, cx);
 2682
 2683            if self.should_open_signature_help_automatically(
 2684                &old_cursor_position,
 2685                self.signature_help_state.backspace_pressed(),
 2686                cx,
 2687            ) {
 2688                self.show_signature_help(&ShowSignatureHelp, window, cx);
 2689            }
 2690            self.signature_help_state.set_backspace_pressed(false);
 2691        }
 2692
 2693        result
 2694    }
 2695
 2696    pub fn edit<I, S, T>(&mut self, edits: I, cx: &mut Context<Self>)
 2697    where
 2698        I: IntoIterator<Item = (Range<S>, T)>,
 2699        S: ToOffset,
 2700        T: Into<Arc<str>>,
 2701    {
 2702        if self.read_only(cx) {
 2703            return;
 2704        }
 2705
 2706        self.buffer
 2707            .update(cx, |buffer, cx| buffer.edit(edits, None, cx));
 2708    }
 2709
 2710    pub fn edit_with_autoindent<I, S, T>(&mut self, edits: I, cx: &mut Context<Self>)
 2711    where
 2712        I: IntoIterator<Item = (Range<S>, T)>,
 2713        S: ToOffset,
 2714        T: Into<Arc<str>>,
 2715    {
 2716        if self.read_only(cx) {
 2717            return;
 2718        }
 2719
 2720        self.buffer.update(cx, |buffer, cx| {
 2721            buffer.edit(edits, self.autoindent_mode.clone(), cx)
 2722        });
 2723    }
 2724
 2725    pub fn edit_with_block_indent<I, S, T>(
 2726        &mut self,
 2727        edits: I,
 2728        original_indent_columns: Vec<Option<u32>>,
 2729        cx: &mut Context<Self>,
 2730    ) where
 2731        I: IntoIterator<Item = (Range<S>, T)>,
 2732        S: ToOffset,
 2733        T: Into<Arc<str>>,
 2734    {
 2735        if self.read_only(cx) {
 2736            return;
 2737        }
 2738
 2739        self.buffer.update(cx, |buffer, cx| {
 2740            buffer.edit(
 2741                edits,
 2742                Some(AutoindentMode::Block {
 2743                    original_indent_columns,
 2744                }),
 2745                cx,
 2746            )
 2747        });
 2748    }
 2749
 2750    fn select(&mut self, phase: SelectPhase, window: &mut Window, cx: &mut Context<Self>) {
 2751        self.hide_context_menu(window, cx);
 2752
 2753        match phase {
 2754            SelectPhase::Begin {
 2755                position,
 2756                add,
 2757                click_count,
 2758            } => self.begin_selection(position, add, click_count, window, cx),
 2759            SelectPhase::BeginColumnar {
 2760                position,
 2761                goal_column,
 2762                reset,
 2763            } => self.begin_columnar_selection(position, goal_column, reset, window, cx),
 2764            SelectPhase::Extend {
 2765                position,
 2766                click_count,
 2767            } => self.extend_selection(position, click_count, window, cx),
 2768            SelectPhase::Update {
 2769                position,
 2770                goal_column,
 2771                scroll_delta,
 2772            } => self.update_selection(position, goal_column, scroll_delta, window, cx),
 2773            SelectPhase::End => self.end_selection(window, cx),
 2774        }
 2775    }
 2776
 2777    fn extend_selection(
 2778        &mut self,
 2779        position: DisplayPoint,
 2780        click_count: usize,
 2781        window: &mut Window,
 2782        cx: &mut Context<Self>,
 2783    ) {
 2784        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 2785        let tail = self.selections.newest::<usize>(cx).tail();
 2786        self.begin_selection(position, false, click_count, window, cx);
 2787
 2788        let position = position.to_offset(&display_map, Bias::Left);
 2789        let tail_anchor = display_map.buffer_snapshot.anchor_before(tail);
 2790
 2791        let mut pending_selection = self
 2792            .selections
 2793            .pending_anchor()
 2794            .expect("extend_selection not called with pending selection");
 2795        if position >= tail {
 2796            pending_selection.start = tail_anchor;
 2797        } else {
 2798            pending_selection.end = tail_anchor;
 2799            pending_selection.reversed = true;
 2800        }
 2801
 2802        let mut pending_mode = self.selections.pending_mode().unwrap();
 2803        match &mut pending_mode {
 2804            SelectMode::Word(range) | SelectMode::Line(range) => *range = tail_anchor..tail_anchor,
 2805            _ => {}
 2806        }
 2807
 2808        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 2809            s.set_pending(pending_selection, pending_mode)
 2810        });
 2811    }
 2812
 2813    fn begin_selection(
 2814        &mut self,
 2815        position: DisplayPoint,
 2816        add: bool,
 2817        click_count: usize,
 2818        window: &mut Window,
 2819        cx: &mut Context<Self>,
 2820    ) {
 2821        if !self.focus_handle.is_focused(window) {
 2822            self.last_focused_descendant = None;
 2823            window.focus(&self.focus_handle);
 2824        }
 2825
 2826        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 2827        let buffer = &display_map.buffer_snapshot;
 2828        let newest_selection = self.selections.newest_anchor().clone();
 2829        let position = display_map.clip_point(position, Bias::Left);
 2830
 2831        let start;
 2832        let end;
 2833        let mode;
 2834        let mut auto_scroll;
 2835        match click_count {
 2836            1 => {
 2837                start = buffer.anchor_before(position.to_point(&display_map));
 2838                end = start;
 2839                mode = SelectMode::Character;
 2840                auto_scroll = true;
 2841            }
 2842            2 => {
 2843                let range = movement::surrounding_word(&display_map, position);
 2844                start = buffer.anchor_before(range.start.to_point(&display_map));
 2845                end = buffer.anchor_before(range.end.to_point(&display_map));
 2846                mode = SelectMode::Word(start..end);
 2847                auto_scroll = true;
 2848            }
 2849            3 => {
 2850                let position = display_map
 2851                    .clip_point(position, Bias::Left)
 2852                    .to_point(&display_map);
 2853                let line_start = display_map.prev_line_boundary(position).0;
 2854                let next_line_start = buffer.clip_point(
 2855                    display_map.next_line_boundary(position).0 + Point::new(1, 0),
 2856                    Bias::Left,
 2857                );
 2858                start = buffer.anchor_before(line_start);
 2859                end = buffer.anchor_before(next_line_start);
 2860                mode = SelectMode::Line(start..end);
 2861                auto_scroll = true;
 2862            }
 2863            _ => {
 2864                start = buffer.anchor_before(0);
 2865                end = buffer.anchor_before(buffer.len());
 2866                mode = SelectMode::All;
 2867                auto_scroll = false;
 2868            }
 2869        }
 2870        auto_scroll &= EditorSettings::get_global(cx).autoscroll_on_clicks;
 2871
 2872        let point_to_delete: Option<usize> = {
 2873            let selected_points: Vec<Selection<Point>> =
 2874                self.selections.disjoint_in_range(start..end, cx);
 2875
 2876            if !add || click_count > 1 {
 2877                None
 2878            } else if !selected_points.is_empty() {
 2879                Some(selected_points[0].id)
 2880            } else {
 2881                let clicked_point_already_selected =
 2882                    self.selections.disjoint.iter().find(|selection| {
 2883                        selection.start.to_point(buffer) == start.to_point(buffer)
 2884                            || selection.end.to_point(buffer) == end.to_point(buffer)
 2885                    });
 2886
 2887                clicked_point_already_selected.map(|selection| selection.id)
 2888            }
 2889        };
 2890
 2891        let selections_count = self.selections.count();
 2892
 2893        self.change_selections(auto_scroll.then(Autoscroll::newest), window, cx, |s| {
 2894            if let Some(point_to_delete) = point_to_delete {
 2895                s.delete(point_to_delete);
 2896
 2897                if selections_count == 1 {
 2898                    s.set_pending_anchor_range(start..end, mode);
 2899                }
 2900            } else {
 2901                if !add {
 2902                    s.clear_disjoint();
 2903                } else if click_count > 1 {
 2904                    s.delete(newest_selection.id)
 2905                }
 2906
 2907                s.set_pending_anchor_range(start..end, mode);
 2908            }
 2909        });
 2910    }
 2911
 2912    fn begin_columnar_selection(
 2913        &mut self,
 2914        position: DisplayPoint,
 2915        goal_column: u32,
 2916        reset: bool,
 2917        window: &mut Window,
 2918        cx: &mut Context<Self>,
 2919    ) {
 2920        if !self.focus_handle.is_focused(window) {
 2921            self.last_focused_descendant = None;
 2922            window.focus(&self.focus_handle);
 2923        }
 2924
 2925        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 2926
 2927        if reset {
 2928            let pointer_position = display_map
 2929                .buffer_snapshot
 2930                .anchor_before(position.to_point(&display_map));
 2931
 2932            self.change_selections(Some(Autoscroll::newest()), window, cx, |s| {
 2933                s.clear_disjoint();
 2934                s.set_pending_anchor_range(
 2935                    pointer_position..pointer_position,
 2936                    SelectMode::Character,
 2937                );
 2938            });
 2939        }
 2940
 2941        let tail = self.selections.newest::<Point>(cx).tail();
 2942        self.columnar_selection_tail = Some(display_map.buffer_snapshot.anchor_before(tail));
 2943
 2944        if !reset {
 2945            self.select_columns(
 2946                tail.to_display_point(&display_map),
 2947                position,
 2948                goal_column,
 2949                &display_map,
 2950                window,
 2951                cx,
 2952            );
 2953        }
 2954    }
 2955
 2956    fn update_selection(
 2957        &mut self,
 2958        position: DisplayPoint,
 2959        goal_column: u32,
 2960        scroll_delta: gpui::Point<f32>,
 2961        window: &mut Window,
 2962        cx: &mut Context<Self>,
 2963    ) {
 2964        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 2965
 2966        if let Some(tail) = self.columnar_selection_tail.as_ref() {
 2967            let tail = tail.to_display_point(&display_map);
 2968            self.select_columns(tail, position, goal_column, &display_map, window, cx);
 2969        } else if let Some(mut pending) = self.selections.pending_anchor() {
 2970            let buffer = self.buffer.read(cx).snapshot(cx);
 2971            let head;
 2972            let tail;
 2973            let mode = self.selections.pending_mode().unwrap();
 2974            match &mode {
 2975                SelectMode::Character => {
 2976                    head = position.to_point(&display_map);
 2977                    tail = pending.tail().to_point(&buffer);
 2978                }
 2979                SelectMode::Word(original_range) => {
 2980                    let original_display_range = original_range.start.to_display_point(&display_map)
 2981                        ..original_range.end.to_display_point(&display_map);
 2982                    let original_buffer_range = original_display_range.start.to_point(&display_map)
 2983                        ..original_display_range.end.to_point(&display_map);
 2984                    if movement::is_inside_word(&display_map, position)
 2985                        || original_display_range.contains(&position)
 2986                    {
 2987                        let word_range = movement::surrounding_word(&display_map, position);
 2988                        if word_range.start < original_display_range.start {
 2989                            head = word_range.start.to_point(&display_map);
 2990                        } else {
 2991                            head = word_range.end.to_point(&display_map);
 2992                        }
 2993                    } else {
 2994                        head = position.to_point(&display_map);
 2995                    }
 2996
 2997                    if head <= original_buffer_range.start {
 2998                        tail = original_buffer_range.end;
 2999                    } else {
 3000                        tail = original_buffer_range.start;
 3001                    }
 3002                }
 3003                SelectMode::Line(original_range) => {
 3004                    let original_range = original_range.to_point(&display_map.buffer_snapshot);
 3005
 3006                    let position = display_map
 3007                        .clip_point(position, Bias::Left)
 3008                        .to_point(&display_map);
 3009                    let line_start = display_map.prev_line_boundary(position).0;
 3010                    let next_line_start = buffer.clip_point(
 3011                        display_map.next_line_boundary(position).0 + Point::new(1, 0),
 3012                        Bias::Left,
 3013                    );
 3014
 3015                    if line_start < original_range.start {
 3016                        head = line_start
 3017                    } else {
 3018                        head = next_line_start
 3019                    }
 3020
 3021                    if head <= original_range.start {
 3022                        tail = original_range.end;
 3023                    } else {
 3024                        tail = original_range.start;
 3025                    }
 3026                }
 3027                SelectMode::All => {
 3028                    return;
 3029                }
 3030            };
 3031
 3032            if head < tail {
 3033                pending.start = buffer.anchor_before(head);
 3034                pending.end = buffer.anchor_before(tail);
 3035                pending.reversed = true;
 3036            } else {
 3037                pending.start = buffer.anchor_before(tail);
 3038                pending.end = buffer.anchor_before(head);
 3039                pending.reversed = false;
 3040            }
 3041
 3042            self.change_selections(None, window, cx, |s| {
 3043                s.set_pending(pending, mode);
 3044            });
 3045        } else {
 3046            log::error!("update_selection dispatched with no pending selection");
 3047            return;
 3048        }
 3049
 3050        self.apply_scroll_delta(scroll_delta, window, cx);
 3051        cx.notify();
 3052    }
 3053
 3054    fn end_selection(&mut self, window: &mut Window, cx: &mut Context<Self>) {
 3055        self.columnar_selection_tail.take();
 3056        if self.selections.pending_anchor().is_some() {
 3057            let selections = self.selections.all::<usize>(cx);
 3058            self.change_selections(None, window, cx, |s| {
 3059                s.select(selections);
 3060                s.clear_pending();
 3061            });
 3062        }
 3063    }
 3064
 3065    fn select_columns(
 3066        &mut self,
 3067        tail: DisplayPoint,
 3068        head: DisplayPoint,
 3069        goal_column: u32,
 3070        display_map: &DisplaySnapshot,
 3071        window: &mut Window,
 3072        cx: &mut Context<Self>,
 3073    ) {
 3074        let start_row = cmp::min(tail.row(), head.row());
 3075        let end_row = cmp::max(tail.row(), head.row());
 3076        let start_column = cmp::min(tail.column(), goal_column);
 3077        let end_column = cmp::max(tail.column(), goal_column);
 3078        let reversed = start_column < tail.column();
 3079
 3080        let selection_ranges = (start_row.0..=end_row.0)
 3081            .map(DisplayRow)
 3082            .filter_map(|row| {
 3083                if start_column <= display_map.line_len(row) && !display_map.is_block_line(row) {
 3084                    let start = display_map
 3085                        .clip_point(DisplayPoint::new(row, start_column), Bias::Left)
 3086                        .to_point(display_map);
 3087                    let end = display_map
 3088                        .clip_point(DisplayPoint::new(row, end_column), Bias::Right)
 3089                        .to_point(display_map);
 3090                    if reversed {
 3091                        Some(end..start)
 3092                    } else {
 3093                        Some(start..end)
 3094                    }
 3095                } else {
 3096                    None
 3097                }
 3098            })
 3099            .collect::<Vec<_>>();
 3100
 3101        self.change_selections(None, window, cx, |s| {
 3102            s.select_ranges(selection_ranges);
 3103        });
 3104        cx.notify();
 3105    }
 3106
 3107    pub fn has_pending_nonempty_selection(&self) -> bool {
 3108        let pending_nonempty_selection = match self.selections.pending_anchor() {
 3109            Some(Selection { start, end, .. }) => start != end,
 3110            None => false,
 3111        };
 3112
 3113        pending_nonempty_selection
 3114            || (self.columnar_selection_tail.is_some() && self.selections.disjoint.len() > 1)
 3115    }
 3116
 3117    pub fn has_pending_selection(&self) -> bool {
 3118        self.selections.pending_anchor().is_some() || self.columnar_selection_tail.is_some()
 3119    }
 3120
 3121    pub fn cancel(&mut self, _: &Cancel, window: &mut Window, cx: &mut Context<Self>) {
 3122        self.selection_mark_mode = false;
 3123
 3124        if self.clear_expanded_diff_hunks(cx) {
 3125            cx.notify();
 3126            return;
 3127        }
 3128        if self.dismiss_menus_and_popups(true, window, cx) {
 3129            return;
 3130        }
 3131
 3132        if self.mode.is_full()
 3133            && self.change_selections(Some(Autoscroll::fit()), window, cx, |s| s.try_cancel())
 3134        {
 3135            return;
 3136        }
 3137
 3138        cx.propagate();
 3139    }
 3140
 3141    pub fn dismiss_menus_and_popups(
 3142        &mut self,
 3143        is_user_requested: bool,
 3144        window: &mut Window,
 3145        cx: &mut Context<Self>,
 3146    ) -> bool {
 3147        if self.take_rename(false, window, cx).is_some() {
 3148            return true;
 3149        }
 3150
 3151        if hide_hover(self, cx) {
 3152            return true;
 3153        }
 3154
 3155        if self.hide_signature_help(cx, SignatureHelpHiddenBy::Escape) {
 3156            return true;
 3157        }
 3158
 3159        if self.hide_context_menu(window, cx).is_some() {
 3160            return true;
 3161        }
 3162
 3163        if self.mouse_context_menu.take().is_some() {
 3164            return true;
 3165        }
 3166
 3167        if is_user_requested && self.discard_inline_completion(true, cx) {
 3168            return true;
 3169        }
 3170
 3171        if self.snippet_stack.pop().is_some() {
 3172            return true;
 3173        }
 3174
 3175        if self.mode.is_full() && matches!(self.active_diagnostics, ActiveDiagnostic::Group(_)) {
 3176            self.dismiss_diagnostics(cx);
 3177            return true;
 3178        }
 3179
 3180        false
 3181    }
 3182
 3183    fn linked_editing_ranges_for(
 3184        &self,
 3185        selection: Range<text::Anchor>,
 3186        cx: &App,
 3187    ) -> Option<HashMap<Entity<Buffer>, Vec<Range<text::Anchor>>>> {
 3188        if self.linked_edit_ranges.is_empty() {
 3189            return None;
 3190        }
 3191        let ((base_range, linked_ranges), buffer_snapshot, buffer) =
 3192            selection.end.buffer_id.and_then(|end_buffer_id| {
 3193                if selection.start.buffer_id != Some(end_buffer_id) {
 3194                    return None;
 3195                }
 3196                let buffer = self.buffer.read(cx).buffer(end_buffer_id)?;
 3197                let snapshot = buffer.read(cx).snapshot();
 3198                self.linked_edit_ranges
 3199                    .get(end_buffer_id, selection.start..selection.end, &snapshot)
 3200                    .map(|ranges| (ranges, snapshot, buffer))
 3201            })?;
 3202        use text::ToOffset as TO;
 3203        // find offset from the start of current range to current cursor position
 3204        let start_byte_offset = TO::to_offset(&base_range.start, &buffer_snapshot);
 3205
 3206        let start_offset = TO::to_offset(&selection.start, &buffer_snapshot);
 3207        let start_difference = start_offset - start_byte_offset;
 3208        let end_offset = TO::to_offset(&selection.end, &buffer_snapshot);
 3209        let end_difference = end_offset - start_byte_offset;
 3210        // Current range has associated linked ranges.
 3211        let mut linked_edits = HashMap::<_, Vec<_>>::default();
 3212        for range in linked_ranges.iter() {
 3213            let start_offset = TO::to_offset(&range.start, &buffer_snapshot);
 3214            let end_offset = start_offset + end_difference;
 3215            let start_offset = start_offset + start_difference;
 3216            if start_offset > buffer_snapshot.len() || end_offset > buffer_snapshot.len() {
 3217                continue;
 3218            }
 3219            if self.selections.disjoint_anchor_ranges().any(|s| {
 3220                if s.start.buffer_id != selection.start.buffer_id
 3221                    || s.end.buffer_id != selection.end.buffer_id
 3222                {
 3223                    return false;
 3224                }
 3225                TO::to_offset(&s.start.text_anchor, &buffer_snapshot) <= end_offset
 3226                    && TO::to_offset(&s.end.text_anchor, &buffer_snapshot) >= start_offset
 3227            }) {
 3228                continue;
 3229            }
 3230            let start = buffer_snapshot.anchor_after(start_offset);
 3231            let end = buffer_snapshot.anchor_after(end_offset);
 3232            linked_edits
 3233                .entry(buffer.clone())
 3234                .or_default()
 3235                .push(start..end);
 3236        }
 3237        Some(linked_edits)
 3238    }
 3239
 3240    pub fn handle_input(&mut self, text: &str, window: &mut Window, cx: &mut Context<Self>) {
 3241        let text: Arc<str> = text.into();
 3242
 3243        if self.read_only(cx) {
 3244            return;
 3245        }
 3246
 3247        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
 3248
 3249        let selections = self.selections.all_adjusted(cx);
 3250        let mut bracket_inserted = false;
 3251        let mut edits = Vec::new();
 3252        let mut linked_edits = HashMap::<_, Vec<_>>::default();
 3253        let mut new_selections = Vec::with_capacity(selections.len());
 3254        let mut new_autoclose_regions = Vec::new();
 3255        let snapshot = self.buffer.read(cx).read(cx);
 3256        let mut clear_linked_edit_ranges = false;
 3257
 3258        for (selection, autoclose_region) in
 3259            self.selections_with_autoclose_regions(selections, &snapshot)
 3260        {
 3261            if let Some(scope) = snapshot.language_scope_at(selection.head()) {
 3262                // Determine if the inserted text matches the opening or closing
 3263                // bracket of any of this language's bracket pairs.
 3264                let mut bracket_pair = None;
 3265                let mut is_bracket_pair_start = false;
 3266                let mut is_bracket_pair_end = false;
 3267                if !text.is_empty() {
 3268                    let mut bracket_pair_matching_end = None;
 3269                    // `text` can be empty when a user is using IME (e.g. Chinese Wubi Simplified)
 3270                    //  and they are removing the character that triggered IME popup.
 3271                    for (pair, enabled) in scope.brackets() {
 3272                        if !pair.close && !pair.surround {
 3273                            continue;
 3274                        }
 3275
 3276                        if enabled && pair.start.ends_with(text.as_ref()) {
 3277                            let prefix_len = pair.start.len() - text.len();
 3278                            let preceding_text_matches_prefix = prefix_len == 0
 3279                                || (selection.start.column >= (prefix_len as u32)
 3280                                    && snapshot.contains_str_at(
 3281                                        Point::new(
 3282                                            selection.start.row,
 3283                                            selection.start.column - (prefix_len as u32),
 3284                                        ),
 3285                                        &pair.start[..prefix_len],
 3286                                    ));
 3287                            if preceding_text_matches_prefix {
 3288                                bracket_pair = Some(pair.clone());
 3289                                is_bracket_pair_start = true;
 3290                                break;
 3291                            }
 3292                        }
 3293                        if pair.end.as_str() == text.as_ref() && bracket_pair_matching_end.is_none()
 3294                        {
 3295                            // take first bracket pair matching end, but don't break in case a later bracket
 3296                            // pair matches start
 3297                            bracket_pair_matching_end = Some(pair.clone());
 3298                        }
 3299                    }
 3300                    if bracket_pair.is_none() && bracket_pair_matching_end.is_some() {
 3301                        bracket_pair = Some(bracket_pair_matching_end.unwrap());
 3302                        is_bracket_pair_end = true;
 3303                    }
 3304                }
 3305
 3306                if let Some(bracket_pair) = bracket_pair {
 3307                    let snapshot_settings = snapshot.language_settings_at(selection.start, cx);
 3308                    let autoclose = self.use_autoclose && snapshot_settings.use_autoclose;
 3309                    let auto_surround =
 3310                        self.use_auto_surround && snapshot_settings.use_auto_surround;
 3311                    if selection.is_empty() {
 3312                        if is_bracket_pair_start {
 3313                            // If the inserted text is a suffix of an opening bracket and the
 3314                            // selection is preceded by the rest of the opening bracket, then
 3315                            // insert the closing bracket.
 3316                            let following_text_allows_autoclose = snapshot
 3317                                .chars_at(selection.start)
 3318                                .next()
 3319                                .map_or(true, |c| scope.should_autoclose_before(c));
 3320
 3321                            let preceding_text_allows_autoclose = selection.start.column == 0
 3322                                || snapshot.reversed_chars_at(selection.start).next().map_or(
 3323                                    true,
 3324                                    |c| {
 3325                                        bracket_pair.start != bracket_pair.end
 3326                                            || !snapshot
 3327                                                .char_classifier_at(selection.start)
 3328                                                .is_word(c)
 3329                                    },
 3330                                );
 3331
 3332                            let is_closing_quote = if bracket_pair.end == bracket_pair.start
 3333                                && bracket_pair.start.len() == 1
 3334                            {
 3335                                let target = bracket_pair.start.chars().next().unwrap();
 3336                                let current_line_count = snapshot
 3337                                    .reversed_chars_at(selection.start)
 3338                                    .take_while(|&c| c != '\n')
 3339                                    .filter(|&c| c == target)
 3340                                    .count();
 3341                                current_line_count % 2 == 1
 3342                            } else {
 3343                                false
 3344                            };
 3345
 3346                            if autoclose
 3347                                && bracket_pair.close
 3348                                && following_text_allows_autoclose
 3349                                && preceding_text_allows_autoclose
 3350                                && !is_closing_quote
 3351                            {
 3352                                let anchor = snapshot.anchor_before(selection.end);
 3353                                new_selections.push((selection.map(|_| anchor), text.len()));
 3354                                new_autoclose_regions.push((
 3355                                    anchor,
 3356                                    text.len(),
 3357                                    selection.id,
 3358                                    bracket_pair.clone(),
 3359                                ));
 3360                                edits.push((
 3361                                    selection.range(),
 3362                                    format!("{}{}", text, bracket_pair.end).into(),
 3363                                ));
 3364                                bracket_inserted = true;
 3365                                continue;
 3366                            }
 3367                        }
 3368
 3369                        if let Some(region) = autoclose_region {
 3370                            // If the selection is followed by an auto-inserted closing bracket,
 3371                            // then don't insert that closing bracket again; just move the selection
 3372                            // past the closing bracket.
 3373                            let should_skip = selection.end == region.range.end.to_point(&snapshot)
 3374                                && text.as_ref() == region.pair.end.as_str();
 3375                            if should_skip {
 3376                                let anchor = snapshot.anchor_after(selection.end);
 3377                                new_selections
 3378                                    .push((selection.map(|_| anchor), region.pair.end.len()));
 3379                                continue;
 3380                            }
 3381                        }
 3382
 3383                        let always_treat_brackets_as_autoclosed = snapshot
 3384                            .language_settings_at(selection.start, cx)
 3385                            .always_treat_brackets_as_autoclosed;
 3386                        if always_treat_brackets_as_autoclosed
 3387                            && is_bracket_pair_end
 3388                            && snapshot.contains_str_at(selection.end, text.as_ref())
 3389                        {
 3390                            // Otherwise, when `always_treat_brackets_as_autoclosed` is set to `true
 3391                            // and the inserted text is a closing bracket and the selection is followed
 3392                            // by the closing bracket then move the selection past the closing bracket.
 3393                            let anchor = snapshot.anchor_after(selection.end);
 3394                            new_selections.push((selection.map(|_| anchor), text.len()));
 3395                            continue;
 3396                        }
 3397                    }
 3398                    // If an opening bracket is 1 character long and is typed while
 3399                    // text is selected, then surround that text with the bracket pair.
 3400                    else if auto_surround
 3401                        && bracket_pair.surround
 3402                        && is_bracket_pair_start
 3403                        && bracket_pair.start.chars().count() == 1
 3404                    {
 3405                        edits.push((selection.start..selection.start, text.clone()));
 3406                        edits.push((
 3407                            selection.end..selection.end,
 3408                            bracket_pair.end.as_str().into(),
 3409                        ));
 3410                        bracket_inserted = true;
 3411                        new_selections.push((
 3412                            Selection {
 3413                                id: selection.id,
 3414                                start: snapshot.anchor_after(selection.start),
 3415                                end: snapshot.anchor_before(selection.end),
 3416                                reversed: selection.reversed,
 3417                                goal: selection.goal,
 3418                            },
 3419                            0,
 3420                        ));
 3421                        continue;
 3422                    }
 3423                }
 3424            }
 3425
 3426            if self.auto_replace_emoji_shortcode
 3427                && selection.is_empty()
 3428                && text.as_ref().ends_with(':')
 3429            {
 3430                if let Some(possible_emoji_short_code) =
 3431                    Self::find_possible_emoji_shortcode_at_position(&snapshot, selection.start)
 3432                {
 3433                    if !possible_emoji_short_code.is_empty() {
 3434                        if let Some(emoji) = emojis::get_by_shortcode(&possible_emoji_short_code) {
 3435                            let emoji_shortcode_start = Point::new(
 3436                                selection.start.row,
 3437                                selection.start.column - possible_emoji_short_code.len() as u32 - 1,
 3438                            );
 3439
 3440                            // Remove shortcode from buffer
 3441                            edits.push((
 3442                                emoji_shortcode_start..selection.start,
 3443                                "".to_string().into(),
 3444                            ));
 3445                            new_selections.push((
 3446                                Selection {
 3447                                    id: selection.id,
 3448                                    start: snapshot.anchor_after(emoji_shortcode_start),
 3449                                    end: snapshot.anchor_before(selection.start),
 3450                                    reversed: selection.reversed,
 3451                                    goal: selection.goal,
 3452                                },
 3453                                0,
 3454                            ));
 3455
 3456                            // Insert emoji
 3457                            let selection_start_anchor = snapshot.anchor_after(selection.start);
 3458                            new_selections.push((selection.map(|_| selection_start_anchor), 0));
 3459                            edits.push((selection.start..selection.end, emoji.to_string().into()));
 3460
 3461                            continue;
 3462                        }
 3463                    }
 3464                }
 3465            }
 3466
 3467            // If not handling any auto-close operation, then just replace the selected
 3468            // text with the given input and move the selection to the end of the
 3469            // newly inserted text.
 3470            let anchor = snapshot.anchor_after(selection.end);
 3471            if !self.linked_edit_ranges.is_empty() {
 3472                let start_anchor = snapshot.anchor_before(selection.start);
 3473
 3474                let is_word_char = text.chars().next().map_or(true, |char| {
 3475                    let classifier = snapshot.char_classifier_at(start_anchor.to_offset(&snapshot));
 3476                    classifier.is_word(char)
 3477                });
 3478
 3479                if is_word_char {
 3480                    if let Some(ranges) = self
 3481                        .linked_editing_ranges_for(start_anchor.text_anchor..anchor.text_anchor, cx)
 3482                    {
 3483                        for (buffer, edits) in ranges {
 3484                            linked_edits
 3485                                .entry(buffer.clone())
 3486                                .or_default()
 3487                                .extend(edits.into_iter().map(|range| (range, text.clone())));
 3488                        }
 3489                    }
 3490                } else {
 3491                    clear_linked_edit_ranges = true;
 3492                }
 3493            }
 3494
 3495            new_selections.push((selection.map(|_| anchor), 0));
 3496            edits.push((selection.start..selection.end, text.clone()));
 3497        }
 3498
 3499        drop(snapshot);
 3500
 3501        self.transact(window, cx, |this, window, cx| {
 3502            if clear_linked_edit_ranges {
 3503                this.linked_edit_ranges.clear();
 3504            }
 3505            let initial_buffer_versions =
 3506                jsx_tag_auto_close::construct_initial_buffer_versions_map(this, &edits, cx);
 3507
 3508            this.buffer.update(cx, |buffer, cx| {
 3509                buffer.edit(edits, this.autoindent_mode.clone(), cx);
 3510            });
 3511            for (buffer, edits) in linked_edits {
 3512                buffer.update(cx, |buffer, cx| {
 3513                    let snapshot = buffer.snapshot();
 3514                    let edits = edits
 3515                        .into_iter()
 3516                        .map(|(range, text)| {
 3517                            use text::ToPoint as TP;
 3518                            let end_point = TP::to_point(&range.end, &snapshot);
 3519                            let start_point = TP::to_point(&range.start, &snapshot);
 3520                            (start_point..end_point, text)
 3521                        })
 3522                        .sorted_by_key(|(range, _)| range.start);
 3523                    buffer.edit(edits, None, cx);
 3524                })
 3525            }
 3526            let new_anchor_selections = new_selections.iter().map(|e| &e.0);
 3527            let new_selection_deltas = new_selections.iter().map(|e| e.1);
 3528            let map = this.display_map.update(cx, |map, cx| map.snapshot(cx));
 3529            let new_selections = resolve_selections::<usize, _>(new_anchor_selections, &map)
 3530                .zip(new_selection_deltas)
 3531                .map(|(selection, delta)| Selection {
 3532                    id: selection.id,
 3533                    start: selection.start + delta,
 3534                    end: selection.end + delta,
 3535                    reversed: selection.reversed,
 3536                    goal: SelectionGoal::None,
 3537                })
 3538                .collect::<Vec<_>>();
 3539
 3540            let mut i = 0;
 3541            for (position, delta, selection_id, pair) in new_autoclose_regions {
 3542                let position = position.to_offset(&map.buffer_snapshot) + delta;
 3543                let start = map.buffer_snapshot.anchor_before(position);
 3544                let end = map.buffer_snapshot.anchor_after(position);
 3545                while let Some(existing_state) = this.autoclose_regions.get(i) {
 3546                    match existing_state.range.start.cmp(&start, &map.buffer_snapshot) {
 3547                        Ordering::Less => i += 1,
 3548                        Ordering::Greater => break,
 3549                        Ordering::Equal => {
 3550                            match end.cmp(&existing_state.range.end, &map.buffer_snapshot) {
 3551                                Ordering::Less => i += 1,
 3552                                Ordering::Equal => break,
 3553                                Ordering::Greater => break,
 3554                            }
 3555                        }
 3556                    }
 3557                }
 3558                this.autoclose_regions.insert(
 3559                    i,
 3560                    AutocloseRegion {
 3561                        selection_id,
 3562                        range: start..end,
 3563                        pair,
 3564                    },
 3565                );
 3566            }
 3567
 3568            let had_active_inline_completion = this.has_active_inline_completion();
 3569            this.change_selections_inner(Some(Autoscroll::fit()), false, window, cx, |s| {
 3570                s.select(new_selections)
 3571            });
 3572
 3573            if !bracket_inserted {
 3574                if let Some(on_type_format_task) =
 3575                    this.trigger_on_type_formatting(text.to_string(), window, cx)
 3576                {
 3577                    on_type_format_task.detach_and_log_err(cx);
 3578                }
 3579            }
 3580
 3581            let editor_settings = EditorSettings::get_global(cx);
 3582            if bracket_inserted
 3583                && (editor_settings.auto_signature_help
 3584                    || editor_settings.show_signature_help_after_edits)
 3585            {
 3586                this.show_signature_help(&ShowSignatureHelp, window, cx);
 3587            }
 3588
 3589            let trigger_in_words =
 3590                this.show_edit_predictions_in_menu() || !had_active_inline_completion;
 3591            if this.hard_wrap.is_some() {
 3592                let latest: Range<Point> = this.selections.newest(cx).range();
 3593                if latest.is_empty()
 3594                    && this
 3595                        .buffer()
 3596                        .read(cx)
 3597                        .snapshot(cx)
 3598                        .line_len(MultiBufferRow(latest.start.row))
 3599                        == latest.start.column
 3600                {
 3601                    this.rewrap_impl(
 3602                        RewrapOptions {
 3603                            override_language_settings: true,
 3604                            preserve_existing_whitespace: true,
 3605                        },
 3606                        cx,
 3607                    )
 3608                }
 3609            }
 3610            this.trigger_completion_on_input(&text, trigger_in_words, window, cx);
 3611            linked_editing_ranges::refresh_linked_ranges(this, window, cx);
 3612            this.refresh_inline_completion(true, false, window, cx);
 3613            jsx_tag_auto_close::handle_from(this, initial_buffer_versions, window, cx);
 3614        });
 3615    }
 3616
 3617    fn find_possible_emoji_shortcode_at_position(
 3618        snapshot: &MultiBufferSnapshot,
 3619        position: Point,
 3620    ) -> Option<String> {
 3621        let mut chars = Vec::new();
 3622        let mut found_colon = false;
 3623        for char in snapshot.reversed_chars_at(position).take(100) {
 3624            // Found a possible emoji shortcode in the middle of the buffer
 3625            if found_colon {
 3626                if char.is_whitespace() {
 3627                    chars.reverse();
 3628                    return Some(chars.iter().collect());
 3629                }
 3630                // If the previous character is not a whitespace, we are in the middle of a word
 3631                // and we only want to complete the shortcode if the word is made up of other emojis
 3632                let mut containing_word = String::new();
 3633                for ch in snapshot
 3634                    .reversed_chars_at(position)
 3635                    .skip(chars.len() + 1)
 3636                    .take(100)
 3637                {
 3638                    if ch.is_whitespace() {
 3639                        break;
 3640                    }
 3641                    containing_word.push(ch);
 3642                }
 3643                let containing_word = containing_word.chars().rev().collect::<String>();
 3644                if util::word_consists_of_emojis(containing_word.as_str()) {
 3645                    chars.reverse();
 3646                    return Some(chars.iter().collect());
 3647                }
 3648            }
 3649
 3650            if char.is_whitespace() || !char.is_ascii() {
 3651                return None;
 3652            }
 3653            if char == ':' {
 3654                found_colon = true;
 3655            } else {
 3656                chars.push(char);
 3657            }
 3658        }
 3659        // Found a possible emoji shortcode at the beginning of the buffer
 3660        chars.reverse();
 3661        Some(chars.iter().collect())
 3662    }
 3663
 3664    pub fn newline(&mut self, _: &Newline, window: &mut Window, cx: &mut Context<Self>) {
 3665        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
 3666        self.transact(window, cx, |this, window, cx| {
 3667            let (edits, selection_fixup_info): (Vec<_>, Vec<_>) = {
 3668                let selections = this.selections.all::<usize>(cx);
 3669                let multi_buffer = this.buffer.read(cx);
 3670                let buffer = multi_buffer.snapshot(cx);
 3671                selections
 3672                    .iter()
 3673                    .map(|selection| {
 3674                        let start_point = selection.start.to_point(&buffer);
 3675                        let mut indent =
 3676                            buffer.indent_size_for_line(MultiBufferRow(start_point.row));
 3677                        indent.len = cmp::min(indent.len, start_point.column);
 3678                        let start = selection.start;
 3679                        let end = selection.end;
 3680                        let selection_is_empty = start == end;
 3681                        let language_scope = buffer.language_scope_at(start);
 3682                        let (comment_delimiter, insert_extra_newline) = if let Some(language) =
 3683                            &language_scope
 3684                        {
 3685                            let insert_extra_newline =
 3686                                insert_extra_newline_brackets(&buffer, start..end, language)
 3687                                    || insert_extra_newline_tree_sitter(&buffer, start..end);
 3688
 3689                            // Comment extension on newline is allowed only for cursor selections
 3690                            let comment_delimiter = maybe!({
 3691                                if !selection_is_empty {
 3692                                    return None;
 3693                                }
 3694
 3695                                if !multi_buffer.language_settings(cx).extend_comment_on_newline {
 3696                                    return None;
 3697                                }
 3698
 3699                                let delimiters = language.line_comment_prefixes();
 3700                                let max_len_of_delimiter =
 3701                                    delimiters.iter().map(|delimiter| delimiter.len()).max()?;
 3702                                let (snapshot, range) =
 3703                                    buffer.buffer_line_for_row(MultiBufferRow(start_point.row))?;
 3704
 3705                                let mut index_of_first_non_whitespace = 0;
 3706                                let comment_candidate = snapshot
 3707                                    .chars_for_range(range)
 3708                                    .skip_while(|c| {
 3709                                        let should_skip = c.is_whitespace();
 3710                                        if should_skip {
 3711                                            index_of_first_non_whitespace += 1;
 3712                                        }
 3713                                        should_skip
 3714                                    })
 3715                                    .take(max_len_of_delimiter)
 3716                                    .collect::<String>();
 3717                                let comment_prefix = delimiters.iter().find(|comment_prefix| {
 3718                                    comment_candidate.starts_with(comment_prefix.as_ref())
 3719                                })?;
 3720                                let cursor_is_placed_after_comment_marker =
 3721                                    index_of_first_non_whitespace + comment_prefix.len()
 3722                                        <= start_point.column as usize;
 3723                                if cursor_is_placed_after_comment_marker {
 3724                                    Some(comment_prefix.clone())
 3725                                } else {
 3726                                    None
 3727                                }
 3728                            });
 3729                            (comment_delimiter, insert_extra_newline)
 3730                        } else {
 3731                            (None, false)
 3732                        };
 3733
 3734                        let capacity_for_delimiter = comment_delimiter
 3735                            .as_deref()
 3736                            .map(str::len)
 3737                            .unwrap_or_default();
 3738                        let mut new_text =
 3739                            String::with_capacity(1 + capacity_for_delimiter + indent.len as usize);
 3740                        new_text.push('\n');
 3741                        new_text.extend(indent.chars());
 3742                        if let Some(delimiter) = &comment_delimiter {
 3743                            new_text.push_str(delimiter);
 3744                        }
 3745                        if insert_extra_newline {
 3746                            new_text = new_text.repeat(2);
 3747                        }
 3748
 3749                        let anchor = buffer.anchor_after(end);
 3750                        let new_selection = selection.map(|_| anchor);
 3751                        (
 3752                            (start..end, new_text),
 3753                            (insert_extra_newline, new_selection),
 3754                        )
 3755                    })
 3756                    .unzip()
 3757            };
 3758
 3759            this.edit_with_autoindent(edits, cx);
 3760            let buffer = this.buffer.read(cx).snapshot(cx);
 3761            let new_selections = selection_fixup_info
 3762                .into_iter()
 3763                .map(|(extra_newline_inserted, new_selection)| {
 3764                    let mut cursor = new_selection.end.to_point(&buffer);
 3765                    if extra_newline_inserted {
 3766                        cursor.row -= 1;
 3767                        cursor.column = buffer.line_len(MultiBufferRow(cursor.row));
 3768                    }
 3769                    new_selection.map(|_| cursor)
 3770                })
 3771                .collect();
 3772
 3773            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 3774                s.select(new_selections)
 3775            });
 3776            this.refresh_inline_completion(true, false, window, cx);
 3777        });
 3778    }
 3779
 3780    pub fn newline_above(&mut self, _: &NewlineAbove, window: &mut Window, cx: &mut Context<Self>) {
 3781        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
 3782
 3783        let buffer = self.buffer.read(cx);
 3784        let snapshot = buffer.snapshot(cx);
 3785
 3786        let mut edits = Vec::new();
 3787        let mut rows = Vec::new();
 3788
 3789        for (rows_inserted, selection) in self.selections.all_adjusted(cx).into_iter().enumerate() {
 3790            let cursor = selection.head();
 3791            let row = cursor.row;
 3792
 3793            let start_of_line = snapshot.clip_point(Point::new(row, 0), Bias::Left);
 3794
 3795            let newline = "\n".to_string();
 3796            edits.push((start_of_line..start_of_line, newline));
 3797
 3798            rows.push(row + rows_inserted as u32);
 3799        }
 3800
 3801        self.transact(window, cx, |editor, window, cx| {
 3802            editor.edit(edits, cx);
 3803
 3804            editor.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 3805                let mut index = 0;
 3806                s.move_cursors_with(|map, _, _| {
 3807                    let row = rows[index];
 3808                    index += 1;
 3809
 3810                    let point = Point::new(row, 0);
 3811                    let boundary = map.next_line_boundary(point).1;
 3812                    let clipped = map.clip_point(boundary, Bias::Left);
 3813
 3814                    (clipped, SelectionGoal::None)
 3815                });
 3816            });
 3817
 3818            let mut indent_edits = Vec::new();
 3819            let multibuffer_snapshot = editor.buffer.read(cx).snapshot(cx);
 3820            for row in rows {
 3821                let indents = multibuffer_snapshot.suggested_indents(row..row + 1, cx);
 3822                for (row, indent) in indents {
 3823                    if indent.len == 0 {
 3824                        continue;
 3825                    }
 3826
 3827                    let text = match indent.kind {
 3828                        IndentKind::Space => " ".repeat(indent.len as usize),
 3829                        IndentKind::Tab => "\t".repeat(indent.len as usize),
 3830                    };
 3831                    let point = Point::new(row.0, 0);
 3832                    indent_edits.push((point..point, text));
 3833                }
 3834            }
 3835            editor.edit(indent_edits, cx);
 3836        });
 3837    }
 3838
 3839    pub fn newline_below(&mut self, _: &NewlineBelow, window: &mut Window, cx: &mut Context<Self>) {
 3840        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
 3841
 3842        let buffer = self.buffer.read(cx);
 3843        let snapshot = buffer.snapshot(cx);
 3844
 3845        let mut edits = Vec::new();
 3846        let mut rows = Vec::new();
 3847        let mut rows_inserted = 0;
 3848
 3849        for selection in self.selections.all_adjusted(cx) {
 3850            let cursor = selection.head();
 3851            let row = cursor.row;
 3852
 3853            let point = Point::new(row + 1, 0);
 3854            let start_of_line = snapshot.clip_point(point, Bias::Left);
 3855
 3856            let newline = "\n".to_string();
 3857            edits.push((start_of_line..start_of_line, newline));
 3858
 3859            rows_inserted += 1;
 3860            rows.push(row + rows_inserted);
 3861        }
 3862
 3863        self.transact(window, cx, |editor, window, cx| {
 3864            editor.edit(edits, cx);
 3865
 3866            editor.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 3867                let mut index = 0;
 3868                s.move_cursors_with(|map, _, _| {
 3869                    let row = rows[index];
 3870                    index += 1;
 3871
 3872                    let point = Point::new(row, 0);
 3873                    let boundary = map.next_line_boundary(point).1;
 3874                    let clipped = map.clip_point(boundary, Bias::Left);
 3875
 3876                    (clipped, SelectionGoal::None)
 3877                });
 3878            });
 3879
 3880            let mut indent_edits = Vec::new();
 3881            let multibuffer_snapshot = editor.buffer.read(cx).snapshot(cx);
 3882            for row in rows {
 3883                let indents = multibuffer_snapshot.suggested_indents(row..row + 1, cx);
 3884                for (row, indent) in indents {
 3885                    if indent.len == 0 {
 3886                        continue;
 3887                    }
 3888
 3889                    let text = match indent.kind {
 3890                        IndentKind::Space => " ".repeat(indent.len as usize),
 3891                        IndentKind::Tab => "\t".repeat(indent.len as usize),
 3892                    };
 3893                    let point = Point::new(row.0, 0);
 3894                    indent_edits.push((point..point, text));
 3895                }
 3896            }
 3897            editor.edit(indent_edits, cx);
 3898        });
 3899    }
 3900
 3901    pub fn insert(&mut self, text: &str, window: &mut Window, cx: &mut Context<Self>) {
 3902        let autoindent = text.is_empty().not().then(|| AutoindentMode::Block {
 3903            original_indent_columns: Vec::new(),
 3904        });
 3905        self.insert_with_autoindent_mode(text, autoindent, window, cx);
 3906    }
 3907
 3908    fn insert_with_autoindent_mode(
 3909        &mut self,
 3910        text: &str,
 3911        autoindent_mode: Option<AutoindentMode>,
 3912        window: &mut Window,
 3913        cx: &mut Context<Self>,
 3914    ) {
 3915        if self.read_only(cx) {
 3916            return;
 3917        }
 3918
 3919        let text: Arc<str> = text.into();
 3920        self.transact(window, cx, |this, window, cx| {
 3921            let old_selections = this.selections.all_adjusted(cx);
 3922            let selection_anchors = this.buffer.update(cx, |buffer, cx| {
 3923                let anchors = {
 3924                    let snapshot = buffer.read(cx);
 3925                    old_selections
 3926                        .iter()
 3927                        .map(|s| {
 3928                            let anchor = snapshot.anchor_after(s.head());
 3929                            s.map(|_| anchor)
 3930                        })
 3931                        .collect::<Vec<_>>()
 3932                };
 3933                buffer.edit(
 3934                    old_selections
 3935                        .iter()
 3936                        .map(|s| (s.start..s.end, text.clone())),
 3937                    autoindent_mode,
 3938                    cx,
 3939                );
 3940                anchors
 3941            });
 3942
 3943            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 3944                s.select_anchors(selection_anchors);
 3945            });
 3946
 3947            cx.notify();
 3948        });
 3949    }
 3950
 3951    fn trigger_completion_on_input(
 3952        &mut self,
 3953        text: &str,
 3954        trigger_in_words: bool,
 3955        window: &mut Window,
 3956        cx: &mut Context<Self>,
 3957    ) {
 3958        let ignore_completion_provider = self
 3959            .context_menu
 3960            .borrow()
 3961            .as_ref()
 3962            .map(|menu| match menu {
 3963                CodeContextMenu::Completions(completions_menu) => {
 3964                    completions_menu.ignore_completion_provider
 3965                }
 3966                CodeContextMenu::CodeActions(_) => false,
 3967            })
 3968            .unwrap_or(false);
 3969
 3970        if ignore_completion_provider {
 3971            self.show_word_completions(&ShowWordCompletions, window, cx);
 3972        } else if self.is_completion_trigger(text, trigger_in_words, cx) {
 3973            self.show_completions(
 3974                &ShowCompletions {
 3975                    trigger: Some(text.to_owned()).filter(|x| !x.is_empty()),
 3976                },
 3977                window,
 3978                cx,
 3979            );
 3980        } else {
 3981            self.hide_context_menu(window, cx);
 3982        }
 3983    }
 3984
 3985    fn is_completion_trigger(
 3986        &self,
 3987        text: &str,
 3988        trigger_in_words: bool,
 3989        cx: &mut Context<Self>,
 3990    ) -> bool {
 3991        let position = self.selections.newest_anchor().head();
 3992        let multibuffer = self.buffer.read(cx);
 3993        let Some(buffer) = position
 3994            .buffer_id
 3995            .and_then(|buffer_id| multibuffer.buffer(buffer_id).clone())
 3996        else {
 3997            return false;
 3998        };
 3999
 4000        if let Some(completion_provider) = &self.completion_provider {
 4001            completion_provider.is_completion_trigger(
 4002                &buffer,
 4003                position.text_anchor,
 4004                text,
 4005                trigger_in_words,
 4006                cx,
 4007            )
 4008        } else {
 4009            false
 4010        }
 4011    }
 4012
 4013    /// If any empty selections is touching the start of its innermost containing autoclose
 4014    /// region, expand it to select the brackets.
 4015    fn select_autoclose_pair(&mut self, window: &mut Window, cx: &mut Context<Self>) {
 4016        let selections = self.selections.all::<usize>(cx);
 4017        let buffer = self.buffer.read(cx).read(cx);
 4018        let new_selections = self
 4019            .selections_with_autoclose_regions(selections, &buffer)
 4020            .map(|(mut selection, region)| {
 4021                if !selection.is_empty() {
 4022                    return selection;
 4023                }
 4024
 4025                if let Some(region) = region {
 4026                    let mut range = region.range.to_offset(&buffer);
 4027                    if selection.start == range.start && range.start >= region.pair.start.len() {
 4028                        range.start -= region.pair.start.len();
 4029                        if buffer.contains_str_at(range.start, &region.pair.start)
 4030                            && buffer.contains_str_at(range.end, &region.pair.end)
 4031                        {
 4032                            range.end += region.pair.end.len();
 4033                            selection.start = range.start;
 4034                            selection.end = range.end;
 4035
 4036                            return selection;
 4037                        }
 4038                    }
 4039                }
 4040
 4041                let always_treat_brackets_as_autoclosed = buffer
 4042                    .language_settings_at(selection.start, cx)
 4043                    .always_treat_brackets_as_autoclosed;
 4044
 4045                if !always_treat_brackets_as_autoclosed {
 4046                    return selection;
 4047                }
 4048
 4049                if let Some(scope) = buffer.language_scope_at(selection.start) {
 4050                    for (pair, enabled) in scope.brackets() {
 4051                        if !enabled || !pair.close {
 4052                            continue;
 4053                        }
 4054
 4055                        if buffer.contains_str_at(selection.start, &pair.end) {
 4056                            let pair_start_len = pair.start.len();
 4057                            if buffer.contains_str_at(
 4058                                selection.start.saturating_sub(pair_start_len),
 4059                                &pair.start,
 4060                            ) {
 4061                                selection.start -= pair_start_len;
 4062                                selection.end += pair.end.len();
 4063
 4064                                return selection;
 4065                            }
 4066                        }
 4067                    }
 4068                }
 4069
 4070                selection
 4071            })
 4072            .collect();
 4073
 4074        drop(buffer);
 4075        self.change_selections(None, window, cx, |selections| {
 4076            selections.select(new_selections)
 4077        });
 4078    }
 4079
 4080    /// Iterate the given selections, and for each one, find the smallest surrounding
 4081    /// autoclose region. This uses the ordering of the selections and the autoclose
 4082    /// regions to avoid repeated comparisons.
 4083    fn selections_with_autoclose_regions<'a, D: ToOffset + Clone>(
 4084        &'a self,
 4085        selections: impl IntoIterator<Item = Selection<D>>,
 4086        buffer: &'a MultiBufferSnapshot,
 4087    ) -> impl Iterator<Item = (Selection<D>, Option<&'a AutocloseRegion>)> {
 4088        let mut i = 0;
 4089        let mut regions = self.autoclose_regions.as_slice();
 4090        selections.into_iter().map(move |selection| {
 4091            let range = selection.start.to_offset(buffer)..selection.end.to_offset(buffer);
 4092
 4093            let mut enclosing = None;
 4094            while let Some(pair_state) = regions.get(i) {
 4095                if pair_state.range.end.to_offset(buffer) < range.start {
 4096                    regions = &regions[i + 1..];
 4097                    i = 0;
 4098                } else if pair_state.range.start.to_offset(buffer) > range.end {
 4099                    break;
 4100                } else {
 4101                    if pair_state.selection_id == selection.id {
 4102                        enclosing = Some(pair_state);
 4103                    }
 4104                    i += 1;
 4105                }
 4106            }
 4107
 4108            (selection, enclosing)
 4109        })
 4110    }
 4111
 4112    /// Remove any autoclose regions that no longer contain their selection.
 4113    fn invalidate_autoclose_regions(
 4114        &mut self,
 4115        mut selections: &[Selection<Anchor>],
 4116        buffer: &MultiBufferSnapshot,
 4117    ) {
 4118        self.autoclose_regions.retain(|state| {
 4119            let mut i = 0;
 4120            while let Some(selection) = selections.get(i) {
 4121                if selection.end.cmp(&state.range.start, buffer).is_lt() {
 4122                    selections = &selections[1..];
 4123                    continue;
 4124                }
 4125                if selection.start.cmp(&state.range.end, buffer).is_gt() {
 4126                    break;
 4127                }
 4128                if selection.id == state.selection_id {
 4129                    return true;
 4130                } else {
 4131                    i += 1;
 4132                }
 4133            }
 4134            false
 4135        });
 4136    }
 4137
 4138    fn completion_query(buffer: &MultiBufferSnapshot, position: impl ToOffset) -> Option<String> {
 4139        let offset = position.to_offset(buffer);
 4140        let (word_range, kind) = buffer.surrounding_word(offset, true);
 4141        if offset > word_range.start && kind == Some(CharKind::Word) {
 4142            Some(
 4143                buffer
 4144                    .text_for_range(word_range.start..offset)
 4145                    .collect::<String>(),
 4146            )
 4147        } else {
 4148            None
 4149        }
 4150    }
 4151
 4152    pub fn toggle_inlay_hints(
 4153        &mut self,
 4154        _: &ToggleInlayHints,
 4155        _: &mut Window,
 4156        cx: &mut Context<Self>,
 4157    ) {
 4158        self.refresh_inlay_hints(
 4159            InlayHintRefreshReason::Toggle(!self.inlay_hints_enabled()),
 4160            cx,
 4161        );
 4162    }
 4163
 4164    pub fn inlay_hints_enabled(&self) -> bool {
 4165        self.inlay_hint_cache.enabled
 4166    }
 4167
 4168    fn refresh_inlay_hints(&mut self, reason: InlayHintRefreshReason, cx: &mut Context<Self>) {
 4169        if self.semantics_provider.is_none() || !self.mode.is_full() {
 4170            return;
 4171        }
 4172
 4173        let reason_description = reason.description();
 4174        let ignore_debounce = matches!(
 4175            reason,
 4176            InlayHintRefreshReason::SettingsChange(_)
 4177                | InlayHintRefreshReason::Toggle(_)
 4178                | InlayHintRefreshReason::ExcerptsRemoved(_)
 4179                | InlayHintRefreshReason::ModifiersChanged(_)
 4180        );
 4181        let (invalidate_cache, required_languages) = match reason {
 4182            InlayHintRefreshReason::ModifiersChanged(enabled) => {
 4183                match self.inlay_hint_cache.modifiers_override(enabled) {
 4184                    Some(enabled) => {
 4185                        if enabled {
 4186                            (InvalidationStrategy::RefreshRequested, None)
 4187                        } else {
 4188                            self.splice_inlays(
 4189                                &self
 4190                                    .visible_inlay_hints(cx)
 4191                                    .iter()
 4192                                    .map(|inlay| inlay.id)
 4193                                    .collect::<Vec<InlayId>>(),
 4194                                Vec::new(),
 4195                                cx,
 4196                            );
 4197                            return;
 4198                        }
 4199                    }
 4200                    None => return,
 4201                }
 4202            }
 4203            InlayHintRefreshReason::Toggle(enabled) => {
 4204                if self.inlay_hint_cache.toggle(enabled) {
 4205                    if enabled {
 4206                        (InvalidationStrategy::RefreshRequested, None)
 4207                    } else {
 4208                        self.splice_inlays(
 4209                            &self
 4210                                .visible_inlay_hints(cx)
 4211                                .iter()
 4212                                .map(|inlay| inlay.id)
 4213                                .collect::<Vec<InlayId>>(),
 4214                            Vec::new(),
 4215                            cx,
 4216                        );
 4217                        return;
 4218                    }
 4219                } else {
 4220                    return;
 4221                }
 4222            }
 4223            InlayHintRefreshReason::SettingsChange(new_settings) => {
 4224                match self.inlay_hint_cache.update_settings(
 4225                    &self.buffer,
 4226                    new_settings,
 4227                    self.visible_inlay_hints(cx),
 4228                    cx,
 4229                ) {
 4230                    ControlFlow::Break(Some(InlaySplice {
 4231                        to_remove,
 4232                        to_insert,
 4233                    })) => {
 4234                        self.splice_inlays(&to_remove, to_insert, cx);
 4235                        return;
 4236                    }
 4237                    ControlFlow::Break(None) => return,
 4238                    ControlFlow::Continue(()) => (InvalidationStrategy::RefreshRequested, None),
 4239                }
 4240            }
 4241            InlayHintRefreshReason::ExcerptsRemoved(excerpts_removed) => {
 4242                if let Some(InlaySplice {
 4243                    to_remove,
 4244                    to_insert,
 4245                }) = self.inlay_hint_cache.remove_excerpts(&excerpts_removed)
 4246                {
 4247                    self.splice_inlays(&to_remove, to_insert, cx);
 4248                }
 4249                self.display_map.update(cx, |display_map, _| {
 4250                    display_map.remove_inlays_for_excerpts(&excerpts_removed)
 4251                });
 4252                return;
 4253            }
 4254            InlayHintRefreshReason::NewLinesShown => (InvalidationStrategy::None, None),
 4255            InlayHintRefreshReason::BufferEdited(buffer_languages) => {
 4256                (InvalidationStrategy::BufferEdited, Some(buffer_languages))
 4257            }
 4258            InlayHintRefreshReason::RefreshRequested => {
 4259                (InvalidationStrategy::RefreshRequested, None)
 4260            }
 4261        };
 4262
 4263        if let Some(InlaySplice {
 4264            to_remove,
 4265            to_insert,
 4266        }) = self.inlay_hint_cache.spawn_hint_refresh(
 4267            reason_description,
 4268            self.excerpts_for_inlay_hints_query(required_languages.as_ref(), cx),
 4269            invalidate_cache,
 4270            ignore_debounce,
 4271            cx,
 4272        ) {
 4273            self.splice_inlays(&to_remove, to_insert, cx);
 4274        }
 4275    }
 4276
 4277    fn visible_inlay_hints(&self, cx: &Context<Editor>) -> Vec<Inlay> {
 4278        self.display_map
 4279            .read(cx)
 4280            .current_inlays()
 4281            .filter(move |inlay| matches!(inlay.id, InlayId::Hint(_)))
 4282            .cloned()
 4283            .collect()
 4284    }
 4285
 4286    pub fn excerpts_for_inlay_hints_query(
 4287        &self,
 4288        restrict_to_languages: Option<&HashSet<Arc<Language>>>,
 4289        cx: &mut Context<Editor>,
 4290    ) -> HashMap<ExcerptId, (Entity<Buffer>, clock::Global, Range<usize>)> {
 4291        let Some(project) = self.project.as_ref() else {
 4292            return HashMap::default();
 4293        };
 4294        let project = project.read(cx);
 4295        let multi_buffer = self.buffer().read(cx);
 4296        let multi_buffer_snapshot = multi_buffer.snapshot(cx);
 4297        let multi_buffer_visible_start = self
 4298            .scroll_manager
 4299            .anchor()
 4300            .anchor
 4301            .to_point(&multi_buffer_snapshot);
 4302        let multi_buffer_visible_end = multi_buffer_snapshot.clip_point(
 4303            multi_buffer_visible_start
 4304                + Point::new(self.visible_line_count().unwrap_or(0.).ceil() as u32, 0),
 4305            Bias::Left,
 4306        );
 4307        let multi_buffer_visible_range = multi_buffer_visible_start..multi_buffer_visible_end;
 4308        multi_buffer_snapshot
 4309            .range_to_buffer_ranges(multi_buffer_visible_range)
 4310            .into_iter()
 4311            .filter(|(_, excerpt_visible_range, _)| !excerpt_visible_range.is_empty())
 4312            .filter_map(|(buffer, excerpt_visible_range, excerpt_id)| {
 4313                let buffer_file = project::File::from_dyn(buffer.file())?;
 4314                let buffer_worktree = project.worktree_for_id(buffer_file.worktree_id(cx), cx)?;
 4315                let worktree_entry = buffer_worktree
 4316                    .read(cx)
 4317                    .entry_for_id(buffer_file.project_entry_id(cx)?)?;
 4318                if worktree_entry.is_ignored {
 4319                    return None;
 4320                }
 4321
 4322                let language = buffer.language()?;
 4323                if let Some(restrict_to_languages) = restrict_to_languages {
 4324                    if !restrict_to_languages.contains(language) {
 4325                        return None;
 4326                    }
 4327                }
 4328                Some((
 4329                    excerpt_id,
 4330                    (
 4331                        multi_buffer.buffer(buffer.remote_id()).unwrap(),
 4332                        buffer.version().clone(),
 4333                        excerpt_visible_range,
 4334                    ),
 4335                ))
 4336            })
 4337            .collect()
 4338    }
 4339
 4340    pub fn text_layout_details(&self, window: &mut Window) -> TextLayoutDetails {
 4341        TextLayoutDetails {
 4342            text_system: window.text_system().clone(),
 4343            editor_style: self.style.clone().unwrap(),
 4344            rem_size: window.rem_size(),
 4345            scroll_anchor: self.scroll_manager.anchor(),
 4346            visible_rows: self.visible_line_count(),
 4347            vertical_scroll_margin: self.scroll_manager.vertical_scroll_margin,
 4348        }
 4349    }
 4350
 4351    pub fn splice_inlays(
 4352        &self,
 4353        to_remove: &[InlayId],
 4354        to_insert: Vec<Inlay>,
 4355        cx: &mut Context<Self>,
 4356    ) {
 4357        self.display_map.update(cx, |display_map, cx| {
 4358            display_map.splice_inlays(to_remove, to_insert, cx)
 4359        });
 4360        cx.notify();
 4361    }
 4362
 4363    fn trigger_on_type_formatting(
 4364        &self,
 4365        input: String,
 4366        window: &mut Window,
 4367        cx: &mut Context<Self>,
 4368    ) -> Option<Task<Result<()>>> {
 4369        if input.len() != 1 {
 4370            return None;
 4371        }
 4372
 4373        let project = self.project.as_ref()?;
 4374        let position = self.selections.newest_anchor().head();
 4375        let (buffer, buffer_position) = self
 4376            .buffer
 4377            .read(cx)
 4378            .text_anchor_for_position(position, cx)?;
 4379
 4380        let settings = language_settings::language_settings(
 4381            buffer
 4382                .read(cx)
 4383                .language_at(buffer_position)
 4384                .map(|l| l.name()),
 4385            buffer.read(cx).file(),
 4386            cx,
 4387        );
 4388        if !settings.use_on_type_format {
 4389            return None;
 4390        }
 4391
 4392        // OnTypeFormatting returns a list of edits, no need to pass them between Zed instances,
 4393        // hence we do LSP request & edit on host side only — add formats to host's history.
 4394        let push_to_lsp_host_history = true;
 4395        // If this is not the host, append its history with new edits.
 4396        let push_to_client_history = project.read(cx).is_via_collab();
 4397
 4398        let on_type_formatting = project.update(cx, |project, cx| {
 4399            project.on_type_format(
 4400                buffer.clone(),
 4401                buffer_position,
 4402                input,
 4403                push_to_lsp_host_history,
 4404                cx,
 4405            )
 4406        });
 4407        Some(cx.spawn_in(window, async move |editor, cx| {
 4408            if let Some(transaction) = on_type_formatting.await? {
 4409                if push_to_client_history {
 4410                    buffer
 4411                        .update(cx, |buffer, _| {
 4412                            buffer.push_transaction(transaction, Instant::now());
 4413                            buffer.finalize_last_transaction();
 4414                        })
 4415                        .ok();
 4416                }
 4417                editor.update(cx, |editor, cx| {
 4418                    editor.refresh_document_highlights(cx);
 4419                })?;
 4420            }
 4421            Ok(())
 4422        }))
 4423    }
 4424
 4425    pub fn show_word_completions(
 4426        &mut self,
 4427        _: &ShowWordCompletions,
 4428        window: &mut Window,
 4429        cx: &mut Context<Self>,
 4430    ) {
 4431        self.open_completions_menu(true, None, window, cx);
 4432    }
 4433
 4434    pub fn show_completions(
 4435        &mut self,
 4436        options: &ShowCompletions,
 4437        window: &mut Window,
 4438        cx: &mut Context<Self>,
 4439    ) {
 4440        self.open_completions_menu(false, options.trigger.as_deref(), window, cx);
 4441    }
 4442
 4443    fn open_completions_menu(
 4444        &mut self,
 4445        ignore_completion_provider: bool,
 4446        trigger: Option<&str>,
 4447        window: &mut Window,
 4448        cx: &mut Context<Self>,
 4449    ) {
 4450        if self.pending_rename.is_some() {
 4451            return;
 4452        }
 4453        if !self.snippet_stack.is_empty() && self.context_menu.borrow().as_ref().is_some() {
 4454            return;
 4455        }
 4456
 4457        let position = self.selections.newest_anchor().head();
 4458        if position.diff_base_anchor.is_some() {
 4459            return;
 4460        }
 4461        let (buffer, buffer_position) =
 4462            if let Some(output) = self.buffer.read(cx).text_anchor_for_position(position, cx) {
 4463                output
 4464            } else {
 4465                return;
 4466            };
 4467        let buffer_snapshot = buffer.read(cx).snapshot();
 4468        let show_completion_documentation = buffer_snapshot
 4469            .settings_at(buffer_position, cx)
 4470            .show_completion_documentation;
 4471
 4472        let query = Self::completion_query(&self.buffer.read(cx).read(cx), position);
 4473
 4474        let trigger_kind = match trigger {
 4475            Some(trigger) if buffer.read(cx).completion_triggers().contains(trigger) => {
 4476                CompletionTriggerKind::TRIGGER_CHARACTER
 4477            }
 4478            _ => CompletionTriggerKind::INVOKED,
 4479        };
 4480        let completion_context = CompletionContext {
 4481            trigger_character: trigger.and_then(|trigger| {
 4482                if trigger_kind == CompletionTriggerKind::TRIGGER_CHARACTER {
 4483                    Some(String::from(trigger))
 4484                } else {
 4485                    None
 4486                }
 4487            }),
 4488            trigger_kind,
 4489        };
 4490
 4491        let (old_range, word_kind) = buffer_snapshot.surrounding_word(buffer_position);
 4492        let (old_range, word_to_exclude) = if word_kind == Some(CharKind::Word) {
 4493            let word_to_exclude = buffer_snapshot
 4494                .text_for_range(old_range.clone())
 4495                .collect::<String>();
 4496            (
 4497                buffer_snapshot.anchor_before(old_range.start)
 4498                    ..buffer_snapshot.anchor_after(old_range.end),
 4499                Some(word_to_exclude),
 4500            )
 4501        } else {
 4502            (buffer_position..buffer_position, None)
 4503        };
 4504
 4505        let completion_settings = language_settings(
 4506            buffer_snapshot
 4507                .language_at(buffer_position)
 4508                .map(|language| language.name()),
 4509            buffer_snapshot.file(),
 4510            cx,
 4511        )
 4512        .completions;
 4513
 4514        // The document can be large, so stay in reasonable bounds when searching for words,
 4515        // otherwise completion pop-up might be slow to appear.
 4516        const WORD_LOOKUP_ROWS: u32 = 5_000;
 4517        let buffer_row = text::ToPoint::to_point(&buffer_position, &buffer_snapshot).row;
 4518        let min_word_search = buffer_snapshot.clip_point(
 4519            Point::new(buffer_row.saturating_sub(WORD_LOOKUP_ROWS), 0),
 4520            Bias::Left,
 4521        );
 4522        let max_word_search = buffer_snapshot.clip_point(
 4523            Point::new(buffer_row + WORD_LOOKUP_ROWS, 0).min(buffer_snapshot.max_point()),
 4524            Bias::Right,
 4525        );
 4526        let word_search_range = buffer_snapshot.point_to_offset(min_word_search)
 4527            ..buffer_snapshot.point_to_offset(max_word_search);
 4528
 4529        let provider = self
 4530            .completion_provider
 4531            .as_ref()
 4532            .filter(|_| !ignore_completion_provider);
 4533        let skip_digits = query
 4534            .as_ref()
 4535            .map_or(true, |query| !query.chars().any(|c| c.is_digit(10)));
 4536
 4537        let (mut words, provided_completions) = match provider {
 4538            Some(provider) => {
 4539                let completions = provider.completions(
 4540                    position.excerpt_id,
 4541                    &buffer,
 4542                    buffer_position,
 4543                    completion_context,
 4544                    window,
 4545                    cx,
 4546                );
 4547
 4548                let words = match completion_settings.words {
 4549                    WordsCompletionMode::Disabled => Task::ready(BTreeMap::default()),
 4550                    WordsCompletionMode::Enabled | WordsCompletionMode::Fallback => cx
 4551                        .background_spawn(async move {
 4552                            buffer_snapshot.words_in_range(WordsQuery {
 4553                                fuzzy_contents: None,
 4554                                range: word_search_range,
 4555                                skip_digits,
 4556                            })
 4557                        }),
 4558                };
 4559
 4560                (words, completions)
 4561            }
 4562            None => (
 4563                cx.background_spawn(async move {
 4564                    buffer_snapshot.words_in_range(WordsQuery {
 4565                        fuzzy_contents: None,
 4566                        range: word_search_range,
 4567                        skip_digits,
 4568                    })
 4569                }),
 4570                Task::ready(Ok(None)),
 4571            ),
 4572        };
 4573
 4574        let sort_completions = provider
 4575            .as_ref()
 4576            .map_or(false, |provider| provider.sort_completions());
 4577
 4578        let filter_completions = provider
 4579            .as_ref()
 4580            .map_or(true, |provider| provider.filter_completions());
 4581
 4582        let id = post_inc(&mut self.next_completion_id);
 4583        let task = cx.spawn_in(window, async move |editor, cx| {
 4584            async move {
 4585                editor.update(cx, |this, _| {
 4586                    this.completion_tasks.retain(|(task_id, _)| *task_id >= id);
 4587                })?;
 4588
 4589                let mut completions = Vec::new();
 4590                if let Some(provided_completions) = provided_completions.await.log_err().flatten() {
 4591                    completions.extend(provided_completions);
 4592                    if completion_settings.words == WordsCompletionMode::Fallback {
 4593                        words = Task::ready(BTreeMap::default());
 4594                    }
 4595                }
 4596
 4597                let mut words = words.await;
 4598                if let Some(word_to_exclude) = &word_to_exclude {
 4599                    words.remove(word_to_exclude);
 4600                }
 4601                for lsp_completion in &completions {
 4602                    words.remove(&lsp_completion.new_text);
 4603                }
 4604                completions.extend(words.into_iter().map(|(word, word_range)| Completion {
 4605                    replace_range: old_range.clone(),
 4606                    new_text: word.clone(),
 4607                    label: CodeLabel::plain(word, None),
 4608                    icon_path: None,
 4609                    documentation: None,
 4610                    source: CompletionSource::BufferWord {
 4611                        word_range,
 4612                        resolved: false,
 4613                    },
 4614                    insert_text_mode: Some(InsertTextMode::AS_IS),
 4615                    confirm: None,
 4616                }));
 4617
 4618                let menu = if completions.is_empty() {
 4619                    None
 4620                } else {
 4621                    let mut menu = CompletionsMenu::new(
 4622                        id,
 4623                        sort_completions,
 4624                        show_completion_documentation,
 4625                        ignore_completion_provider,
 4626                        position,
 4627                        buffer.clone(),
 4628                        completions.into(),
 4629                    );
 4630
 4631                    menu.filter(
 4632                        if filter_completions {
 4633                            query.as_deref()
 4634                        } else {
 4635                            None
 4636                        },
 4637                        cx.background_executor().clone(),
 4638                    )
 4639                    .await;
 4640
 4641                    menu.visible().then_some(menu)
 4642                };
 4643
 4644                editor.update_in(cx, |editor, window, cx| {
 4645                    match editor.context_menu.borrow().as_ref() {
 4646                        None => {}
 4647                        Some(CodeContextMenu::Completions(prev_menu)) => {
 4648                            if prev_menu.id > id {
 4649                                return;
 4650                            }
 4651                        }
 4652                        _ => return,
 4653                    }
 4654
 4655                    if editor.focus_handle.is_focused(window) && menu.is_some() {
 4656                        let mut menu = menu.unwrap();
 4657                        menu.resolve_visible_completions(editor.completion_provider.as_deref(), cx);
 4658
 4659                        *editor.context_menu.borrow_mut() =
 4660                            Some(CodeContextMenu::Completions(menu));
 4661
 4662                        if editor.show_edit_predictions_in_menu() {
 4663                            editor.update_visible_inline_completion(window, cx);
 4664                        } else {
 4665                            editor.discard_inline_completion(false, cx);
 4666                        }
 4667
 4668                        cx.notify();
 4669                    } else if editor.completion_tasks.len() <= 1 {
 4670                        // If there are no more completion tasks and the last menu was
 4671                        // empty, we should hide it.
 4672                        let was_hidden = editor.hide_context_menu(window, cx).is_none();
 4673                        // If it was already hidden and we don't show inline
 4674                        // completions in the menu, we should also show the
 4675                        // inline-completion when available.
 4676                        if was_hidden && editor.show_edit_predictions_in_menu() {
 4677                            editor.update_visible_inline_completion(window, cx);
 4678                        }
 4679                    }
 4680                })?;
 4681
 4682                anyhow::Ok(())
 4683            }
 4684            .log_err()
 4685            .await
 4686        });
 4687
 4688        self.completion_tasks.push((id, task));
 4689    }
 4690
 4691    #[cfg(feature = "test-support")]
 4692    pub fn current_completions(&self) -> Option<Vec<project::Completion>> {
 4693        let menu = self.context_menu.borrow();
 4694        if let CodeContextMenu::Completions(menu) = menu.as_ref()? {
 4695            let completions = menu.completions.borrow();
 4696            Some(completions.to_vec())
 4697        } else {
 4698            None
 4699        }
 4700    }
 4701
 4702    pub fn confirm_completion(
 4703        &mut self,
 4704        action: &ConfirmCompletion,
 4705        window: &mut Window,
 4706        cx: &mut Context<Self>,
 4707    ) -> Option<Task<Result<()>>> {
 4708        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
 4709        self.do_completion(action.item_ix, CompletionIntent::Complete, window, cx)
 4710    }
 4711
 4712    pub fn confirm_completion_insert(
 4713        &mut self,
 4714        _: &ConfirmCompletionInsert,
 4715        window: &mut Window,
 4716        cx: &mut Context<Self>,
 4717    ) -> Option<Task<Result<()>>> {
 4718        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
 4719        self.do_completion(None, CompletionIntent::CompleteWithInsert, window, cx)
 4720    }
 4721
 4722    pub fn confirm_completion_replace(
 4723        &mut self,
 4724        _: &ConfirmCompletionReplace,
 4725        window: &mut Window,
 4726        cx: &mut Context<Self>,
 4727    ) -> Option<Task<Result<()>>> {
 4728        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
 4729        self.do_completion(None, CompletionIntent::CompleteWithReplace, window, cx)
 4730    }
 4731
 4732    pub fn compose_completion(
 4733        &mut self,
 4734        action: &ComposeCompletion,
 4735        window: &mut Window,
 4736        cx: &mut Context<Self>,
 4737    ) -> Option<Task<Result<()>>> {
 4738        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
 4739        self.do_completion(action.item_ix, CompletionIntent::Compose, window, cx)
 4740    }
 4741
 4742    fn do_completion(
 4743        &mut self,
 4744        item_ix: Option<usize>,
 4745        intent: CompletionIntent,
 4746        window: &mut Window,
 4747        cx: &mut Context<Editor>,
 4748    ) -> Option<Task<Result<()>>> {
 4749        use language::ToOffset as _;
 4750
 4751        let CodeContextMenu::Completions(completions_menu) = self.hide_context_menu(window, cx)?
 4752        else {
 4753            return None;
 4754        };
 4755
 4756        let candidate_id = {
 4757            let entries = completions_menu.entries.borrow();
 4758            let mat = entries.get(item_ix.unwrap_or(completions_menu.selected_item))?;
 4759            if self.show_edit_predictions_in_menu() {
 4760                self.discard_inline_completion(true, cx);
 4761            }
 4762            mat.candidate_id
 4763        };
 4764
 4765        let buffer_handle = completions_menu.buffer;
 4766        let completion = completions_menu
 4767            .completions
 4768            .borrow()
 4769            .get(candidate_id)?
 4770            .clone();
 4771        cx.stop_propagation();
 4772
 4773        let snippet;
 4774        let new_text;
 4775        if completion.is_snippet() {
 4776            snippet = Some(Snippet::parse(&completion.new_text).log_err()?);
 4777            new_text = snippet.as_ref().unwrap().text.clone();
 4778        } else {
 4779            snippet = None;
 4780            new_text = completion.new_text.clone();
 4781        };
 4782
 4783        let replace_range = choose_completion_range(&completion, intent, &buffer_handle, cx);
 4784        let buffer = buffer_handle.read(cx);
 4785        let snapshot = self.buffer.read(cx).snapshot(cx);
 4786        let replace_range_multibuffer = {
 4787            let excerpt = snapshot
 4788                .excerpt_containing(self.selections.newest_anchor().range())
 4789                .unwrap();
 4790            let multibuffer_anchor = snapshot
 4791                .anchor_in_excerpt(excerpt.id(), buffer.anchor_before(replace_range.start))
 4792                .unwrap()
 4793                ..snapshot
 4794                    .anchor_in_excerpt(excerpt.id(), buffer.anchor_before(replace_range.end))
 4795                    .unwrap();
 4796            multibuffer_anchor.start.to_offset(&snapshot)
 4797                ..multibuffer_anchor.end.to_offset(&snapshot)
 4798        };
 4799        let newest_anchor = self.selections.newest_anchor();
 4800        if newest_anchor.head().buffer_id != Some(buffer.remote_id()) {
 4801            return None;
 4802        }
 4803
 4804        let old_text = buffer
 4805            .text_for_range(replace_range.clone())
 4806            .collect::<String>();
 4807        let lookbehind = newest_anchor
 4808            .start
 4809            .text_anchor
 4810            .to_offset(buffer)
 4811            .saturating_sub(replace_range.start);
 4812        let lookahead = replace_range
 4813            .end
 4814            .saturating_sub(newest_anchor.end.text_anchor.to_offset(buffer));
 4815        let prefix = &old_text[..old_text.len().saturating_sub(lookahead)];
 4816        let suffix = &old_text[lookbehind.min(old_text.len())..];
 4817
 4818        let selections = self.selections.all::<usize>(cx);
 4819        let mut ranges = Vec::new();
 4820        let mut linked_edits = HashMap::<_, Vec<_>>::default();
 4821
 4822        for selection in &selections {
 4823            let range = if selection.id == newest_anchor.id {
 4824                replace_range_multibuffer.clone()
 4825            } else {
 4826                let mut range = selection.range();
 4827
 4828                // if prefix is present, don't duplicate it
 4829                if snapshot.contains_str_at(range.start.saturating_sub(lookbehind), prefix) {
 4830                    range.start = range.start.saturating_sub(lookbehind);
 4831
 4832                    // if suffix is also present, mimic the newest cursor and replace it
 4833                    if selection.id != newest_anchor.id
 4834                        && snapshot.contains_str_at(range.end, suffix)
 4835                    {
 4836                        range.end += lookahead;
 4837                    }
 4838                }
 4839                range
 4840            };
 4841
 4842            ranges.push(range);
 4843
 4844            if !self.linked_edit_ranges.is_empty() {
 4845                let start_anchor = snapshot.anchor_before(selection.head());
 4846                let end_anchor = snapshot.anchor_after(selection.tail());
 4847                if let Some(ranges) = self
 4848                    .linked_editing_ranges_for(start_anchor.text_anchor..end_anchor.text_anchor, cx)
 4849                {
 4850                    for (buffer, edits) in ranges {
 4851                        linked_edits
 4852                            .entry(buffer.clone())
 4853                            .or_default()
 4854                            .extend(edits.into_iter().map(|range| (range, new_text.to_owned())));
 4855                    }
 4856                }
 4857            }
 4858        }
 4859
 4860        cx.emit(EditorEvent::InputHandled {
 4861            utf16_range_to_replace: None,
 4862            text: new_text.clone().into(),
 4863        });
 4864
 4865        self.transact(window, cx, |this, window, cx| {
 4866            if let Some(mut snippet) = snippet {
 4867                snippet.text = new_text.to_string();
 4868                this.insert_snippet(&ranges, snippet, window, cx).log_err();
 4869            } else {
 4870                this.buffer.update(cx, |buffer, cx| {
 4871                    let auto_indent = match completion.insert_text_mode {
 4872                        Some(InsertTextMode::AS_IS) => None,
 4873                        _ => this.autoindent_mode.clone(),
 4874                    };
 4875                    let edits = ranges.into_iter().map(|range| (range, new_text.as_str()));
 4876                    buffer.edit(edits, auto_indent, cx);
 4877                });
 4878            }
 4879            for (buffer, edits) in linked_edits {
 4880                buffer.update(cx, |buffer, cx| {
 4881                    let snapshot = buffer.snapshot();
 4882                    let edits = edits
 4883                        .into_iter()
 4884                        .map(|(range, text)| {
 4885                            use text::ToPoint as TP;
 4886                            let end_point = TP::to_point(&range.end, &snapshot);
 4887                            let start_point = TP::to_point(&range.start, &snapshot);
 4888                            (start_point..end_point, text)
 4889                        })
 4890                        .sorted_by_key(|(range, _)| range.start);
 4891                    buffer.edit(edits, None, cx);
 4892                })
 4893            }
 4894
 4895            this.refresh_inline_completion(true, false, window, cx);
 4896        });
 4897
 4898        let show_new_completions_on_confirm = completion
 4899            .confirm
 4900            .as_ref()
 4901            .map_or(false, |confirm| confirm(intent, window, cx));
 4902        if show_new_completions_on_confirm {
 4903            self.show_completions(&ShowCompletions { trigger: None }, window, cx);
 4904        }
 4905
 4906        let provider = self.completion_provider.as_ref()?;
 4907        drop(completion);
 4908        let apply_edits = provider.apply_additional_edits_for_completion(
 4909            buffer_handle,
 4910            completions_menu.completions.clone(),
 4911            candidate_id,
 4912            true,
 4913            cx,
 4914        );
 4915
 4916        let editor_settings = EditorSettings::get_global(cx);
 4917        if editor_settings.show_signature_help_after_edits || editor_settings.auto_signature_help {
 4918            // After the code completion is finished, users often want to know what signatures are needed.
 4919            // so we should automatically call signature_help
 4920            self.show_signature_help(&ShowSignatureHelp, window, cx);
 4921        }
 4922
 4923        Some(cx.foreground_executor().spawn(async move {
 4924            apply_edits.await?;
 4925            Ok(())
 4926        }))
 4927    }
 4928
 4929    pub fn toggle_code_actions(
 4930        &mut self,
 4931        action: &ToggleCodeActions,
 4932        window: &mut Window,
 4933        cx: &mut Context<Self>,
 4934    ) {
 4935        let mut context_menu = self.context_menu.borrow_mut();
 4936        if let Some(CodeContextMenu::CodeActions(code_actions)) = context_menu.as_ref() {
 4937            if code_actions.deployed_from_indicator == action.deployed_from_indicator {
 4938                // Toggle if we're selecting the same one
 4939                *context_menu = None;
 4940                cx.notify();
 4941                return;
 4942            } else {
 4943                // Otherwise, clear it and start a new one
 4944                *context_menu = None;
 4945                cx.notify();
 4946            }
 4947        }
 4948        drop(context_menu);
 4949        let snapshot = self.snapshot(window, cx);
 4950        let deployed_from_indicator = action.deployed_from_indicator;
 4951        let mut task = self.code_actions_task.take();
 4952        let action = action.clone();
 4953        cx.spawn_in(window, async move |editor, cx| {
 4954            while let Some(prev_task) = task {
 4955                prev_task.await.log_err();
 4956                task = editor.update(cx, |this, _| this.code_actions_task.take())?;
 4957            }
 4958
 4959            let spawned_test_task = editor.update_in(cx, |editor, window, cx| {
 4960                if editor.focus_handle.is_focused(window) {
 4961                    let multibuffer_point = action
 4962                        .deployed_from_indicator
 4963                        .map(|row| DisplayPoint::new(row, 0).to_point(&snapshot))
 4964                        .unwrap_or_else(|| editor.selections.newest::<Point>(cx).head());
 4965                    let (buffer, buffer_row) = snapshot
 4966                        .buffer_snapshot
 4967                        .buffer_line_for_row(MultiBufferRow(multibuffer_point.row))
 4968                        .and_then(|(buffer_snapshot, range)| {
 4969                            editor
 4970                                .buffer
 4971                                .read(cx)
 4972                                .buffer(buffer_snapshot.remote_id())
 4973                                .map(|buffer| (buffer, range.start.row))
 4974                        })?;
 4975                    let (_, code_actions) = editor
 4976                        .available_code_actions
 4977                        .clone()
 4978                        .and_then(|(location, code_actions)| {
 4979                            let snapshot = location.buffer.read(cx).snapshot();
 4980                            let point_range = location.range.to_point(&snapshot);
 4981                            let point_range = point_range.start.row..=point_range.end.row;
 4982                            if point_range.contains(&buffer_row) {
 4983                                Some((location, code_actions))
 4984                            } else {
 4985                                None
 4986                            }
 4987                        })
 4988                        .unzip();
 4989                    let buffer_id = buffer.read(cx).remote_id();
 4990                    let tasks = editor
 4991                        .tasks
 4992                        .get(&(buffer_id, buffer_row))
 4993                        .map(|t| Arc::new(t.to_owned()));
 4994                    if tasks.is_none() && code_actions.is_none() {
 4995                        return None;
 4996                    }
 4997
 4998                    editor.completion_tasks.clear();
 4999                    editor.discard_inline_completion(false, cx);
 5000                    let task_context =
 5001                        tasks
 5002                            .as_ref()
 5003                            .zip(editor.project.clone())
 5004                            .map(|(tasks, project)| {
 5005                                Self::build_tasks_context(&project, &buffer, buffer_row, tasks, cx)
 5006                            });
 5007
 5008                    let debugger_flag = cx.has_flag::<Debugger>();
 5009
 5010                    Some(cx.spawn_in(window, async move |editor, cx| {
 5011                        let task_context = match task_context {
 5012                            Some(task_context) => task_context.await,
 5013                            None => None,
 5014                        };
 5015                        let resolved_tasks =
 5016                            tasks
 5017                                .zip(task_context)
 5018                                .map(|(tasks, task_context)| ResolvedTasks {
 5019                                    templates: tasks.resolve(&task_context).collect(),
 5020                                    position: snapshot.buffer_snapshot.anchor_before(Point::new(
 5021                                        multibuffer_point.row,
 5022                                        tasks.column,
 5023                                    )),
 5024                                });
 5025                        let spawn_straight_away = resolved_tasks.as_ref().map_or(false, |tasks| {
 5026                            tasks
 5027                                .templates
 5028                                .iter()
 5029                                .filter(|task| {
 5030                                    if matches!(task.1.task_type(), task::TaskType::Debug(_)) {
 5031                                        debugger_flag
 5032                                    } else {
 5033                                        true
 5034                                    }
 5035                                })
 5036                                .count()
 5037                                == 1
 5038                        }) && code_actions
 5039                            .as_ref()
 5040                            .map_or(true, |actions| actions.is_empty());
 5041                        if let Ok(task) = editor.update_in(cx, |editor, window, cx| {
 5042                            *editor.context_menu.borrow_mut() =
 5043                                Some(CodeContextMenu::CodeActions(CodeActionsMenu {
 5044                                    buffer,
 5045                                    actions: CodeActionContents::new(
 5046                                        resolved_tasks,
 5047                                        code_actions,
 5048                                        cx,
 5049                                    ),
 5050                                    selected_item: Default::default(),
 5051                                    scroll_handle: UniformListScrollHandle::default(),
 5052                                    deployed_from_indicator,
 5053                                }));
 5054                            if spawn_straight_away {
 5055                                if let Some(task) = editor.confirm_code_action(
 5056                                    &ConfirmCodeAction { item_ix: Some(0) },
 5057                                    window,
 5058                                    cx,
 5059                                ) {
 5060                                    cx.notify();
 5061                                    return task;
 5062                                }
 5063                            }
 5064                            cx.notify();
 5065                            Task::ready(Ok(()))
 5066                        }) {
 5067                            task.await
 5068                        } else {
 5069                            Ok(())
 5070                        }
 5071                    }))
 5072                } else {
 5073                    Some(Task::ready(Ok(())))
 5074                }
 5075            })?;
 5076            if let Some(task) = spawned_test_task {
 5077                task.await?;
 5078            }
 5079
 5080            Ok::<_, anyhow::Error>(())
 5081        })
 5082        .detach_and_log_err(cx);
 5083    }
 5084
 5085    pub fn confirm_code_action(
 5086        &mut self,
 5087        action: &ConfirmCodeAction,
 5088        window: &mut Window,
 5089        cx: &mut Context<Self>,
 5090    ) -> Option<Task<Result<()>>> {
 5091        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
 5092
 5093        let actions_menu =
 5094            if let CodeContextMenu::CodeActions(menu) = self.hide_context_menu(window, cx)? {
 5095                menu
 5096            } else {
 5097                return None;
 5098            };
 5099
 5100        let action_ix = action.item_ix.unwrap_or(actions_menu.selected_item);
 5101        let action = actions_menu.actions.get(action_ix)?;
 5102        let title = action.label();
 5103        let buffer = actions_menu.buffer;
 5104        let workspace = self.workspace()?;
 5105
 5106        match action {
 5107            CodeActionsItem::Task(task_source_kind, resolved_task) => {
 5108                match resolved_task.task_type() {
 5109                    task::TaskType::Script => workspace.update(cx, |workspace, cx| {
 5110                        workspace::tasks::schedule_resolved_task(
 5111                            workspace,
 5112                            task_source_kind,
 5113                            resolved_task,
 5114                            false,
 5115                            cx,
 5116                        );
 5117
 5118                        Some(Task::ready(Ok(())))
 5119                    }),
 5120                    task::TaskType::Debug(debug_args) => {
 5121                        if debug_args.locator.is_some() {
 5122                            workspace.update(cx, |workspace, cx| {
 5123                                workspace::tasks::schedule_resolved_task(
 5124                                    workspace,
 5125                                    task_source_kind,
 5126                                    resolved_task,
 5127                                    false,
 5128                                    cx,
 5129                                );
 5130                            });
 5131
 5132                            return Some(Task::ready(Ok(())));
 5133                        }
 5134
 5135                        if let Some(project) = self.project.as_ref() {
 5136                            project
 5137                                .update(cx, |project, cx| {
 5138                                    project.start_debug_session(
 5139                                        resolved_task.resolved_debug_adapter_config().unwrap(),
 5140                                        cx,
 5141                                    )
 5142                                })
 5143                                .detach_and_log_err(cx);
 5144                            Some(Task::ready(Ok(())))
 5145                        } else {
 5146                            Some(Task::ready(Ok(())))
 5147                        }
 5148                    }
 5149                }
 5150            }
 5151            CodeActionsItem::CodeAction {
 5152                excerpt_id,
 5153                action,
 5154                provider,
 5155            } => {
 5156                let apply_code_action =
 5157                    provider.apply_code_action(buffer, action, excerpt_id, true, window, cx);
 5158                let workspace = workspace.downgrade();
 5159                Some(cx.spawn_in(window, async move |editor, cx| {
 5160                    let project_transaction = apply_code_action.await?;
 5161                    Self::open_project_transaction(
 5162                        &editor,
 5163                        workspace,
 5164                        project_transaction,
 5165                        title,
 5166                        cx,
 5167                    )
 5168                    .await
 5169                }))
 5170            }
 5171        }
 5172    }
 5173
 5174    pub async fn open_project_transaction(
 5175        this: &WeakEntity<Editor>,
 5176        workspace: WeakEntity<Workspace>,
 5177        transaction: ProjectTransaction,
 5178        title: String,
 5179        cx: &mut AsyncWindowContext,
 5180    ) -> Result<()> {
 5181        let mut entries = transaction.0.into_iter().collect::<Vec<_>>();
 5182        cx.update(|_, cx| {
 5183            entries.sort_unstable_by_key(|(buffer, _)| {
 5184                buffer.read(cx).file().map(|f| f.path().clone())
 5185            });
 5186        })?;
 5187
 5188        // If the project transaction's edits are all contained within this editor, then
 5189        // avoid opening a new editor to display them.
 5190
 5191        if let Some((buffer, transaction)) = entries.first() {
 5192            if entries.len() == 1 {
 5193                let excerpt = this.update(cx, |editor, cx| {
 5194                    editor
 5195                        .buffer()
 5196                        .read(cx)
 5197                        .excerpt_containing(editor.selections.newest_anchor().head(), cx)
 5198                })?;
 5199                if let Some((_, excerpted_buffer, excerpt_range)) = excerpt {
 5200                    if excerpted_buffer == *buffer {
 5201                        let all_edits_within_excerpt = buffer.read_with(cx, |buffer, _| {
 5202                            let excerpt_range = excerpt_range.to_offset(buffer);
 5203                            buffer
 5204                                .edited_ranges_for_transaction::<usize>(transaction)
 5205                                .all(|range| {
 5206                                    excerpt_range.start <= range.start
 5207                                        && excerpt_range.end >= range.end
 5208                                })
 5209                        })?;
 5210
 5211                        if all_edits_within_excerpt {
 5212                            return Ok(());
 5213                        }
 5214                    }
 5215                }
 5216            }
 5217        } else {
 5218            return Ok(());
 5219        }
 5220
 5221        let mut ranges_to_highlight = Vec::new();
 5222        let excerpt_buffer = cx.new(|cx| {
 5223            let mut multibuffer = MultiBuffer::new(Capability::ReadWrite).with_title(title);
 5224            for (buffer_handle, transaction) in &entries {
 5225                let edited_ranges = buffer_handle
 5226                    .read(cx)
 5227                    .edited_ranges_for_transaction::<Point>(transaction)
 5228                    .collect::<Vec<_>>();
 5229                let (ranges, _) = multibuffer.set_excerpts_for_path(
 5230                    PathKey::for_buffer(buffer_handle, cx),
 5231                    buffer_handle.clone(),
 5232                    edited_ranges,
 5233                    DEFAULT_MULTIBUFFER_CONTEXT,
 5234                    cx,
 5235                );
 5236
 5237                ranges_to_highlight.extend(ranges);
 5238            }
 5239            multibuffer.push_transaction(entries.iter().map(|(b, t)| (b, t)), cx);
 5240            multibuffer
 5241        })?;
 5242
 5243        workspace.update_in(cx, |workspace, window, cx| {
 5244            let project = workspace.project().clone();
 5245            let editor =
 5246                cx.new(|cx| Editor::for_multibuffer(excerpt_buffer, Some(project), window, cx));
 5247            workspace.add_item_to_active_pane(Box::new(editor.clone()), None, true, window, cx);
 5248            editor.update(cx, |editor, cx| {
 5249                editor.highlight_background::<Self>(
 5250                    &ranges_to_highlight,
 5251                    |theme| theme.editor_highlighted_line_background,
 5252                    cx,
 5253                );
 5254            });
 5255        })?;
 5256
 5257        Ok(())
 5258    }
 5259
 5260    pub fn clear_code_action_providers(&mut self) {
 5261        self.code_action_providers.clear();
 5262        self.available_code_actions.take();
 5263    }
 5264
 5265    pub fn add_code_action_provider(
 5266        &mut self,
 5267        provider: Rc<dyn CodeActionProvider>,
 5268        window: &mut Window,
 5269        cx: &mut Context<Self>,
 5270    ) {
 5271        if self
 5272            .code_action_providers
 5273            .iter()
 5274            .any(|existing_provider| existing_provider.id() == provider.id())
 5275        {
 5276            return;
 5277        }
 5278
 5279        self.code_action_providers.push(provider);
 5280        self.refresh_code_actions(window, cx);
 5281    }
 5282
 5283    pub fn remove_code_action_provider(
 5284        &mut self,
 5285        id: Arc<str>,
 5286        window: &mut Window,
 5287        cx: &mut Context<Self>,
 5288    ) {
 5289        self.code_action_providers
 5290            .retain(|provider| provider.id() != id);
 5291        self.refresh_code_actions(window, cx);
 5292    }
 5293
 5294    fn refresh_code_actions(&mut self, window: &mut Window, cx: &mut Context<Self>) -> Option<()> {
 5295        let newest_selection = self.selections.newest_anchor().clone();
 5296        let newest_selection_adjusted = self.selections.newest_adjusted(cx).clone();
 5297        let buffer = self.buffer.read(cx);
 5298        if newest_selection.head().diff_base_anchor.is_some() {
 5299            return None;
 5300        }
 5301        let (start_buffer, start) =
 5302            buffer.text_anchor_for_position(newest_selection_adjusted.start, cx)?;
 5303        let (end_buffer, end) =
 5304            buffer.text_anchor_for_position(newest_selection_adjusted.end, cx)?;
 5305        if start_buffer != end_buffer {
 5306            return None;
 5307        }
 5308
 5309        self.code_actions_task = Some(cx.spawn_in(window, async move |this, cx| {
 5310            cx.background_executor()
 5311                .timer(CODE_ACTIONS_DEBOUNCE_TIMEOUT)
 5312                .await;
 5313
 5314            let (providers, tasks) = this.update_in(cx, |this, window, cx| {
 5315                let providers = this.code_action_providers.clone();
 5316                let tasks = this
 5317                    .code_action_providers
 5318                    .iter()
 5319                    .map(|provider| provider.code_actions(&start_buffer, start..end, window, cx))
 5320                    .collect::<Vec<_>>();
 5321                (providers, tasks)
 5322            })?;
 5323
 5324            let mut actions = Vec::new();
 5325            for (provider, provider_actions) in
 5326                providers.into_iter().zip(future::join_all(tasks).await)
 5327            {
 5328                if let Some(provider_actions) = provider_actions.log_err() {
 5329                    actions.extend(provider_actions.into_iter().map(|action| {
 5330                        AvailableCodeAction {
 5331                            excerpt_id: newest_selection.start.excerpt_id,
 5332                            action,
 5333                            provider: provider.clone(),
 5334                        }
 5335                    }));
 5336                }
 5337            }
 5338
 5339            this.update(cx, |this, cx| {
 5340                this.available_code_actions = if actions.is_empty() {
 5341                    None
 5342                } else {
 5343                    Some((
 5344                        Location {
 5345                            buffer: start_buffer,
 5346                            range: start..end,
 5347                        },
 5348                        actions.into(),
 5349                    ))
 5350                };
 5351                cx.notify();
 5352            })
 5353        }));
 5354        None
 5355    }
 5356
 5357    fn start_inline_blame_timer(&mut self, window: &mut Window, cx: &mut Context<Self>) {
 5358        if let Some(delay) = ProjectSettings::get_global(cx).git.inline_blame_delay() {
 5359            self.show_git_blame_inline = false;
 5360
 5361            self.show_git_blame_inline_delay_task =
 5362                Some(cx.spawn_in(window, async move |this, cx| {
 5363                    cx.background_executor().timer(delay).await;
 5364
 5365                    this.update(cx, |this, cx| {
 5366                        this.show_git_blame_inline = true;
 5367                        cx.notify();
 5368                    })
 5369                    .log_err();
 5370                }));
 5371        }
 5372    }
 5373
 5374    fn refresh_document_highlights(&mut self, cx: &mut Context<Self>) -> Option<()> {
 5375        if self.pending_rename.is_some() {
 5376            return None;
 5377        }
 5378
 5379        let provider = self.semantics_provider.clone()?;
 5380        let buffer = self.buffer.read(cx);
 5381        let newest_selection = self.selections.newest_anchor().clone();
 5382        let cursor_position = newest_selection.head();
 5383        let (cursor_buffer, cursor_buffer_position) =
 5384            buffer.text_anchor_for_position(cursor_position, cx)?;
 5385        let (tail_buffer, _) = buffer.text_anchor_for_position(newest_selection.tail(), cx)?;
 5386        if cursor_buffer != tail_buffer {
 5387            return None;
 5388        }
 5389        let debounce = EditorSettings::get_global(cx).lsp_highlight_debounce;
 5390        self.document_highlights_task = Some(cx.spawn(async move |this, cx| {
 5391            cx.background_executor()
 5392                .timer(Duration::from_millis(debounce))
 5393                .await;
 5394
 5395            let highlights = if let Some(highlights) = cx
 5396                .update(|cx| {
 5397                    provider.document_highlights(&cursor_buffer, cursor_buffer_position, cx)
 5398                })
 5399                .ok()
 5400                .flatten()
 5401            {
 5402                highlights.await.log_err()
 5403            } else {
 5404                None
 5405            };
 5406
 5407            if let Some(highlights) = highlights {
 5408                this.update(cx, |this, cx| {
 5409                    if this.pending_rename.is_some() {
 5410                        return;
 5411                    }
 5412
 5413                    let buffer_id = cursor_position.buffer_id;
 5414                    let buffer = this.buffer.read(cx);
 5415                    if !buffer
 5416                        .text_anchor_for_position(cursor_position, cx)
 5417                        .map_or(false, |(buffer, _)| buffer == cursor_buffer)
 5418                    {
 5419                        return;
 5420                    }
 5421
 5422                    let cursor_buffer_snapshot = cursor_buffer.read(cx);
 5423                    let mut write_ranges = Vec::new();
 5424                    let mut read_ranges = Vec::new();
 5425                    for highlight in highlights {
 5426                        for (excerpt_id, excerpt_range) in
 5427                            buffer.excerpts_for_buffer(cursor_buffer.read(cx).remote_id(), cx)
 5428                        {
 5429                            let start = highlight
 5430                                .range
 5431                                .start
 5432                                .max(&excerpt_range.context.start, cursor_buffer_snapshot);
 5433                            let end = highlight
 5434                                .range
 5435                                .end
 5436                                .min(&excerpt_range.context.end, cursor_buffer_snapshot);
 5437                            if start.cmp(&end, cursor_buffer_snapshot).is_ge() {
 5438                                continue;
 5439                            }
 5440
 5441                            let range = Anchor {
 5442                                buffer_id,
 5443                                excerpt_id,
 5444                                text_anchor: start,
 5445                                diff_base_anchor: None,
 5446                            }..Anchor {
 5447                                buffer_id,
 5448                                excerpt_id,
 5449                                text_anchor: end,
 5450                                diff_base_anchor: None,
 5451                            };
 5452                            if highlight.kind == lsp::DocumentHighlightKind::WRITE {
 5453                                write_ranges.push(range);
 5454                            } else {
 5455                                read_ranges.push(range);
 5456                            }
 5457                        }
 5458                    }
 5459
 5460                    this.highlight_background::<DocumentHighlightRead>(
 5461                        &read_ranges,
 5462                        |theme| theme.editor_document_highlight_read_background,
 5463                        cx,
 5464                    );
 5465                    this.highlight_background::<DocumentHighlightWrite>(
 5466                        &write_ranges,
 5467                        |theme| theme.editor_document_highlight_write_background,
 5468                        cx,
 5469                    );
 5470                    cx.notify();
 5471                })
 5472                .log_err();
 5473            }
 5474        }));
 5475        None
 5476    }
 5477
 5478    pub fn refresh_selected_text_highlights(
 5479        &mut self,
 5480        window: &mut Window,
 5481        cx: &mut Context<Editor>,
 5482    ) {
 5483        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 5484            return;
 5485        }
 5486        self.selection_highlight_task.take();
 5487        if !EditorSettings::get_global(cx).selection_highlight {
 5488            self.clear_background_highlights::<SelectedTextHighlight>(cx);
 5489            return;
 5490        }
 5491        if self.selections.count() != 1 || self.selections.line_mode {
 5492            self.clear_background_highlights::<SelectedTextHighlight>(cx);
 5493            return;
 5494        }
 5495        let selection = self.selections.newest::<Point>(cx);
 5496        if selection.is_empty() || selection.start.row != selection.end.row {
 5497            self.clear_background_highlights::<SelectedTextHighlight>(cx);
 5498            return;
 5499        }
 5500        let debounce = EditorSettings::get_global(cx).selection_highlight_debounce;
 5501        self.selection_highlight_task = Some(cx.spawn_in(window, async move |editor, cx| {
 5502            cx.background_executor()
 5503                .timer(Duration::from_millis(debounce))
 5504                .await;
 5505            let Some(Some(matches_task)) = editor
 5506                .update_in(cx, |editor, _, cx| {
 5507                    if editor.selections.count() != 1 || editor.selections.line_mode {
 5508                        editor.clear_background_highlights::<SelectedTextHighlight>(cx);
 5509                        return None;
 5510                    }
 5511                    let selection = editor.selections.newest::<Point>(cx);
 5512                    if selection.is_empty() || selection.start.row != selection.end.row {
 5513                        editor.clear_background_highlights::<SelectedTextHighlight>(cx);
 5514                        return None;
 5515                    }
 5516                    let buffer = editor.buffer().read(cx).snapshot(cx);
 5517                    let query = buffer.text_for_range(selection.range()).collect::<String>();
 5518                    if query.trim().is_empty() {
 5519                        editor.clear_background_highlights::<SelectedTextHighlight>(cx);
 5520                        return None;
 5521                    }
 5522                    Some(cx.background_spawn(async move {
 5523                        let mut ranges = Vec::new();
 5524                        let selection_anchors = selection.range().to_anchors(&buffer);
 5525                        for range in [buffer.anchor_before(0)..buffer.anchor_after(buffer.len())] {
 5526                            for (search_buffer, search_range, excerpt_id) in
 5527                                buffer.range_to_buffer_ranges(range)
 5528                            {
 5529                                ranges.extend(
 5530                                    project::search::SearchQuery::text(
 5531                                        query.clone(),
 5532                                        false,
 5533                                        false,
 5534                                        false,
 5535                                        Default::default(),
 5536                                        Default::default(),
 5537                                        None,
 5538                                    )
 5539                                    .unwrap()
 5540                                    .search(search_buffer, Some(search_range.clone()))
 5541                                    .await
 5542                                    .into_iter()
 5543                                    .filter_map(
 5544                                        |match_range| {
 5545                                            let start = search_buffer.anchor_after(
 5546                                                search_range.start + match_range.start,
 5547                                            );
 5548                                            let end = search_buffer.anchor_before(
 5549                                                search_range.start + match_range.end,
 5550                                            );
 5551                                            let range = Anchor::range_in_buffer(
 5552                                                excerpt_id,
 5553                                                search_buffer.remote_id(),
 5554                                                start..end,
 5555                                            );
 5556                                            (range != selection_anchors).then_some(range)
 5557                                        },
 5558                                    ),
 5559                                );
 5560                            }
 5561                        }
 5562                        ranges
 5563                    }))
 5564                })
 5565                .log_err()
 5566            else {
 5567                return;
 5568            };
 5569            let matches = matches_task.await;
 5570            editor
 5571                .update_in(cx, |editor, _, cx| {
 5572                    editor.clear_background_highlights::<SelectedTextHighlight>(cx);
 5573                    if !matches.is_empty() {
 5574                        editor.highlight_background::<SelectedTextHighlight>(
 5575                            &matches,
 5576                            |theme| theme.editor_document_highlight_bracket_background,
 5577                            cx,
 5578                        )
 5579                    }
 5580                })
 5581                .log_err();
 5582        }));
 5583    }
 5584
 5585    pub fn refresh_inline_completion(
 5586        &mut self,
 5587        debounce: bool,
 5588        user_requested: bool,
 5589        window: &mut Window,
 5590        cx: &mut Context<Self>,
 5591    ) -> Option<()> {
 5592        let provider = self.edit_prediction_provider()?;
 5593        let cursor = self.selections.newest_anchor().head();
 5594        let (buffer, cursor_buffer_position) =
 5595            self.buffer.read(cx).text_anchor_for_position(cursor, cx)?;
 5596
 5597        if !self.edit_predictions_enabled_in_buffer(&buffer, cursor_buffer_position, cx) {
 5598            self.discard_inline_completion(false, cx);
 5599            return None;
 5600        }
 5601
 5602        if !user_requested
 5603            && (!self.should_show_edit_predictions()
 5604                || !self.is_focused(window)
 5605                || buffer.read(cx).is_empty())
 5606        {
 5607            self.discard_inline_completion(false, cx);
 5608            return None;
 5609        }
 5610
 5611        self.update_visible_inline_completion(window, cx);
 5612        provider.refresh(
 5613            self.project.clone(),
 5614            buffer,
 5615            cursor_buffer_position,
 5616            debounce,
 5617            cx,
 5618        );
 5619        Some(())
 5620    }
 5621
 5622    fn show_edit_predictions_in_menu(&self) -> bool {
 5623        match self.edit_prediction_settings {
 5624            EditPredictionSettings::Disabled => false,
 5625            EditPredictionSettings::Enabled { show_in_menu, .. } => show_in_menu,
 5626        }
 5627    }
 5628
 5629    pub fn edit_predictions_enabled(&self) -> bool {
 5630        match self.edit_prediction_settings {
 5631            EditPredictionSettings::Disabled => false,
 5632            EditPredictionSettings::Enabled { .. } => true,
 5633        }
 5634    }
 5635
 5636    fn edit_prediction_requires_modifier(&self) -> bool {
 5637        match self.edit_prediction_settings {
 5638            EditPredictionSettings::Disabled => false,
 5639            EditPredictionSettings::Enabled {
 5640                preview_requires_modifier,
 5641                ..
 5642            } => preview_requires_modifier,
 5643        }
 5644    }
 5645
 5646    pub fn update_edit_prediction_settings(&mut self, cx: &mut Context<Self>) {
 5647        if self.edit_prediction_provider.is_none() {
 5648            self.edit_prediction_settings = EditPredictionSettings::Disabled;
 5649        } else {
 5650            let selection = self.selections.newest_anchor();
 5651            let cursor = selection.head();
 5652
 5653            if let Some((buffer, cursor_buffer_position)) =
 5654                self.buffer.read(cx).text_anchor_for_position(cursor, cx)
 5655            {
 5656                self.edit_prediction_settings =
 5657                    self.edit_prediction_settings_at_position(&buffer, cursor_buffer_position, cx);
 5658            }
 5659        }
 5660    }
 5661
 5662    fn edit_prediction_settings_at_position(
 5663        &self,
 5664        buffer: &Entity<Buffer>,
 5665        buffer_position: language::Anchor,
 5666        cx: &App,
 5667    ) -> EditPredictionSettings {
 5668        if !self.mode.is_full()
 5669            || !self.show_inline_completions_override.unwrap_or(true)
 5670            || self.inline_completions_disabled_in_scope(buffer, buffer_position, cx)
 5671        {
 5672            return EditPredictionSettings::Disabled;
 5673        }
 5674
 5675        let buffer = buffer.read(cx);
 5676
 5677        let file = buffer.file();
 5678
 5679        if !language_settings(buffer.language().map(|l| l.name()), file, cx).show_edit_predictions {
 5680            return EditPredictionSettings::Disabled;
 5681        };
 5682
 5683        let by_provider = matches!(
 5684            self.menu_inline_completions_policy,
 5685            MenuInlineCompletionsPolicy::ByProvider
 5686        );
 5687
 5688        let show_in_menu = by_provider
 5689            && self
 5690                .edit_prediction_provider
 5691                .as_ref()
 5692                .map_or(false, |provider| {
 5693                    provider.provider.show_completions_in_menu()
 5694                });
 5695
 5696        let preview_requires_modifier =
 5697            all_language_settings(file, cx).edit_predictions_mode() == EditPredictionsMode::Subtle;
 5698
 5699        EditPredictionSettings::Enabled {
 5700            show_in_menu,
 5701            preview_requires_modifier,
 5702        }
 5703    }
 5704
 5705    fn should_show_edit_predictions(&self) -> bool {
 5706        self.snippet_stack.is_empty() && self.edit_predictions_enabled()
 5707    }
 5708
 5709    pub fn edit_prediction_preview_is_active(&self) -> bool {
 5710        matches!(
 5711            self.edit_prediction_preview,
 5712            EditPredictionPreview::Active { .. }
 5713        )
 5714    }
 5715
 5716    pub fn edit_predictions_enabled_at_cursor(&self, cx: &App) -> bool {
 5717        let cursor = self.selections.newest_anchor().head();
 5718        if let Some((buffer, cursor_position)) =
 5719            self.buffer.read(cx).text_anchor_for_position(cursor, cx)
 5720        {
 5721            self.edit_predictions_enabled_in_buffer(&buffer, cursor_position, cx)
 5722        } else {
 5723            false
 5724        }
 5725    }
 5726
 5727    fn edit_predictions_enabled_in_buffer(
 5728        &self,
 5729        buffer: &Entity<Buffer>,
 5730        buffer_position: language::Anchor,
 5731        cx: &App,
 5732    ) -> bool {
 5733        maybe!({
 5734            if self.read_only(cx) {
 5735                return Some(false);
 5736            }
 5737            let provider = self.edit_prediction_provider()?;
 5738            if !provider.is_enabled(&buffer, buffer_position, cx) {
 5739                return Some(false);
 5740            }
 5741            let buffer = buffer.read(cx);
 5742            let Some(file) = buffer.file() else {
 5743                return Some(true);
 5744            };
 5745            let settings = all_language_settings(Some(file), cx);
 5746            Some(settings.edit_predictions_enabled_for_file(file, cx))
 5747        })
 5748        .unwrap_or(false)
 5749    }
 5750
 5751    fn cycle_inline_completion(
 5752        &mut self,
 5753        direction: Direction,
 5754        window: &mut Window,
 5755        cx: &mut Context<Self>,
 5756    ) -> Option<()> {
 5757        let provider = self.edit_prediction_provider()?;
 5758        let cursor = self.selections.newest_anchor().head();
 5759        let (buffer, cursor_buffer_position) =
 5760            self.buffer.read(cx).text_anchor_for_position(cursor, cx)?;
 5761        if self.inline_completions_hidden_for_vim_mode || !self.should_show_edit_predictions() {
 5762            return None;
 5763        }
 5764
 5765        provider.cycle(buffer, cursor_buffer_position, direction, cx);
 5766        self.update_visible_inline_completion(window, cx);
 5767
 5768        Some(())
 5769    }
 5770
 5771    pub fn show_inline_completion(
 5772        &mut self,
 5773        _: &ShowEditPrediction,
 5774        window: &mut Window,
 5775        cx: &mut Context<Self>,
 5776    ) {
 5777        if !self.has_active_inline_completion() {
 5778            self.refresh_inline_completion(false, true, window, cx);
 5779            return;
 5780        }
 5781
 5782        self.update_visible_inline_completion(window, cx);
 5783    }
 5784
 5785    pub fn display_cursor_names(
 5786        &mut self,
 5787        _: &DisplayCursorNames,
 5788        window: &mut Window,
 5789        cx: &mut Context<Self>,
 5790    ) {
 5791        self.show_cursor_names(window, cx);
 5792    }
 5793
 5794    fn show_cursor_names(&mut self, window: &mut Window, cx: &mut Context<Self>) {
 5795        self.show_cursor_names = true;
 5796        cx.notify();
 5797        cx.spawn_in(window, async move |this, cx| {
 5798            cx.background_executor().timer(CURSORS_VISIBLE_FOR).await;
 5799            this.update(cx, |this, cx| {
 5800                this.show_cursor_names = false;
 5801                cx.notify()
 5802            })
 5803            .ok()
 5804        })
 5805        .detach();
 5806    }
 5807
 5808    pub fn next_edit_prediction(
 5809        &mut self,
 5810        _: &NextEditPrediction,
 5811        window: &mut Window,
 5812        cx: &mut Context<Self>,
 5813    ) {
 5814        if self.has_active_inline_completion() {
 5815            self.cycle_inline_completion(Direction::Next, window, cx);
 5816        } else {
 5817            let is_copilot_disabled = self
 5818                .refresh_inline_completion(false, true, window, cx)
 5819                .is_none();
 5820            if is_copilot_disabled {
 5821                cx.propagate();
 5822            }
 5823        }
 5824    }
 5825
 5826    pub fn previous_edit_prediction(
 5827        &mut self,
 5828        _: &PreviousEditPrediction,
 5829        window: &mut Window,
 5830        cx: &mut Context<Self>,
 5831    ) {
 5832        if self.has_active_inline_completion() {
 5833            self.cycle_inline_completion(Direction::Prev, window, cx);
 5834        } else {
 5835            let is_copilot_disabled = self
 5836                .refresh_inline_completion(false, true, window, cx)
 5837                .is_none();
 5838            if is_copilot_disabled {
 5839                cx.propagate();
 5840            }
 5841        }
 5842    }
 5843
 5844    pub fn accept_edit_prediction(
 5845        &mut self,
 5846        _: &AcceptEditPrediction,
 5847        window: &mut Window,
 5848        cx: &mut Context<Self>,
 5849    ) {
 5850        if self.show_edit_predictions_in_menu() {
 5851            self.hide_context_menu(window, cx);
 5852        }
 5853
 5854        let Some(active_inline_completion) = self.active_inline_completion.as_ref() else {
 5855            return;
 5856        };
 5857
 5858        self.report_inline_completion_event(
 5859            active_inline_completion.completion_id.clone(),
 5860            true,
 5861            cx,
 5862        );
 5863
 5864        match &active_inline_completion.completion {
 5865            InlineCompletion::Move { target, .. } => {
 5866                let target = *target;
 5867
 5868                if let Some(position_map) = &self.last_position_map {
 5869                    if position_map
 5870                        .visible_row_range
 5871                        .contains(&target.to_display_point(&position_map.snapshot).row())
 5872                        || !self.edit_prediction_requires_modifier()
 5873                    {
 5874                        self.unfold_ranges(&[target..target], true, false, cx);
 5875                        // Note that this is also done in vim's handler of the Tab action.
 5876                        self.change_selections(
 5877                            Some(Autoscroll::newest()),
 5878                            window,
 5879                            cx,
 5880                            |selections| {
 5881                                selections.select_anchor_ranges([target..target]);
 5882                            },
 5883                        );
 5884                        self.clear_row_highlights::<EditPredictionPreview>();
 5885
 5886                        self.edit_prediction_preview
 5887                            .set_previous_scroll_position(None);
 5888                    } else {
 5889                        self.edit_prediction_preview
 5890                            .set_previous_scroll_position(Some(
 5891                                position_map.snapshot.scroll_anchor,
 5892                            ));
 5893
 5894                        self.highlight_rows::<EditPredictionPreview>(
 5895                            target..target,
 5896                            cx.theme().colors().editor_highlighted_line_background,
 5897                            true,
 5898                            cx,
 5899                        );
 5900                        self.request_autoscroll(Autoscroll::fit(), cx);
 5901                    }
 5902                }
 5903            }
 5904            InlineCompletion::Edit { edits, .. } => {
 5905                if let Some(provider) = self.edit_prediction_provider() {
 5906                    provider.accept(cx);
 5907                }
 5908
 5909                let snapshot = self.buffer.read(cx).snapshot(cx);
 5910                let last_edit_end = edits.last().unwrap().0.end.bias_right(&snapshot);
 5911
 5912                self.buffer.update(cx, |buffer, cx| {
 5913                    buffer.edit(edits.iter().cloned(), None, cx)
 5914                });
 5915
 5916                self.change_selections(None, window, cx, |s| {
 5917                    s.select_anchor_ranges([last_edit_end..last_edit_end])
 5918                });
 5919
 5920                self.update_visible_inline_completion(window, cx);
 5921                if self.active_inline_completion.is_none() {
 5922                    self.refresh_inline_completion(true, true, window, cx);
 5923                }
 5924
 5925                cx.notify();
 5926            }
 5927        }
 5928
 5929        self.edit_prediction_requires_modifier_in_indent_conflict = false;
 5930    }
 5931
 5932    pub fn accept_partial_inline_completion(
 5933        &mut self,
 5934        _: &AcceptPartialEditPrediction,
 5935        window: &mut Window,
 5936        cx: &mut Context<Self>,
 5937    ) {
 5938        let Some(active_inline_completion) = self.active_inline_completion.as_ref() else {
 5939            return;
 5940        };
 5941        if self.selections.count() != 1 {
 5942            return;
 5943        }
 5944
 5945        self.report_inline_completion_event(
 5946            active_inline_completion.completion_id.clone(),
 5947            true,
 5948            cx,
 5949        );
 5950
 5951        match &active_inline_completion.completion {
 5952            InlineCompletion::Move { target, .. } => {
 5953                let target = *target;
 5954                self.change_selections(Some(Autoscroll::newest()), window, cx, |selections| {
 5955                    selections.select_anchor_ranges([target..target]);
 5956                });
 5957            }
 5958            InlineCompletion::Edit { edits, .. } => {
 5959                // Find an insertion that starts at the cursor position.
 5960                let snapshot = self.buffer.read(cx).snapshot(cx);
 5961                let cursor_offset = self.selections.newest::<usize>(cx).head();
 5962                let insertion = edits.iter().find_map(|(range, text)| {
 5963                    let range = range.to_offset(&snapshot);
 5964                    if range.is_empty() && range.start == cursor_offset {
 5965                        Some(text)
 5966                    } else {
 5967                        None
 5968                    }
 5969                });
 5970
 5971                if let Some(text) = insertion {
 5972                    let mut partial_completion = text
 5973                        .chars()
 5974                        .by_ref()
 5975                        .take_while(|c| c.is_alphabetic())
 5976                        .collect::<String>();
 5977                    if partial_completion.is_empty() {
 5978                        partial_completion = text
 5979                            .chars()
 5980                            .by_ref()
 5981                            .take_while(|c| c.is_whitespace() || !c.is_alphabetic())
 5982                            .collect::<String>();
 5983                    }
 5984
 5985                    cx.emit(EditorEvent::InputHandled {
 5986                        utf16_range_to_replace: None,
 5987                        text: partial_completion.clone().into(),
 5988                    });
 5989
 5990                    self.insert_with_autoindent_mode(&partial_completion, None, window, cx);
 5991
 5992                    self.refresh_inline_completion(true, true, window, cx);
 5993                    cx.notify();
 5994                } else {
 5995                    self.accept_edit_prediction(&Default::default(), window, cx);
 5996                }
 5997            }
 5998        }
 5999    }
 6000
 6001    fn discard_inline_completion(
 6002        &mut self,
 6003        should_report_inline_completion_event: bool,
 6004        cx: &mut Context<Self>,
 6005    ) -> bool {
 6006        if should_report_inline_completion_event {
 6007            let completion_id = self
 6008                .active_inline_completion
 6009                .as_ref()
 6010                .and_then(|active_completion| active_completion.completion_id.clone());
 6011
 6012            self.report_inline_completion_event(completion_id, false, cx);
 6013        }
 6014
 6015        if let Some(provider) = self.edit_prediction_provider() {
 6016            provider.discard(cx);
 6017        }
 6018
 6019        self.take_active_inline_completion(cx)
 6020    }
 6021
 6022    fn report_inline_completion_event(&self, id: Option<SharedString>, accepted: bool, cx: &App) {
 6023        let Some(provider) = self.edit_prediction_provider() else {
 6024            return;
 6025        };
 6026
 6027        let Some((_, buffer, _)) = self
 6028            .buffer
 6029            .read(cx)
 6030            .excerpt_containing(self.selections.newest_anchor().head(), cx)
 6031        else {
 6032            return;
 6033        };
 6034
 6035        let extension = buffer
 6036            .read(cx)
 6037            .file()
 6038            .and_then(|file| Some(file.path().extension()?.to_string_lossy().to_string()));
 6039
 6040        let event_type = match accepted {
 6041            true => "Edit Prediction Accepted",
 6042            false => "Edit Prediction Discarded",
 6043        };
 6044        telemetry::event!(
 6045            event_type,
 6046            provider = provider.name(),
 6047            prediction_id = id,
 6048            suggestion_accepted = accepted,
 6049            file_extension = extension,
 6050        );
 6051    }
 6052
 6053    pub fn has_active_inline_completion(&self) -> bool {
 6054        self.active_inline_completion.is_some()
 6055    }
 6056
 6057    fn take_active_inline_completion(&mut self, cx: &mut Context<Self>) -> bool {
 6058        let Some(active_inline_completion) = self.active_inline_completion.take() else {
 6059            return false;
 6060        };
 6061
 6062        self.splice_inlays(&active_inline_completion.inlay_ids, Default::default(), cx);
 6063        self.clear_highlights::<InlineCompletionHighlight>(cx);
 6064        self.stale_inline_completion_in_menu = Some(active_inline_completion);
 6065        true
 6066    }
 6067
 6068    /// Returns true when we're displaying the edit prediction popover below the cursor
 6069    /// like we are not previewing and the LSP autocomplete menu is visible
 6070    /// or we are in `when_holding_modifier` mode.
 6071    pub fn edit_prediction_visible_in_cursor_popover(&self, has_completion: bool) -> bool {
 6072        if self.edit_prediction_preview_is_active()
 6073            || !self.show_edit_predictions_in_menu()
 6074            || !self.edit_predictions_enabled()
 6075        {
 6076            return false;
 6077        }
 6078
 6079        if self.has_visible_completions_menu() {
 6080            return true;
 6081        }
 6082
 6083        has_completion && self.edit_prediction_requires_modifier()
 6084    }
 6085
 6086    fn handle_modifiers_changed(
 6087        &mut self,
 6088        modifiers: Modifiers,
 6089        position_map: &PositionMap,
 6090        window: &mut Window,
 6091        cx: &mut Context<Self>,
 6092    ) {
 6093        if self.show_edit_predictions_in_menu() {
 6094            self.update_edit_prediction_preview(&modifiers, window, cx);
 6095        }
 6096
 6097        self.update_selection_mode(&modifiers, position_map, window, cx);
 6098
 6099        let mouse_position = window.mouse_position();
 6100        if !position_map.text_hitbox.is_hovered(window) {
 6101            return;
 6102        }
 6103
 6104        self.update_hovered_link(
 6105            position_map.point_for_position(mouse_position),
 6106            &position_map.snapshot,
 6107            modifiers,
 6108            window,
 6109            cx,
 6110        )
 6111    }
 6112
 6113    fn update_selection_mode(
 6114        &mut self,
 6115        modifiers: &Modifiers,
 6116        position_map: &PositionMap,
 6117        window: &mut Window,
 6118        cx: &mut Context<Self>,
 6119    ) {
 6120        if modifiers != &COLUMNAR_SELECTION_MODIFIERS || self.selections.pending.is_none() {
 6121            return;
 6122        }
 6123
 6124        let mouse_position = window.mouse_position();
 6125        let point_for_position = position_map.point_for_position(mouse_position);
 6126        let position = point_for_position.previous_valid;
 6127
 6128        self.select(
 6129            SelectPhase::BeginColumnar {
 6130                position,
 6131                reset: false,
 6132                goal_column: point_for_position.exact_unclipped.column(),
 6133            },
 6134            window,
 6135            cx,
 6136        );
 6137    }
 6138
 6139    fn update_edit_prediction_preview(
 6140        &mut self,
 6141        modifiers: &Modifiers,
 6142        window: &mut Window,
 6143        cx: &mut Context<Self>,
 6144    ) {
 6145        let accept_keybind = self.accept_edit_prediction_keybind(window, cx);
 6146        let Some(accept_keystroke) = accept_keybind.keystroke() else {
 6147            return;
 6148        };
 6149
 6150        if &accept_keystroke.modifiers == modifiers && accept_keystroke.modifiers.modified() {
 6151            if matches!(
 6152                self.edit_prediction_preview,
 6153                EditPredictionPreview::Inactive { .. }
 6154            ) {
 6155                self.edit_prediction_preview = EditPredictionPreview::Active {
 6156                    previous_scroll_position: None,
 6157                    since: Instant::now(),
 6158                };
 6159
 6160                self.update_visible_inline_completion(window, cx);
 6161                cx.notify();
 6162            }
 6163        } else if let EditPredictionPreview::Active {
 6164            previous_scroll_position,
 6165            since,
 6166        } = self.edit_prediction_preview
 6167        {
 6168            if let (Some(previous_scroll_position), Some(position_map)) =
 6169                (previous_scroll_position, self.last_position_map.as_ref())
 6170            {
 6171                self.set_scroll_position(
 6172                    previous_scroll_position
 6173                        .scroll_position(&position_map.snapshot.display_snapshot),
 6174                    window,
 6175                    cx,
 6176                );
 6177            }
 6178
 6179            self.edit_prediction_preview = EditPredictionPreview::Inactive {
 6180                released_too_fast: since.elapsed() < Duration::from_millis(200),
 6181            };
 6182            self.clear_row_highlights::<EditPredictionPreview>();
 6183            self.update_visible_inline_completion(window, cx);
 6184            cx.notify();
 6185        }
 6186    }
 6187
 6188    fn update_visible_inline_completion(
 6189        &mut self,
 6190        _window: &mut Window,
 6191        cx: &mut Context<Self>,
 6192    ) -> Option<()> {
 6193        let selection = self.selections.newest_anchor();
 6194        let cursor = selection.head();
 6195        let multibuffer = self.buffer.read(cx).snapshot(cx);
 6196        let offset_selection = selection.map(|endpoint| endpoint.to_offset(&multibuffer));
 6197        let excerpt_id = cursor.excerpt_id;
 6198
 6199        let show_in_menu = self.show_edit_predictions_in_menu();
 6200        let completions_menu_has_precedence = !show_in_menu
 6201            && (self.context_menu.borrow().is_some()
 6202                || (!self.completion_tasks.is_empty() && !self.has_active_inline_completion()));
 6203
 6204        if completions_menu_has_precedence
 6205            || !offset_selection.is_empty()
 6206            || self
 6207                .active_inline_completion
 6208                .as_ref()
 6209                .map_or(false, |completion| {
 6210                    let invalidation_range = completion.invalidation_range.to_offset(&multibuffer);
 6211                    let invalidation_range = invalidation_range.start..=invalidation_range.end;
 6212                    !invalidation_range.contains(&offset_selection.head())
 6213                })
 6214        {
 6215            self.discard_inline_completion(false, cx);
 6216            return None;
 6217        }
 6218
 6219        self.take_active_inline_completion(cx);
 6220        let Some(provider) = self.edit_prediction_provider() else {
 6221            self.edit_prediction_settings = EditPredictionSettings::Disabled;
 6222            return None;
 6223        };
 6224
 6225        let (buffer, cursor_buffer_position) =
 6226            self.buffer.read(cx).text_anchor_for_position(cursor, cx)?;
 6227
 6228        self.edit_prediction_settings =
 6229            self.edit_prediction_settings_at_position(&buffer, cursor_buffer_position, cx);
 6230
 6231        self.edit_prediction_indent_conflict = multibuffer.is_line_whitespace_upto(cursor);
 6232
 6233        if self.edit_prediction_indent_conflict {
 6234            let cursor_point = cursor.to_point(&multibuffer);
 6235
 6236            let indents = multibuffer.suggested_indents(cursor_point.row..cursor_point.row + 1, cx);
 6237
 6238            if let Some((_, indent)) = indents.iter().next() {
 6239                if indent.len == cursor_point.column {
 6240                    self.edit_prediction_indent_conflict = false;
 6241                }
 6242            }
 6243        }
 6244
 6245        let inline_completion = provider.suggest(&buffer, cursor_buffer_position, cx)?;
 6246        let edits = inline_completion
 6247            .edits
 6248            .into_iter()
 6249            .flat_map(|(range, new_text)| {
 6250                let start = multibuffer.anchor_in_excerpt(excerpt_id, range.start)?;
 6251                let end = multibuffer.anchor_in_excerpt(excerpt_id, range.end)?;
 6252                Some((start..end, new_text))
 6253            })
 6254            .collect::<Vec<_>>();
 6255        if edits.is_empty() {
 6256            return None;
 6257        }
 6258
 6259        let first_edit_start = edits.first().unwrap().0.start;
 6260        let first_edit_start_point = first_edit_start.to_point(&multibuffer);
 6261        let edit_start_row = first_edit_start_point.row.saturating_sub(2);
 6262
 6263        let last_edit_end = edits.last().unwrap().0.end;
 6264        let last_edit_end_point = last_edit_end.to_point(&multibuffer);
 6265        let edit_end_row = cmp::min(multibuffer.max_point().row, last_edit_end_point.row + 2);
 6266
 6267        let cursor_row = cursor.to_point(&multibuffer).row;
 6268
 6269        let snapshot = multibuffer.buffer_for_excerpt(excerpt_id).cloned()?;
 6270
 6271        let mut inlay_ids = Vec::new();
 6272        let invalidation_row_range;
 6273        let move_invalidation_row_range = if cursor_row < edit_start_row {
 6274            Some(cursor_row..edit_end_row)
 6275        } else if cursor_row > edit_end_row {
 6276            Some(edit_start_row..cursor_row)
 6277        } else {
 6278            None
 6279        };
 6280        let is_move =
 6281            move_invalidation_row_range.is_some() || self.inline_completions_hidden_for_vim_mode;
 6282        let completion = if is_move {
 6283            invalidation_row_range =
 6284                move_invalidation_row_range.unwrap_or(edit_start_row..edit_end_row);
 6285            let target = first_edit_start;
 6286            InlineCompletion::Move { target, snapshot }
 6287        } else {
 6288            let show_completions_in_buffer = !self.edit_prediction_visible_in_cursor_popover(true)
 6289                && !self.inline_completions_hidden_for_vim_mode;
 6290
 6291            if show_completions_in_buffer {
 6292                if edits
 6293                    .iter()
 6294                    .all(|(range, _)| range.to_offset(&multibuffer).is_empty())
 6295                {
 6296                    let mut inlays = Vec::new();
 6297                    for (range, new_text) in &edits {
 6298                        let inlay = Inlay::inline_completion(
 6299                            post_inc(&mut self.next_inlay_id),
 6300                            range.start,
 6301                            new_text.as_str(),
 6302                        );
 6303                        inlay_ids.push(inlay.id);
 6304                        inlays.push(inlay);
 6305                    }
 6306
 6307                    self.splice_inlays(&[], inlays, cx);
 6308                } else {
 6309                    let background_color = cx.theme().status().deleted_background;
 6310                    self.highlight_text::<InlineCompletionHighlight>(
 6311                        edits.iter().map(|(range, _)| range.clone()).collect(),
 6312                        HighlightStyle {
 6313                            background_color: Some(background_color),
 6314                            ..Default::default()
 6315                        },
 6316                        cx,
 6317                    );
 6318                }
 6319            }
 6320
 6321            invalidation_row_range = edit_start_row..edit_end_row;
 6322
 6323            let display_mode = if all_edits_insertions_or_deletions(&edits, &multibuffer) {
 6324                if provider.show_tab_accept_marker() {
 6325                    EditDisplayMode::TabAccept
 6326                } else {
 6327                    EditDisplayMode::Inline
 6328                }
 6329            } else {
 6330                EditDisplayMode::DiffPopover
 6331            };
 6332
 6333            InlineCompletion::Edit {
 6334                edits,
 6335                edit_preview: inline_completion.edit_preview,
 6336                display_mode,
 6337                snapshot,
 6338            }
 6339        };
 6340
 6341        let invalidation_range = multibuffer
 6342            .anchor_before(Point::new(invalidation_row_range.start, 0))
 6343            ..multibuffer.anchor_after(Point::new(
 6344                invalidation_row_range.end,
 6345                multibuffer.line_len(MultiBufferRow(invalidation_row_range.end)),
 6346            ));
 6347
 6348        self.stale_inline_completion_in_menu = None;
 6349        self.active_inline_completion = Some(InlineCompletionState {
 6350            inlay_ids,
 6351            completion,
 6352            completion_id: inline_completion.id,
 6353            invalidation_range,
 6354        });
 6355
 6356        cx.notify();
 6357
 6358        Some(())
 6359    }
 6360
 6361    pub fn edit_prediction_provider(&self) -> Option<Arc<dyn InlineCompletionProviderHandle>> {
 6362        Some(self.edit_prediction_provider.as_ref()?.provider.clone())
 6363    }
 6364
 6365    fn render_code_actions_indicator(
 6366        &self,
 6367        _style: &EditorStyle,
 6368        row: DisplayRow,
 6369        is_active: bool,
 6370        breakpoint: Option<&(Anchor, Breakpoint)>,
 6371        cx: &mut Context<Self>,
 6372    ) -> Option<IconButton> {
 6373        let color = Color::Muted;
 6374        let position = breakpoint.as_ref().map(|(anchor, _)| *anchor);
 6375        let show_tooltip = !self.context_menu_visible();
 6376
 6377        if self.available_code_actions.is_some() {
 6378            Some(
 6379                IconButton::new("code_actions_indicator", ui::IconName::Bolt)
 6380                    .shape(ui::IconButtonShape::Square)
 6381                    .icon_size(IconSize::XSmall)
 6382                    .icon_color(color)
 6383                    .toggle_state(is_active)
 6384                    .when(show_tooltip, |this| {
 6385                        this.tooltip({
 6386                            let focus_handle = self.focus_handle.clone();
 6387                            move |window, cx| {
 6388                                Tooltip::for_action_in(
 6389                                    "Toggle Code Actions",
 6390                                    &ToggleCodeActions {
 6391                                        deployed_from_indicator: None,
 6392                                    },
 6393                                    &focus_handle,
 6394                                    window,
 6395                                    cx,
 6396                                )
 6397                            }
 6398                        })
 6399                    })
 6400                    .on_click(cx.listener(move |editor, _e, window, cx| {
 6401                        window.focus(&editor.focus_handle(cx));
 6402                        editor.toggle_code_actions(
 6403                            &ToggleCodeActions {
 6404                                deployed_from_indicator: Some(row),
 6405                            },
 6406                            window,
 6407                            cx,
 6408                        );
 6409                    }))
 6410                    .on_right_click(cx.listener(move |editor, event: &ClickEvent, window, cx| {
 6411                        editor.set_breakpoint_context_menu(
 6412                            row,
 6413                            position,
 6414                            event.down.position,
 6415                            window,
 6416                            cx,
 6417                        );
 6418                    })),
 6419            )
 6420        } else {
 6421            None
 6422        }
 6423    }
 6424
 6425    fn clear_tasks(&mut self) {
 6426        self.tasks.clear()
 6427    }
 6428
 6429    fn insert_tasks(&mut self, key: (BufferId, BufferRow), value: RunnableTasks) {
 6430        if self.tasks.insert(key, value).is_some() {
 6431            // This case should hopefully be rare, but just in case...
 6432            log::error!(
 6433                "multiple different run targets found on a single line, only the last target will be rendered"
 6434            )
 6435        }
 6436    }
 6437
 6438    /// Get all display points of breakpoints that will be rendered within editor
 6439    ///
 6440    /// This function is used to handle overlaps between breakpoints and Code action/runner symbol.
 6441    /// It's also used to set the color of line numbers with breakpoints to the breakpoint color.
 6442    /// TODO debugger: Use this function to color toggle symbols that house nested breakpoints
 6443    fn active_breakpoints(
 6444        &self,
 6445        range: Range<DisplayRow>,
 6446        window: &mut Window,
 6447        cx: &mut Context<Self>,
 6448    ) -> HashMap<DisplayRow, (Anchor, Breakpoint)> {
 6449        let mut breakpoint_display_points = HashMap::default();
 6450
 6451        let Some(breakpoint_store) = self.breakpoint_store.clone() else {
 6452            return breakpoint_display_points;
 6453        };
 6454
 6455        let snapshot = self.snapshot(window, cx);
 6456
 6457        let multi_buffer_snapshot = &snapshot.display_snapshot.buffer_snapshot;
 6458        let Some(project) = self.project.as_ref() else {
 6459            return breakpoint_display_points;
 6460        };
 6461
 6462        let range = snapshot.display_point_to_point(DisplayPoint::new(range.start, 0), Bias::Left)
 6463            ..snapshot.display_point_to_point(DisplayPoint::new(range.end, 0), Bias::Right);
 6464
 6465        for (buffer_snapshot, range, excerpt_id) in
 6466            multi_buffer_snapshot.range_to_buffer_ranges(range)
 6467        {
 6468            let Some(buffer) = project.read_with(cx, |this, cx| {
 6469                this.buffer_for_id(buffer_snapshot.remote_id(), cx)
 6470            }) else {
 6471                continue;
 6472            };
 6473            let breakpoints = breakpoint_store.read(cx).breakpoints(
 6474                &buffer,
 6475                Some(
 6476                    buffer_snapshot.anchor_before(range.start)
 6477                        ..buffer_snapshot.anchor_after(range.end),
 6478                ),
 6479                buffer_snapshot,
 6480                cx,
 6481            );
 6482            for (anchor, breakpoint) in breakpoints {
 6483                let multi_buffer_anchor =
 6484                    Anchor::in_buffer(excerpt_id, buffer_snapshot.remote_id(), *anchor);
 6485                let position = multi_buffer_anchor
 6486                    .to_point(&multi_buffer_snapshot)
 6487                    .to_display_point(&snapshot);
 6488
 6489                breakpoint_display_points
 6490                    .insert(position.row(), (multi_buffer_anchor, breakpoint.clone()));
 6491            }
 6492        }
 6493
 6494        breakpoint_display_points
 6495    }
 6496
 6497    fn breakpoint_context_menu(
 6498        &self,
 6499        anchor: Anchor,
 6500        window: &mut Window,
 6501        cx: &mut Context<Self>,
 6502    ) -> Entity<ui::ContextMenu> {
 6503        let weak_editor = cx.weak_entity();
 6504        let focus_handle = self.focus_handle(cx);
 6505
 6506        let row = self
 6507            .buffer
 6508            .read(cx)
 6509            .snapshot(cx)
 6510            .summary_for_anchor::<Point>(&anchor)
 6511            .row;
 6512
 6513        let breakpoint = self
 6514            .breakpoint_at_row(row, window, cx)
 6515            .map(|(anchor, bp)| (anchor, Arc::from(bp)));
 6516
 6517        let log_breakpoint_msg = if breakpoint.as_ref().is_some_and(|bp| bp.1.message.is_some()) {
 6518            "Edit Log Breakpoint"
 6519        } else {
 6520            "Set Log Breakpoint"
 6521        };
 6522
 6523        let condition_breakpoint_msg = if breakpoint
 6524            .as_ref()
 6525            .is_some_and(|bp| bp.1.condition.is_some())
 6526        {
 6527            "Edit Condition Breakpoint"
 6528        } else {
 6529            "Set Condition Breakpoint"
 6530        };
 6531
 6532        let hit_condition_breakpoint_msg = if breakpoint
 6533            .as_ref()
 6534            .is_some_and(|bp| bp.1.hit_condition.is_some())
 6535        {
 6536            "Edit Hit Condition Breakpoint"
 6537        } else {
 6538            "Set Hit Condition Breakpoint"
 6539        };
 6540
 6541        let set_breakpoint_msg = if breakpoint.as_ref().is_some() {
 6542            "Unset Breakpoint"
 6543        } else {
 6544            "Set Breakpoint"
 6545        };
 6546
 6547        let run_to_cursor = command_palette_hooks::CommandPaletteFilter::try_global(cx)
 6548            .map_or(false, |filter| !filter.is_hidden(&DebuggerRunToCursor));
 6549
 6550        let toggle_state_msg = breakpoint.as_ref().map_or(None, |bp| match bp.1.state {
 6551            BreakpointState::Enabled => Some("Disable"),
 6552            BreakpointState::Disabled => Some("Enable"),
 6553        });
 6554
 6555        let (anchor, breakpoint) =
 6556            breakpoint.unwrap_or_else(|| (anchor, Arc::new(Breakpoint::new_standard())));
 6557
 6558        ui::ContextMenu::build(window, cx, |menu, _, _cx| {
 6559            menu.on_blur_subscription(Subscription::new(|| {}))
 6560                .context(focus_handle)
 6561                .when(run_to_cursor, |this| {
 6562                    let weak_editor = weak_editor.clone();
 6563                    this.entry("Run to cursor", None, move |window, cx| {
 6564                        weak_editor
 6565                            .update(cx, |editor, cx| {
 6566                                editor.change_selections(None, window, cx, |s| {
 6567                                    s.select_ranges([Point::new(row, 0)..Point::new(row, 0)])
 6568                                });
 6569                            })
 6570                            .ok();
 6571
 6572                        window.dispatch_action(Box::new(DebuggerRunToCursor), cx);
 6573                    })
 6574                    .separator()
 6575                })
 6576                .when_some(toggle_state_msg, |this, msg| {
 6577                    this.entry(msg, None, {
 6578                        let weak_editor = weak_editor.clone();
 6579                        let breakpoint = breakpoint.clone();
 6580                        move |_window, cx| {
 6581                            weak_editor
 6582                                .update(cx, |this, cx| {
 6583                                    this.edit_breakpoint_at_anchor(
 6584                                        anchor,
 6585                                        breakpoint.as_ref().clone(),
 6586                                        BreakpointEditAction::InvertState,
 6587                                        cx,
 6588                                    );
 6589                                })
 6590                                .log_err();
 6591                        }
 6592                    })
 6593                })
 6594                .entry(set_breakpoint_msg, None, {
 6595                    let weak_editor = weak_editor.clone();
 6596                    let breakpoint = breakpoint.clone();
 6597                    move |_window, cx| {
 6598                        weak_editor
 6599                            .update(cx, |this, cx| {
 6600                                this.edit_breakpoint_at_anchor(
 6601                                    anchor,
 6602                                    breakpoint.as_ref().clone(),
 6603                                    BreakpointEditAction::Toggle,
 6604                                    cx,
 6605                                );
 6606                            })
 6607                            .log_err();
 6608                    }
 6609                })
 6610                .entry(log_breakpoint_msg, None, {
 6611                    let breakpoint = breakpoint.clone();
 6612                    let weak_editor = weak_editor.clone();
 6613                    move |window, cx| {
 6614                        weak_editor
 6615                            .update(cx, |this, cx| {
 6616                                this.add_edit_breakpoint_block(
 6617                                    anchor,
 6618                                    breakpoint.as_ref(),
 6619                                    BreakpointPromptEditAction::Log,
 6620                                    window,
 6621                                    cx,
 6622                                );
 6623                            })
 6624                            .log_err();
 6625                    }
 6626                })
 6627                .entry(condition_breakpoint_msg, None, {
 6628                    let breakpoint = breakpoint.clone();
 6629                    let weak_editor = weak_editor.clone();
 6630                    move |window, cx| {
 6631                        weak_editor
 6632                            .update(cx, |this, cx| {
 6633                                this.add_edit_breakpoint_block(
 6634                                    anchor,
 6635                                    breakpoint.as_ref(),
 6636                                    BreakpointPromptEditAction::Condition,
 6637                                    window,
 6638                                    cx,
 6639                                );
 6640                            })
 6641                            .log_err();
 6642                    }
 6643                })
 6644                .entry(hit_condition_breakpoint_msg, None, move |window, cx| {
 6645                    weak_editor
 6646                        .update(cx, |this, cx| {
 6647                            this.add_edit_breakpoint_block(
 6648                                anchor,
 6649                                breakpoint.as_ref(),
 6650                                BreakpointPromptEditAction::HitCondition,
 6651                                window,
 6652                                cx,
 6653                            );
 6654                        })
 6655                        .log_err();
 6656                })
 6657        })
 6658    }
 6659
 6660    fn render_breakpoint(
 6661        &self,
 6662        position: Anchor,
 6663        row: DisplayRow,
 6664        breakpoint: &Breakpoint,
 6665        cx: &mut Context<Self>,
 6666    ) -> IconButton {
 6667        let (color, icon) = {
 6668            let icon = match (&breakpoint.message.is_some(), breakpoint.is_disabled()) {
 6669                (false, false) => ui::IconName::DebugBreakpoint,
 6670                (true, false) => ui::IconName::DebugLogBreakpoint,
 6671                (false, true) => ui::IconName::DebugDisabledBreakpoint,
 6672                (true, true) => ui::IconName::DebugDisabledLogBreakpoint,
 6673            };
 6674
 6675            let color = if self
 6676                .gutter_breakpoint_indicator
 6677                .0
 6678                .is_some_and(|(point, is_visible)| is_visible && point.row() == row)
 6679            {
 6680                Color::Hint
 6681            } else {
 6682                Color::Debugger
 6683            };
 6684
 6685            (color, icon)
 6686        };
 6687
 6688        let breakpoint = Arc::from(breakpoint.clone());
 6689
 6690        IconButton::new(("breakpoint_indicator", row.0 as usize), icon)
 6691            .icon_size(IconSize::XSmall)
 6692            .size(ui::ButtonSize::None)
 6693            .icon_color(color)
 6694            .style(ButtonStyle::Transparent)
 6695            .on_click(cx.listener({
 6696                let breakpoint = breakpoint.clone();
 6697
 6698                move |editor, event: &ClickEvent, window, cx| {
 6699                    let edit_action = if event.modifiers().platform || breakpoint.is_disabled() {
 6700                        BreakpointEditAction::InvertState
 6701                    } else {
 6702                        BreakpointEditAction::Toggle
 6703                    };
 6704
 6705                    window.focus(&editor.focus_handle(cx));
 6706                    editor.edit_breakpoint_at_anchor(
 6707                        position,
 6708                        breakpoint.as_ref().clone(),
 6709                        edit_action,
 6710                        cx,
 6711                    );
 6712                }
 6713            }))
 6714            .on_right_click(cx.listener(move |editor, event: &ClickEvent, window, cx| {
 6715                editor.set_breakpoint_context_menu(
 6716                    row,
 6717                    Some(position),
 6718                    event.down.position,
 6719                    window,
 6720                    cx,
 6721                );
 6722            }))
 6723    }
 6724
 6725    fn build_tasks_context(
 6726        project: &Entity<Project>,
 6727        buffer: &Entity<Buffer>,
 6728        buffer_row: u32,
 6729        tasks: &Arc<RunnableTasks>,
 6730        cx: &mut Context<Self>,
 6731    ) -> Task<Option<task::TaskContext>> {
 6732        let position = Point::new(buffer_row, tasks.column);
 6733        let range_start = buffer.read(cx).anchor_at(position, Bias::Right);
 6734        let location = Location {
 6735            buffer: buffer.clone(),
 6736            range: range_start..range_start,
 6737        };
 6738        // Fill in the environmental variables from the tree-sitter captures
 6739        let mut captured_task_variables = TaskVariables::default();
 6740        for (capture_name, value) in tasks.extra_variables.clone() {
 6741            captured_task_variables.insert(
 6742                task::VariableName::Custom(capture_name.into()),
 6743                value.clone(),
 6744            );
 6745        }
 6746        project.update(cx, |project, cx| {
 6747            project.task_store().update(cx, |task_store, cx| {
 6748                task_store.task_context_for_location(captured_task_variables, location, cx)
 6749            })
 6750        })
 6751    }
 6752
 6753    pub fn spawn_nearest_task(
 6754        &mut self,
 6755        action: &SpawnNearestTask,
 6756        window: &mut Window,
 6757        cx: &mut Context<Self>,
 6758    ) {
 6759        let Some((workspace, _)) = self.workspace.clone() else {
 6760            return;
 6761        };
 6762        let Some(project) = self.project.clone() else {
 6763            return;
 6764        };
 6765
 6766        // Try to find a closest, enclosing node using tree-sitter that has a
 6767        // task
 6768        let Some((buffer, buffer_row, tasks)) = self
 6769            .find_enclosing_node_task(cx)
 6770            // Or find the task that's closest in row-distance.
 6771            .or_else(|| self.find_closest_task(cx))
 6772        else {
 6773            return;
 6774        };
 6775
 6776        let reveal_strategy = action.reveal;
 6777        let task_context = Self::build_tasks_context(&project, &buffer, buffer_row, &tasks, cx);
 6778        cx.spawn_in(window, async move |_, cx| {
 6779            let context = task_context.await?;
 6780            let (task_source_kind, mut resolved_task) = tasks.resolve(&context).next()?;
 6781
 6782            let resolved = resolved_task.resolved.as_mut()?;
 6783            resolved.reveal = reveal_strategy;
 6784
 6785            workspace
 6786                .update(cx, |workspace, cx| {
 6787                    workspace::tasks::schedule_resolved_task(
 6788                        workspace,
 6789                        task_source_kind,
 6790                        resolved_task,
 6791                        false,
 6792                        cx,
 6793                    );
 6794                })
 6795                .ok()
 6796        })
 6797        .detach();
 6798    }
 6799
 6800    fn find_closest_task(
 6801        &mut self,
 6802        cx: &mut Context<Self>,
 6803    ) -> Option<(Entity<Buffer>, u32, Arc<RunnableTasks>)> {
 6804        let cursor_row = self.selections.newest_adjusted(cx).head().row;
 6805
 6806        let ((buffer_id, row), tasks) = self
 6807            .tasks
 6808            .iter()
 6809            .min_by_key(|((_, row), _)| cursor_row.abs_diff(*row))?;
 6810
 6811        let buffer = self.buffer.read(cx).buffer(*buffer_id)?;
 6812        let tasks = Arc::new(tasks.to_owned());
 6813        Some((buffer, *row, tasks))
 6814    }
 6815
 6816    fn find_enclosing_node_task(
 6817        &mut self,
 6818        cx: &mut Context<Self>,
 6819    ) -> Option<(Entity<Buffer>, u32, Arc<RunnableTasks>)> {
 6820        let snapshot = self.buffer.read(cx).snapshot(cx);
 6821        let offset = self.selections.newest::<usize>(cx).head();
 6822        let excerpt = snapshot.excerpt_containing(offset..offset)?;
 6823        let buffer_id = excerpt.buffer().remote_id();
 6824
 6825        let layer = excerpt.buffer().syntax_layer_at(offset)?;
 6826        let mut cursor = layer.node().walk();
 6827
 6828        while cursor.goto_first_child_for_byte(offset).is_some() {
 6829            if cursor.node().end_byte() == offset {
 6830                cursor.goto_next_sibling();
 6831            }
 6832        }
 6833
 6834        // Ascend to the smallest ancestor that contains the range and has a task.
 6835        loop {
 6836            let node = cursor.node();
 6837            let node_range = node.byte_range();
 6838            let symbol_start_row = excerpt.buffer().offset_to_point(node.start_byte()).row;
 6839
 6840            // Check if this node contains our offset
 6841            if node_range.start <= offset && node_range.end >= offset {
 6842                // If it contains offset, check for task
 6843                if let Some(tasks) = self.tasks.get(&(buffer_id, symbol_start_row)) {
 6844                    let buffer = self.buffer.read(cx).buffer(buffer_id)?;
 6845                    return Some((buffer, symbol_start_row, Arc::new(tasks.to_owned())));
 6846                }
 6847            }
 6848
 6849            if !cursor.goto_parent() {
 6850                break;
 6851            }
 6852        }
 6853        None
 6854    }
 6855
 6856    fn render_run_indicator(
 6857        &self,
 6858        _style: &EditorStyle,
 6859        is_active: bool,
 6860        row: DisplayRow,
 6861        breakpoint: Option<(Anchor, Breakpoint)>,
 6862        cx: &mut Context<Self>,
 6863    ) -> IconButton {
 6864        let color = Color::Muted;
 6865        let position = breakpoint.as_ref().map(|(anchor, _)| *anchor);
 6866
 6867        IconButton::new(("run_indicator", row.0 as usize), ui::IconName::Play)
 6868            .shape(ui::IconButtonShape::Square)
 6869            .icon_size(IconSize::XSmall)
 6870            .icon_color(color)
 6871            .toggle_state(is_active)
 6872            .on_click(cx.listener(move |editor, _e, window, cx| {
 6873                window.focus(&editor.focus_handle(cx));
 6874                editor.toggle_code_actions(
 6875                    &ToggleCodeActions {
 6876                        deployed_from_indicator: Some(row),
 6877                    },
 6878                    window,
 6879                    cx,
 6880                );
 6881            }))
 6882            .on_right_click(cx.listener(move |editor, event: &ClickEvent, window, cx| {
 6883                editor.set_breakpoint_context_menu(row, position, event.down.position, window, cx);
 6884            }))
 6885    }
 6886
 6887    pub fn context_menu_visible(&self) -> bool {
 6888        !self.edit_prediction_preview_is_active()
 6889            && self
 6890                .context_menu
 6891                .borrow()
 6892                .as_ref()
 6893                .map_or(false, |menu| menu.visible())
 6894    }
 6895
 6896    fn context_menu_origin(&self) -> Option<ContextMenuOrigin> {
 6897        self.context_menu
 6898            .borrow()
 6899            .as_ref()
 6900            .map(|menu| menu.origin())
 6901    }
 6902
 6903    pub fn set_context_menu_options(&mut self, options: ContextMenuOptions) {
 6904        self.context_menu_options = Some(options);
 6905    }
 6906
 6907    const EDIT_PREDICTION_POPOVER_PADDING_X: Pixels = Pixels(24.);
 6908    const EDIT_PREDICTION_POPOVER_PADDING_Y: Pixels = Pixels(2.);
 6909
 6910    fn render_edit_prediction_popover(
 6911        &mut self,
 6912        text_bounds: &Bounds<Pixels>,
 6913        content_origin: gpui::Point<Pixels>,
 6914        editor_snapshot: &EditorSnapshot,
 6915        visible_row_range: Range<DisplayRow>,
 6916        scroll_top: f32,
 6917        scroll_bottom: f32,
 6918        line_layouts: &[LineWithInvisibles],
 6919        line_height: Pixels,
 6920        scroll_pixel_position: gpui::Point<Pixels>,
 6921        newest_selection_head: Option<DisplayPoint>,
 6922        editor_width: Pixels,
 6923        style: &EditorStyle,
 6924        window: &mut Window,
 6925        cx: &mut App,
 6926    ) -> Option<(AnyElement, gpui::Point<Pixels>)> {
 6927        let active_inline_completion = self.active_inline_completion.as_ref()?;
 6928
 6929        if self.edit_prediction_visible_in_cursor_popover(true) {
 6930            return None;
 6931        }
 6932
 6933        match &active_inline_completion.completion {
 6934            InlineCompletion::Move { target, .. } => {
 6935                let target_display_point = target.to_display_point(editor_snapshot);
 6936
 6937                if self.edit_prediction_requires_modifier() {
 6938                    if !self.edit_prediction_preview_is_active() {
 6939                        return None;
 6940                    }
 6941
 6942                    self.render_edit_prediction_modifier_jump_popover(
 6943                        text_bounds,
 6944                        content_origin,
 6945                        visible_row_range,
 6946                        line_layouts,
 6947                        line_height,
 6948                        scroll_pixel_position,
 6949                        newest_selection_head,
 6950                        target_display_point,
 6951                        window,
 6952                        cx,
 6953                    )
 6954                } else {
 6955                    self.render_edit_prediction_eager_jump_popover(
 6956                        text_bounds,
 6957                        content_origin,
 6958                        editor_snapshot,
 6959                        visible_row_range,
 6960                        scroll_top,
 6961                        scroll_bottom,
 6962                        line_height,
 6963                        scroll_pixel_position,
 6964                        target_display_point,
 6965                        editor_width,
 6966                        window,
 6967                        cx,
 6968                    )
 6969                }
 6970            }
 6971            InlineCompletion::Edit {
 6972                display_mode: EditDisplayMode::Inline,
 6973                ..
 6974            } => None,
 6975            InlineCompletion::Edit {
 6976                display_mode: EditDisplayMode::TabAccept,
 6977                edits,
 6978                ..
 6979            } => {
 6980                let range = &edits.first()?.0;
 6981                let target_display_point = range.end.to_display_point(editor_snapshot);
 6982
 6983                self.render_edit_prediction_end_of_line_popover(
 6984                    "Accept",
 6985                    editor_snapshot,
 6986                    visible_row_range,
 6987                    target_display_point,
 6988                    line_height,
 6989                    scroll_pixel_position,
 6990                    content_origin,
 6991                    editor_width,
 6992                    window,
 6993                    cx,
 6994                )
 6995            }
 6996            InlineCompletion::Edit {
 6997                edits,
 6998                edit_preview,
 6999                display_mode: EditDisplayMode::DiffPopover,
 7000                snapshot,
 7001            } => self.render_edit_prediction_diff_popover(
 7002                text_bounds,
 7003                content_origin,
 7004                editor_snapshot,
 7005                visible_row_range,
 7006                line_layouts,
 7007                line_height,
 7008                scroll_pixel_position,
 7009                newest_selection_head,
 7010                editor_width,
 7011                style,
 7012                edits,
 7013                edit_preview,
 7014                snapshot,
 7015                window,
 7016                cx,
 7017            ),
 7018        }
 7019    }
 7020
 7021    fn render_edit_prediction_modifier_jump_popover(
 7022        &mut self,
 7023        text_bounds: &Bounds<Pixels>,
 7024        content_origin: gpui::Point<Pixels>,
 7025        visible_row_range: Range<DisplayRow>,
 7026        line_layouts: &[LineWithInvisibles],
 7027        line_height: Pixels,
 7028        scroll_pixel_position: gpui::Point<Pixels>,
 7029        newest_selection_head: Option<DisplayPoint>,
 7030        target_display_point: DisplayPoint,
 7031        window: &mut Window,
 7032        cx: &mut App,
 7033    ) -> Option<(AnyElement, gpui::Point<Pixels>)> {
 7034        let scrolled_content_origin =
 7035            content_origin - gpui::Point::new(scroll_pixel_position.x, Pixels(0.0));
 7036
 7037        const SCROLL_PADDING_Y: Pixels = px(12.);
 7038
 7039        if target_display_point.row() < visible_row_range.start {
 7040            return self.render_edit_prediction_scroll_popover(
 7041                |_| SCROLL_PADDING_Y,
 7042                IconName::ArrowUp,
 7043                visible_row_range,
 7044                line_layouts,
 7045                newest_selection_head,
 7046                scrolled_content_origin,
 7047                window,
 7048                cx,
 7049            );
 7050        } else if target_display_point.row() >= visible_row_range.end {
 7051            return self.render_edit_prediction_scroll_popover(
 7052                |size| text_bounds.size.height - size.height - SCROLL_PADDING_Y,
 7053                IconName::ArrowDown,
 7054                visible_row_range,
 7055                line_layouts,
 7056                newest_selection_head,
 7057                scrolled_content_origin,
 7058                window,
 7059                cx,
 7060            );
 7061        }
 7062
 7063        const POLE_WIDTH: Pixels = px(2.);
 7064
 7065        let line_layout =
 7066            line_layouts.get(target_display_point.row().minus(visible_row_range.start) as usize)?;
 7067        let target_column = target_display_point.column() as usize;
 7068
 7069        let target_x = line_layout.x_for_index(target_column);
 7070        let target_y =
 7071            (target_display_point.row().as_f32() * line_height) - scroll_pixel_position.y;
 7072
 7073        let flag_on_right = target_x < text_bounds.size.width / 2.;
 7074
 7075        let mut border_color = Self::edit_prediction_callout_popover_border_color(cx);
 7076        border_color.l += 0.001;
 7077
 7078        let mut element = v_flex()
 7079            .items_end()
 7080            .when(flag_on_right, |el| el.items_start())
 7081            .child(if flag_on_right {
 7082                self.render_edit_prediction_line_popover("Jump", None, window, cx)?
 7083                    .rounded_bl(px(0.))
 7084                    .rounded_tl(px(0.))
 7085                    .border_l_2()
 7086                    .border_color(border_color)
 7087            } else {
 7088                self.render_edit_prediction_line_popover("Jump", None, window, cx)?
 7089                    .rounded_br(px(0.))
 7090                    .rounded_tr(px(0.))
 7091                    .border_r_2()
 7092                    .border_color(border_color)
 7093            })
 7094            .child(div().w(POLE_WIDTH).bg(border_color).h(line_height))
 7095            .into_any();
 7096
 7097        let size = element.layout_as_root(AvailableSpace::min_size(), window, cx);
 7098
 7099        let mut origin = scrolled_content_origin + point(target_x, target_y)
 7100            - point(
 7101                if flag_on_right {
 7102                    POLE_WIDTH
 7103                } else {
 7104                    size.width - POLE_WIDTH
 7105                },
 7106                size.height - line_height,
 7107            );
 7108
 7109        origin.x = origin.x.max(content_origin.x);
 7110
 7111        element.prepaint_at(origin, window, cx);
 7112
 7113        Some((element, origin))
 7114    }
 7115
 7116    fn render_edit_prediction_scroll_popover(
 7117        &mut self,
 7118        to_y: impl Fn(Size<Pixels>) -> Pixels,
 7119        scroll_icon: IconName,
 7120        visible_row_range: Range<DisplayRow>,
 7121        line_layouts: &[LineWithInvisibles],
 7122        newest_selection_head: Option<DisplayPoint>,
 7123        scrolled_content_origin: gpui::Point<Pixels>,
 7124        window: &mut Window,
 7125        cx: &mut App,
 7126    ) -> Option<(AnyElement, gpui::Point<Pixels>)> {
 7127        let mut element = self
 7128            .render_edit_prediction_line_popover("Scroll", Some(scroll_icon), window, cx)?
 7129            .into_any();
 7130
 7131        let size = element.layout_as_root(AvailableSpace::min_size(), window, cx);
 7132
 7133        let cursor = newest_selection_head?;
 7134        let cursor_row_layout =
 7135            line_layouts.get(cursor.row().minus(visible_row_range.start) as usize)?;
 7136        let cursor_column = cursor.column() as usize;
 7137
 7138        let cursor_character_x = cursor_row_layout.x_for_index(cursor_column);
 7139
 7140        let origin = scrolled_content_origin + point(cursor_character_x, to_y(size));
 7141
 7142        element.prepaint_at(origin, window, cx);
 7143        Some((element, origin))
 7144    }
 7145
 7146    fn render_edit_prediction_eager_jump_popover(
 7147        &mut self,
 7148        text_bounds: &Bounds<Pixels>,
 7149        content_origin: gpui::Point<Pixels>,
 7150        editor_snapshot: &EditorSnapshot,
 7151        visible_row_range: Range<DisplayRow>,
 7152        scroll_top: f32,
 7153        scroll_bottom: f32,
 7154        line_height: Pixels,
 7155        scroll_pixel_position: gpui::Point<Pixels>,
 7156        target_display_point: DisplayPoint,
 7157        editor_width: Pixels,
 7158        window: &mut Window,
 7159        cx: &mut App,
 7160    ) -> Option<(AnyElement, gpui::Point<Pixels>)> {
 7161        if target_display_point.row().as_f32() < scroll_top {
 7162            let mut element = self
 7163                .render_edit_prediction_line_popover(
 7164                    "Jump to Edit",
 7165                    Some(IconName::ArrowUp),
 7166                    window,
 7167                    cx,
 7168                )?
 7169                .into_any();
 7170
 7171            let size = element.layout_as_root(AvailableSpace::min_size(), window, cx);
 7172            let offset = point(
 7173                (text_bounds.size.width - size.width) / 2.,
 7174                Self::EDIT_PREDICTION_POPOVER_PADDING_Y,
 7175            );
 7176
 7177            let origin = text_bounds.origin + offset;
 7178            element.prepaint_at(origin, window, cx);
 7179            Some((element, origin))
 7180        } else if (target_display_point.row().as_f32() + 1.) > scroll_bottom {
 7181            let mut element = self
 7182                .render_edit_prediction_line_popover(
 7183                    "Jump to Edit",
 7184                    Some(IconName::ArrowDown),
 7185                    window,
 7186                    cx,
 7187                )?
 7188                .into_any();
 7189
 7190            let size = element.layout_as_root(AvailableSpace::min_size(), window, cx);
 7191            let offset = point(
 7192                (text_bounds.size.width - size.width) / 2.,
 7193                text_bounds.size.height - size.height - Self::EDIT_PREDICTION_POPOVER_PADDING_Y,
 7194            );
 7195
 7196            let origin = text_bounds.origin + offset;
 7197            element.prepaint_at(origin, window, cx);
 7198            Some((element, origin))
 7199        } else {
 7200            self.render_edit_prediction_end_of_line_popover(
 7201                "Jump to Edit",
 7202                editor_snapshot,
 7203                visible_row_range,
 7204                target_display_point,
 7205                line_height,
 7206                scroll_pixel_position,
 7207                content_origin,
 7208                editor_width,
 7209                window,
 7210                cx,
 7211            )
 7212        }
 7213    }
 7214
 7215    fn render_edit_prediction_end_of_line_popover(
 7216        self: &mut Editor,
 7217        label: &'static str,
 7218        editor_snapshot: &EditorSnapshot,
 7219        visible_row_range: Range<DisplayRow>,
 7220        target_display_point: DisplayPoint,
 7221        line_height: Pixels,
 7222        scroll_pixel_position: gpui::Point<Pixels>,
 7223        content_origin: gpui::Point<Pixels>,
 7224        editor_width: Pixels,
 7225        window: &mut Window,
 7226        cx: &mut App,
 7227    ) -> Option<(AnyElement, gpui::Point<Pixels>)> {
 7228        let target_line_end = DisplayPoint::new(
 7229            target_display_point.row(),
 7230            editor_snapshot.line_len(target_display_point.row()),
 7231        );
 7232
 7233        let mut element = self
 7234            .render_edit_prediction_line_popover(label, None, window, cx)?
 7235            .into_any();
 7236
 7237        let size = element.layout_as_root(AvailableSpace::min_size(), window, cx);
 7238
 7239        let line_origin = self.display_to_pixel_point(target_line_end, editor_snapshot, window)?;
 7240
 7241        let start_point = content_origin - point(scroll_pixel_position.x, Pixels::ZERO);
 7242        let mut origin = start_point
 7243            + line_origin
 7244            + point(Self::EDIT_PREDICTION_POPOVER_PADDING_X, Pixels::ZERO);
 7245        origin.x = origin.x.max(content_origin.x);
 7246
 7247        let max_x = content_origin.x + editor_width - size.width;
 7248
 7249        if origin.x > max_x {
 7250            let offset = line_height + Self::EDIT_PREDICTION_POPOVER_PADDING_Y;
 7251
 7252            let icon = if visible_row_range.contains(&(target_display_point.row() + 2)) {
 7253                origin.y += offset;
 7254                IconName::ArrowUp
 7255            } else {
 7256                origin.y -= offset;
 7257                IconName::ArrowDown
 7258            };
 7259
 7260            element = self
 7261                .render_edit_prediction_line_popover(label, Some(icon), window, cx)?
 7262                .into_any();
 7263
 7264            let size = element.layout_as_root(AvailableSpace::min_size(), window, cx);
 7265
 7266            origin.x = content_origin.x + editor_width - size.width - px(2.);
 7267        }
 7268
 7269        element.prepaint_at(origin, window, cx);
 7270        Some((element, origin))
 7271    }
 7272
 7273    fn render_edit_prediction_diff_popover(
 7274        self: &Editor,
 7275        text_bounds: &Bounds<Pixels>,
 7276        content_origin: gpui::Point<Pixels>,
 7277        editor_snapshot: &EditorSnapshot,
 7278        visible_row_range: Range<DisplayRow>,
 7279        line_layouts: &[LineWithInvisibles],
 7280        line_height: Pixels,
 7281        scroll_pixel_position: gpui::Point<Pixels>,
 7282        newest_selection_head: Option<DisplayPoint>,
 7283        editor_width: Pixels,
 7284        style: &EditorStyle,
 7285        edits: &Vec<(Range<Anchor>, String)>,
 7286        edit_preview: &Option<language::EditPreview>,
 7287        snapshot: &language::BufferSnapshot,
 7288        window: &mut Window,
 7289        cx: &mut App,
 7290    ) -> Option<(AnyElement, gpui::Point<Pixels>)> {
 7291        let edit_start = edits
 7292            .first()
 7293            .unwrap()
 7294            .0
 7295            .start
 7296            .to_display_point(editor_snapshot);
 7297        let edit_end = edits
 7298            .last()
 7299            .unwrap()
 7300            .0
 7301            .end
 7302            .to_display_point(editor_snapshot);
 7303
 7304        let is_visible = visible_row_range.contains(&edit_start.row())
 7305            || visible_row_range.contains(&edit_end.row());
 7306        if !is_visible {
 7307            return None;
 7308        }
 7309
 7310        let highlighted_edits =
 7311            crate::inline_completion_edit_text(&snapshot, edits, edit_preview.as_ref()?, false, cx);
 7312
 7313        let styled_text = highlighted_edits.to_styled_text(&style.text);
 7314        let line_count = highlighted_edits.text.lines().count();
 7315
 7316        const BORDER_WIDTH: Pixels = px(1.);
 7317
 7318        let keybind = self.render_edit_prediction_accept_keybind(window, cx);
 7319        let has_keybind = keybind.is_some();
 7320
 7321        let mut element = h_flex()
 7322            .items_start()
 7323            .child(
 7324                h_flex()
 7325                    .bg(cx.theme().colors().editor_background)
 7326                    .border(BORDER_WIDTH)
 7327                    .shadow_sm()
 7328                    .border_color(cx.theme().colors().border)
 7329                    .rounded_l_lg()
 7330                    .when(line_count > 1, |el| el.rounded_br_lg())
 7331                    .pr_1()
 7332                    .child(styled_text),
 7333            )
 7334            .child(
 7335                h_flex()
 7336                    .h(line_height + BORDER_WIDTH * 2.)
 7337                    .px_1p5()
 7338                    .gap_1()
 7339                    // Workaround: For some reason, there's a gap if we don't do this
 7340                    .ml(-BORDER_WIDTH)
 7341                    .shadow(smallvec![gpui::BoxShadow {
 7342                        color: gpui::black().opacity(0.05),
 7343                        offset: point(px(1.), px(1.)),
 7344                        blur_radius: px(2.),
 7345                        spread_radius: px(0.),
 7346                    }])
 7347                    .bg(Editor::edit_prediction_line_popover_bg_color(cx))
 7348                    .border(BORDER_WIDTH)
 7349                    .border_color(cx.theme().colors().border)
 7350                    .rounded_r_lg()
 7351                    .id("edit_prediction_diff_popover_keybind")
 7352                    .when(!has_keybind, |el| {
 7353                        let status_colors = cx.theme().status();
 7354
 7355                        el.bg(status_colors.error_background)
 7356                            .border_color(status_colors.error.opacity(0.6))
 7357                            .child(Icon::new(IconName::Info).color(Color::Error))
 7358                            .cursor_default()
 7359                            .hoverable_tooltip(move |_window, cx| {
 7360                                cx.new(|_| MissingEditPredictionKeybindingTooltip).into()
 7361                            })
 7362                    })
 7363                    .children(keybind),
 7364            )
 7365            .into_any();
 7366
 7367        let longest_row =
 7368            editor_snapshot.longest_row_in_range(edit_start.row()..edit_end.row() + 1);
 7369        let longest_line_width = if visible_row_range.contains(&longest_row) {
 7370            line_layouts[(longest_row.0 - visible_row_range.start.0) as usize].width
 7371        } else {
 7372            layout_line(
 7373                longest_row,
 7374                editor_snapshot,
 7375                style,
 7376                editor_width,
 7377                |_| false,
 7378                window,
 7379                cx,
 7380            )
 7381            .width
 7382        };
 7383
 7384        let viewport_bounds =
 7385            Bounds::new(Default::default(), window.viewport_size()).extend(Edges {
 7386                right: -EditorElement::SCROLLBAR_WIDTH,
 7387                ..Default::default()
 7388            });
 7389
 7390        let x_after_longest =
 7391            text_bounds.origin.x + longest_line_width + Self::EDIT_PREDICTION_POPOVER_PADDING_X
 7392                - scroll_pixel_position.x;
 7393
 7394        let element_bounds = element.layout_as_root(AvailableSpace::min_size(), window, cx);
 7395
 7396        // Fully visible if it can be displayed within the window (allow overlapping other
 7397        // panes). However, this is only allowed if the popover starts within text_bounds.
 7398        let can_position_to_the_right = x_after_longest < text_bounds.right()
 7399            && x_after_longest + element_bounds.width < viewport_bounds.right();
 7400
 7401        let mut origin = if can_position_to_the_right {
 7402            point(
 7403                x_after_longest,
 7404                text_bounds.origin.y + edit_start.row().as_f32() * line_height
 7405                    - scroll_pixel_position.y,
 7406            )
 7407        } else {
 7408            let cursor_row = newest_selection_head.map(|head| head.row());
 7409            let above_edit = edit_start
 7410                .row()
 7411                .0
 7412                .checked_sub(line_count as u32)
 7413                .map(DisplayRow);
 7414            let below_edit = Some(edit_end.row() + 1);
 7415            let above_cursor =
 7416                cursor_row.and_then(|row| row.0.checked_sub(line_count as u32).map(DisplayRow));
 7417            let below_cursor = cursor_row.map(|cursor_row| cursor_row + 1);
 7418
 7419            // Place the edit popover adjacent to the edit if there is a location
 7420            // available that is onscreen and does not obscure the cursor. Otherwise,
 7421            // place it adjacent to the cursor.
 7422            let row_target = [above_edit, below_edit, above_cursor, below_cursor]
 7423                .into_iter()
 7424                .flatten()
 7425                .find(|&start_row| {
 7426                    let end_row = start_row + line_count as u32;
 7427                    visible_row_range.contains(&start_row)
 7428                        && visible_row_range.contains(&end_row)
 7429                        && cursor_row.map_or(true, |cursor_row| {
 7430                            !((start_row..end_row).contains(&cursor_row))
 7431                        })
 7432                })?;
 7433
 7434            content_origin
 7435                + point(
 7436                    -scroll_pixel_position.x,
 7437                    row_target.as_f32() * line_height - scroll_pixel_position.y,
 7438                )
 7439        };
 7440
 7441        origin.x -= BORDER_WIDTH;
 7442
 7443        window.defer_draw(element, origin, 1);
 7444
 7445        // Do not return an element, since it will already be drawn due to defer_draw.
 7446        None
 7447    }
 7448
 7449    fn edit_prediction_cursor_popover_height(&self) -> Pixels {
 7450        px(30.)
 7451    }
 7452
 7453    fn current_user_player_color(&self, cx: &mut App) -> PlayerColor {
 7454        if self.read_only(cx) {
 7455            cx.theme().players().read_only()
 7456        } else {
 7457            self.style.as_ref().unwrap().local_player
 7458        }
 7459    }
 7460
 7461    fn render_edit_prediction_accept_keybind(
 7462        &self,
 7463        window: &mut Window,
 7464        cx: &App,
 7465    ) -> Option<AnyElement> {
 7466        let accept_binding = self.accept_edit_prediction_keybind(window, cx);
 7467        let accept_keystroke = accept_binding.keystroke()?;
 7468
 7469        let is_platform_style_mac = PlatformStyle::platform() == PlatformStyle::Mac;
 7470
 7471        let modifiers_color = if accept_keystroke.modifiers == window.modifiers() {
 7472            Color::Accent
 7473        } else {
 7474            Color::Muted
 7475        };
 7476
 7477        h_flex()
 7478            .px_0p5()
 7479            .when(is_platform_style_mac, |parent| parent.gap_0p5())
 7480            .font(theme::ThemeSettings::get_global(cx).buffer_font.clone())
 7481            .text_size(TextSize::XSmall.rems(cx))
 7482            .child(h_flex().children(ui::render_modifiers(
 7483                &accept_keystroke.modifiers,
 7484                PlatformStyle::platform(),
 7485                Some(modifiers_color),
 7486                Some(IconSize::XSmall.rems().into()),
 7487                true,
 7488            )))
 7489            .when(is_platform_style_mac, |parent| {
 7490                parent.child(accept_keystroke.key.clone())
 7491            })
 7492            .when(!is_platform_style_mac, |parent| {
 7493                parent.child(
 7494                    Key::new(
 7495                        util::capitalize(&accept_keystroke.key),
 7496                        Some(Color::Default),
 7497                    )
 7498                    .size(Some(IconSize::XSmall.rems().into())),
 7499                )
 7500            })
 7501            .into_any()
 7502            .into()
 7503    }
 7504
 7505    fn render_edit_prediction_line_popover(
 7506        &self,
 7507        label: impl Into<SharedString>,
 7508        icon: Option<IconName>,
 7509        window: &mut Window,
 7510        cx: &App,
 7511    ) -> Option<Stateful<Div>> {
 7512        let padding_right = if icon.is_some() { px(4.) } else { px(8.) };
 7513
 7514        let keybind = self.render_edit_prediction_accept_keybind(window, cx);
 7515        let has_keybind = keybind.is_some();
 7516
 7517        let result = h_flex()
 7518            .id("ep-line-popover")
 7519            .py_0p5()
 7520            .pl_1()
 7521            .pr(padding_right)
 7522            .gap_1()
 7523            .rounded_md()
 7524            .border_1()
 7525            .bg(Self::edit_prediction_line_popover_bg_color(cx))
 7526            .border_color(Self::edit_prediction_callout_popover_border_color(cx))
 7527            .shadow_sm()
 7528            .when(!has_keybind, |el| {
 7529                let status_colors = cx.theme().status();
 7530
 7531                el.bg(status_colors.error_background)
 7532                    .border_color(status_colors.error.opacity(0.6))
 7533                    .pl_2()
 7534                    .child(Icon::new(IconName::ZedPredictError).color(Color::Error))
 7535                    .cursor_default()
 7536                    .hoverable_tooltip(move |_window, cx| {
 7537                        cx.new(|_| MissingEditPredictionKeybindingTooltip).into()
 7538                    })
 7539            })
 7540            .children(keybind)
 7541            .child(
 7542                Label::new(label)
 7543                    .size(LabelSize::Small)
 7544                    .when(!has_keybind, |el| {
 7545                        el.color(cx.theme().status().error.into()).strikethrough()
 7546                    }),
 7547            )
 7548            .when(!has_keybind, |el| {
 7549                el.child(
 7550                    h_flex().ml_1().child(
 7551                        Icon::new(IconName::Info)
 7552                            .size(IconSize::Small)
 7553                            .color(cx.theme().status().error.into()),
 7554                    ),
 7555                )
 7556            })
 7557            .when_some(icon, |element, icon| {
 7558                element.child(
 7559                    div()
 7560                        .mt(px(1.5))
 7561                        .child(Icon::new(icon).size(IconSize::Small)),
 7562                )
 7563            });
 7564
 7565        Some(result)
 7566    }
 7567
 7568    fn edit_prediction_line_popover_bg_color(cx: &App) -> Hsla {
 7569        let accent_color = cx.theme().colors().text_accent;
 7570        let editor_bg_color = cx.theme().colors().editor_background;
 7571        editor_bg_color.blend(accent_color.opacity(0.1))
 7572    }
 7573
 7574    fn edit_prediction_callout_popover_border_color(cx: &App) -> Hsla {
 7575        let accent_color = cx.theme().colors().text_accent;
 7576        let editor_bg_color = cx.theme().colors().editor_background;
 7577        editor_bg_color.blend(accent_color.opacity(0.6))
 7578    }
 7579
 7580    fn render_edit_prediction_cursor_popover(
 7581        &self,
 7582        min_width: Pixels,
 7583        max_width: Pixels,
 7584        cursor_point: Point,
 7585        style: &EditorStyle,
 7586        accept_keystroke: Option<&gpui::Keystroke>,
 7587        _window: &Window,
 7588        cx: &mut Context<Editor>,
 7589    ) -> Option<AnyElement> {
 7590        let provider = self.edit_prediction_provider.as_ref()?;
 7591
 7592        if provider.provider.needs_terms_acceptance(cx) {
 7593            return Some(
 7594                h_flex()
 7595                    .min_w(min_width)
 7596                    .flex_1()
 7597                    .px_2()
 7598                    .py_1()
 7599                    .gap_3()
 7600                    .elevation_2(cx)
 7601                    .hover(|style| style.bg(cx.theme().colors().element_hover))
 7602                    .id("accept-terms")
 7603                    .cursor_pointer()
 7604                    .on_mouse_down(MouseButton::Left, |_, window, _| window.prevent_default())
 7605                    .on_click(cx.listener(|this, _event, window, cx| {
 7606                        cx.stop_propagation();
 7607                        this.report_editor_event("Edit Prediction Provider ToS Clicked", None, cx);
 7608                        window.dispatch_action(
 7609                            zed_actions::OpenZedPredictOnboarding.boxed_clone(),
 7610                            cx,
 7611                        );
 7612                    }))
 7613                    .child(
 7614                        h_flex()
 7615                            .flex_1()
 7616                            .gap_2()
 7617                            .child(Icon::new(IconName::ZedPredict))
 7618                            .child(Label::new("Accept Terms of Service"))
 7619                            .child(div().w_full())
 7620                            .child(
 7621                                Icon::new(IconName::ArrowUpRight)
 7622                                    .color(Color::Muted)
 7623                                    .size(IconSize::Small),
 7624                            )
 7625                            .into_any_element(),
 7626                    )
 7627                    .into_any(),
 7628            );
 7629        }
 7630
 7631        let is_refreshing = provider.provider.is_refreshing(cx);
 7632
 7633        fn pending_completion_container() -> Div {
 7634            h_flex()
 7635                .h_full()
 7636                .flex_1()
 7637                .gap_2()
 7638                .child(Icon::new(IconName::ZedPredict))
 7639        }
 7640
 7641        let completion = match &self.active_inline_completion {
 7642            Some(prediction) => {
 7643                if !self.has_visible_completions_menu() {
 7644                    const RADIUS: Pixels = px(6.);
 7645                    const BORDER_WIDTH: Pixels = px(1.);
 7646
 7647                    return Some(
 7648                        h_flex()
 7649                            .elevation_2(cx)
 7650                            .border(BORDER_WIDTH)
 7651                            .border_color(cx.theme().colors().border)
 7652                            .when(accept_keystroke.is_none(), |el| {
 7653                                el.border_color(cx.theme().status().error)
 7654                            })
 7655                            .rounded(RADIUS)
 7656                            .rounded_tl(px(0.))
 7657                            .overflow_hidden()
 7658                            .child(div().px_1p5().child(match &prediction.completion {
 7659                                InlineCompletion::Move { target, snapshot } => {
 7660                                    use text::ToPoint as _;
 7661                                    if target.text_anchor.to_point(&snapshot).row > cursor_point.row
 7662                                    {
 7663                                        Icon::new(IconName::ZedPredictDown)
 7664                                    } else {
 7665                                        Icon::new(IconName::ZedPredictUp)
 7666                                    }
 7667                                }
 7668                                InlineCompletion::Edit { .. } => Icon::new(IconName::ZedPredict),
 7669                            }))
 7670                            .child(
 7671                                h_flex()
 7672                                    .gap_1()
 7673                                    .py_1()
 7674                                    .px_2()
 7675                                    .rounded_r(RADIUS - BORDER_WIDTH)
 7676                                    .border_l_1()
 7677                                    .border_color(cx.theme().colors().border)
 7678                                    .bg(Self::edit_prediction_line_popover_bg_color(cx))
 7679                                    .when(self.edit_prediction_preview.released_too_fast(), |el| {
 7680                                        el.child(
 7681                                            Label::new("Hold")
 7682                                                .size(LabelSize::Small)
 7683                                                .when(accept_keystroke.is_none(), |el| {
 7684                                                    el.strikethrough()
 7685                                                })
 7686                                                .line_height_style(LineHeightStyle::UiLabel),
 7687                                        )
 7688                                    })
 7689                                    .id("edit_prediction_cursor_popover_keybind")
 7690                                    .when(accept_keystroke.is_none(), |el| {
 7691                                        let status_colors = cx.theme().status();
 7692
 7693                                        el.bg(status_colors.error_background)
 7694                                            .border_color(status_colors.error.opacity(0.6))
 7695                                            .child(Icon::new(IconName::Info).color(Color::Error))
 7696                                            .cursor_default()
 7697                                            .hoverable_tooltip(move |_window, cx| {
 7698                                                cx.new(|_| MissingEditPredictionKeybindingTooltip)
 7699                                                    .into()
 7700                                            })
 7701                                    })
 7702                                    .when_some(
 7703                                        accept_keystroke.as_ref(),
 7704                                        |el, accept_keystroke| {
 7705                                            el.child(h_flex().children(ui::render_modifiers(
 7706                                                &accept_keystroke.modifiers,
 7707                                                PlatformStyle::platform(),
 7708                                                Some(Color::Default),
 7709                                                Some(IconSize::XSmall.rems().into()),
 7710                                                false,
 7711                                            )))
 7712                                        },
 7713                                    ),
 7714                            )
 7715                            .into_any(),
 7716                    );
 7717                }
 7718
 7719                self.render_edit_prediction_cursor_popover_preview(
 7720                    prediction,
 7721                    cursor_point,
 7722                    style,
 7723                    cx,
 7724                )?
 7725            }
 7726
 7727            None if is_refreshing => match &self.stale_inline_completion_in_menu {
 7728                Some(stale_completion) => self.render_edit_prediction_cursor_popover_preview(
 7729                    stale_completion,
 7730                    cursor_point,
 7731                    style,
 7732                    cx,
 7733                )?,
 7734
 7735                None => {
 7736                    pending_completion_container().child(Label::new("...").size(LabelSize::Small))
 7737                }
 7738            },
 7739
 7740            None => pending_completion_container().child(Label::new("No Prediction")),
 7741        };
 7742
 7743        let completion = if is_refreshing {
 7744            completion
 7745                .with_animation(
 7746                    "loading-completion",
 7747                    Animation::new(Duration::from_secs(2))
 7748                        .repeat()
 7749                        .with_easing(pulsating_between(0.4, 0.8)),
 7750                    |label, delta| label.opacity(delta),
 7751                )
 7752                .into_any_element()
 7753        } else {
 7754            completion.into_any_element()
 7755        };
 7756
 7757        let has_completion = self.active_inline_completion.is_some();
 7758
 7759        let is_platform_style_mac = PlatformStyle::platform() == PlatformStyle::Mac;
 7760        Some(
 7761            h_flex()
 7762                .min_w(min_width)
 7763                .max_w(max_width)
 7764                .flex_1()
 7765                .elevation_2(cx)
 7766                .border_color(cx.theme().colors().border)
 7767                .child(
 7768                    div()
 7769                        .flex_1()
 7770                        .py_1()
 7771                        .px_2()
 7772                        .overflow_hidden()
 7773                        .child(completion),
 7774                )
 7775                .when_some(accept_keystroke, |el, accept_keystroke| {
 7776                    if !accept_keystroke.modifiers.modified() {
 7777                        return el;
 7778                    }
 7779
 7780                    el.child(
 7781                        h_flex()
 7782                            .h_full()
 7783                            .border_l_1()
 7784                            .rounded_r_lg()
 7785                            .border_color(cx.theme().colors().border)
 7786                            .bg(Self::edit_prediction_line_popover_bg_color(cx))
 7787                            .gap_1()
 7788                            .py_1()
 7789                            .px_2()
 7790                            .child(
 7791                                h_flex()
 7792                                    .font(theme::ThemeSettings::get_global(cx).buffer_font.clone())
 7793                                    .when(is_platform_style_mac, |parent| parent.gap_1())
 7794                                    .child(h_flex().children(ui::render_modifiers(
 7795                                        &accept_keystroke.modifiers,
 7796                                        PlatformStyle::platform(),
 7797                                        Some(if !has_completion {
 7798                                            Color::Muted
 7799                                        } else {
 7800                                            Color::Default
 7801                                        }),
 7802                                        None,
 7803                                        false,
 7804                                    ))),
 7805                            )
 7806                            .child(Label::new("Preview").into_any_element())
 7807                            .opacity(if has_completion { 1.0 } else { 0.4 }),
 7808                    )
 7809                })
 7810                .into_any(),
 7811        )
 7812    }
 7813
 7814    fn render_edit_prediction_cursor_popover_preview(
 7815        &self,
 7816        completion: &InlineCompletionState,
 7817        cursor_point: Point,
 7818        style: &EditorStyle,
 7819        cx: &mut Context<Editor>,
 7820    ) -> Option<Div> {
 7821        use text::ToPoint as _;
 7822
 7823        fn render_relative_row_jump(
 7824            prefix: impl Into<String>,
 7825            current_row: u32,
 7826            target_row: u32,
 7827        ) -> Div {
 7828            let (row_diff, arrow) = if target_row < current_row {
 7829                (current_row - target_row, IconName::ArrowUp)
 7830            } else {
 7831                (target_row - current_row, IconName::ArrowDown)
 7832            };
 7833
 7834            h_flex()
 7835                .child(
 7836                    Label::new(format!("{}{}", prefix.into(), row_diff))
 7837                        .color(Color::Muted)
 7838                        .size(LabelSize::Small),
 7839                )
 7840                .child(Icon::new(arrow).color(Color::Muted).size(IconSize::Small))
 7841        }
 7842
 7843        match &completion.completion {
 7844            InlineCompletion::Move {
 7845                target, snapshot, ..
 7846            } => Some(
 7847                h_flex()
 7848                    .px_2()
 7849                    .gap_2()
 7850                    .flex_1()
 7851                    .child(
 7852                        if target.text_anchor.to_point(&snapshot).row > cursor_point.row {
 7853                            Icon::new(IconName::ZedPredictDown)
 7854                        } else {
 7855                            Icon::new(IconName::ZedPredictUp)
 7856                        },
 7857                    )
 7858                    .child(Label::new("Jump to Edit")),
 7859            ),
 7860
 7861            InlineCompletion::Edit {
 7862                edits,
 7863                edit_preview,
 7864                snapshot,
 7865                display_mode: _,
 7866            } => {
 7867                let first_edit_row = edits.first()?.0.start.text_anchor.to_point(&snapshot).row;
 7868
 7869                let (highlighted_edits, has_more_lines) = crate::inline_completion_edit_text(
 7870                    &snapshot,
 7871                    &edits,
 7872                    edit_preview.as_ref()?,
 7873                    true,
 7874                    cx,
 7875                )
 7876                .first_line_preview();
 7877
 7878                let styled_text = gpui::StyledText::new(highlighted_edits.text)
 7879                    .with_default_highlights(&style.text, highlighted_edits.highlights);
 7880
 7881                let preview = h_flex()
 7882                    .gap_1()
 7883                    .min_w_16()
 7884                    .child(styled_text)
 7885                    .when(has_more_lines, |parent| parent.child(""));
 7886
 7887                let left = if first_edit_row != cursor_point.row {
 7888                    render_relative_row_jump("", cursor_point.row, first_edit_row)
 7889                        .into_any_element()
 7890                } else {
 7891                    Icon::new(IconName::ZedPredict).into_any_element()
 7892                };
 7893
 7894                Some(
 7895                    h_flex()
 7896                        .h_full()
 7897                        .flex_1()
 7898                        .gap_2()
 7899                        .pr_1()
 7900                        .overflow_x_hidden()
 7901                        .font(theme::ThemeSettings::get_global(cx).buffer_font.clone())
 7902                        .child(left)
 7903                        .child(preview),
 7904                )
 7905            }
 7906        }
 7907    }
 7908
 7909    fn render_context_menu(
 7910        &self,
 7911        style: &EditorStyle,
 7912        max_height_in_lines: u32,
 7913        window: &mut Window,
 7914        cx: &mut Context<Editor>,
 7915    ) -> Option<AnyElement> {
 7916        let menu = self.context_menu.borrow();
 7917        let menu = menu.as_ref()?;
 7918        if !menu.visible() {
 7919            return None;
 7920        };
 7921        Some(menu.render(style, max_height_in_lines, window, cx))
 7922    }
 7923
 7924    fn render_context_menu_aside(
 7925        &mut self,
 7926        max_size: Size<Pixels>,
 7927        window: &mut Window,
 7928        cx: &mut Context<Editor>,
 7929    ) -> Option<AnyElement> {
 7930        self.context_menu.borrow_mut().as_mut().and_then(|menu| {
 7931            if menu.visible() {
 7932                menu.render_aside(self, max_size, window, cx)
 7933            } else {
 7934                None
 7935            }
 7936        })
 7937    }
 7938
 7939    fn hide_context_menu(
 7940        &mut self,
 7941        window: &mut Window,
 7942        cx: &mut Context<Self>,
 7943    ) -> Option<CodeContextMenu> {
 7944        cx.notify();
 7945        self.completion_tasks.clear();
 7946        let context_menu = self.context_menu.borrow_mut().take();
 7947        self.stale_inline_completion_in_menu.take();
 7948        self.update_visible_inline_completion(window, cx);
 7949        context_menu
 7950    }
 7951
 7952    fn show_snippet_choices(
 7953        &mut self,
 7954        choices: &Vec<String>,
 7955        selection: Range<Anchor>,
 7956        cx: &mut Context<Self>,
 7957    ) {
 7958        if selection.start.buffer_id.is_none() {
 7959            return;
 7960        }
 7961        let buffer_id = selection.start.buffer_id.unwrap();
 7962        let buffer = self.buffer().read(cx).buffer(buffer_id);
 7963        let id = post_inc(&mut self.next_completion_id);
 7964
 7965        if let Some(buffer) = buffer {
 7966            *self.context_menu.borrow_mut() = Some(CodeContextMenu::Completions(
 7967                CompletionsMenu::new_snippet_choices(id, true, choices, selection, buffer),
 7968            ));
 7969        }
 7970    }
 7971
 7972    pub fn insert_snippet(
 7973        &mut self,
 7974        insertion_ranges: &[Range<usize>],
 7975        snippet: Snippet,
 7976        window: &mut Window,
 7977        cx: &mut Context<Self>,
 7978    ) -> Result<()> {
 7979        struct Tabstop<T> {
 7980            is_end_tabstop: bool,
 7981            ranges: Vec<Range<T>>,
 7982            choices: Option<Vec<String>>,
 7983        }
 7984
 7985        let tabstops = self.buffer.update(cx, |buffer, cx| {
 7986            let snippet_text: Arc<str> = snippet.text.clone().into();
 7987            let edits = insertion_ranges
 7988                .iter()
 7989                .cloned()
 7990                .map(|range| (range, snippet_text.clone()));
 7991            buffer.edit(edits, Some(AutoindentMode::EachLine), cx);
 7992
 7993            let snapshot = &*buffer.read(cx);
 7994            let snippet = &snippet;
 7995            snippet
 7996                .tabstops
 7997                .iter()
 7998                .map(|tabstop| {
 7999                    let is_end_tabstop = tabstop.ranges.first().map_or(false, |tabstop| {
 8000                        tabstop.is_empty() && tabstop.start == snippet.text.len() as isize
 8001                    });
 8002                    let mut tabstop_ranges = tabstop
 8003                        .ranges
 8004                        .iter()
 8005                        .flat_map(|tabstop_range| {
 8006                            let mut delta = 0_isize;
 8007                            insertion_ranges.iter().map(move |insertion_range| {
 8008                                let insertion_start = insertion_range.start as isize + delta;
 8009                                delta +=
 8010                                    snippet.text.len() as isize - insertion_range.len() as isize;
 8011
 8012                                let start = ((insertion_start + tabstop_range.start) as usize)
 8013                                    .min(snapshot.len());
 8014                                let end = ((insertion_start + tabstop_range.end) as usize)
 8015                                    .min(snapshot.len());
 8016                                snapshot.anchor_before(start)..snapshot.anchor_after(end)
 8017                            })
 8018                        })
 8019                        .collect::<Vec<_>>();
 8020                    tabstop_ranges.sort_unstable_by(|a, b| a.start.cmp(&b.start, snapshot));
 8021
 8022                    Tabstop {
 8023                        is_end_tabstop,
 8024                        ranges: tabstop_ranges,
 8025                        choices: tabstop.choices.clone(),
 8026                    }
 8027                })
 8028                .collect::<Vec<_>>()
 8029        });
 8030        if let Some(tabstop) = tabstops.first() {
 8031            self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8032                s.select_ranges(tabstop.ranges.iter().cloned());
 8033            });
 8034
 8035            if let Some(choices) = &tabstop.choices {
 8036                if let Some(selection) = tabstop.ranges.first() {
 8037                    self.show_snippet_choices(choices, selection.clone(), cx)
 8038                }
 8039            }
 8040
 8041            // If we're already at the last tabstop and it's at the end of the snippet,
 8042            // we're done, we don't need to keep the state around.
 8043            if !tabstop.is_end_tabstop {
 8044                let choices = tabstops
 8045                    .iter()
 8046                    .map(|tabstop| tabstop.choices.clone())
 8047                    .collect();
 8048
 8049                let ranges = tabstops
 8050                    .into_iter()
 8051                    .map(|tabstop| tabstop.ranges)
 8052                    .collect::<Vec<_>>();
 8053
 8054                self.snippet_stack.push(SnippetState {
 8055                    active_index: 0,
 8056                    ranges,
 8057                    choices,
 8058                });
 8059            }
 8060
 8061            // Check whether the just-entered snippet ends with an auto-closable bracket.
 8062            if self.autoclose_regions.is_empty() {
 8063                let snapshot = self.buffer.read(cx).snapshot(cx);
 8064                for selection in &mut self.selections.all::<Point>(cx) {
 8065                    let selection_head = selection.head();
 8066                    let Some(scope) = snapshot.language_scope_at(selection_head) else {
 8067                        continue;
 8068                    };
 8069
 8070                    let mut bracket_pair = None;
 8071                    let next_chars = snapshot.chars_at(selection_head).collect::<String>();
 8072                    let prev_chars = snapshot
 8073                        .reversed_chars_at(selection_head)
 8074                        .collect::<String>();
 8075                    for (pair, enabled) in scope.brackets() {
 8076                        if enabled
 8077                            && pair.close
 8078                            && prev_chars.starts_with(pair.start.as_str())
 8079                            && next_chars.starts_with(pair.end.as_str())
 8080                        {
 8081                            bracket_pair = Some(pair.clone());
 8082                            break;
 8083                        }
 8084                    }
 8085                    if let Some(pair) = bracket_pair {
 8086                        let snapshot_settings = snapshot.language_settings_at(selection_head, cx);
 8087                        let autoclose_enabled =
 8088                            self.use_autoclose && snapshot_settings.use_autoclose;
 8089                        if autoclose_enabled {
 8090                            let start = snapshot.anchor_after(selection_head);
 8091                            let end = snapshot.anchor_after(selection_head);
 8092                            self.autoclose_regions.push(AutocloseRegion {
 8093                                selection_id: selection.id,
 8094                                range: start..end,
 8095                                pair,
 8096                            });
 8097                        }
 8098                    }
 8099                }
 8100            }
 8101        }
 8102        Ok(())
 8103    }
 8104
 8105    pub fn move_to_next_snippet_tabstop(
 8106        &mut self,
 8107        window: &mut Window,
 8108        cx: &mut Context<Self>,
 8109    ) -> bool {
 8110        self.move_to_snippet_tabstop(Bias::Right, window, cx)
 8111    }
 8112
 8113    pub fn move_to_prev_snippet_tabstop(
 8114        &mut self,
 8115        window: &mut Window,
 8116        cx: &mut Context<Self>,
 8117    ) -> bool {
 8118        self.move_to_snippet_tabstop(Bias::Left, window, cx)
 8119    }
 8120
 8121    pub fn move_to_snippet_tabstop(
 8122        &mut self,
 8123        bias: Bias,
 8124        window: &mut Window,
 8125        cx: &mut Context<Self>,
 8126    ) -> bool {
 8127        if let Some(mut snippet) = self.snippet_stack.pop() {
 8128            match bias {
 8129                Bias::Left => {
 8130                    if snippet.active_index > 0 {
 8131                        snippet.active_index -= 1;
 8132                    } else {
 8133                        self.snippet_stack.push(snippet);
 8134                        return false;
 8135                    }
 8136                }
 8137                Bias::Right => {
 8138                    if snippet.active_index + 1 < snippet.ranges.len() {
 8139                        snippet.active_index += 1;
 8140                    } else {
 8141                        self.snippet_stack.push(snippet);
 8142                        return false;
 8143                    }
 8144                }
 8145            }
 8146            if let Some(current_ranges) = snippet.ranges.get(snippet.active_index) {
 8147                self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8148                    s.select_anchor_ranges(current_ranges.iter().cloned())
 8149                });
 8150
 8151                if let Some(choices) = &snippet.choices[snippet.active_index] {
 8152                    if let Some(selection) = current_ranges.first() {
 8153                        self.show_snippet_choices(&choices, selection.clone(), cx);
 8154                    }
 8155                }
 8156
 8157                // If snippet state is not at the last tabstop, push it back on the stack
 8158                if snippet.active_index + 1 < snippet.ranges.len() {
 8159                    self.snippet_stack.push(snippet);
 8160                }
 8161                return true;
 8162            }
 8163        }
 8164
 8165        false
 8166    }
 8167
 8168    pub fn clear(&mut self, window: &mut Window, cx: &mut Context<Self>) {
 8169        self.transact(window, cx, |this, window, cx| {
 8170            this.select_all(&SelectAll, window, cx);
 8171            this.insert("", window, cx);
 8172        });
 8173    }
 8174
 8175    pub fn backspace(&mut self, _: &Backspace, window: &mut Window, cx: &mut Context<Self>) {
 8176        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
 8177        self.transact(window, cx, |this, window, cx| {
 8178            this.select_autoclose_pair(window, cx);
 8179            let mut linked_ranges = HashMap::<_, Vec<_>>::default();
 8180            if !this.linked_edit_ranges.is_empty() {
 8181                let selections = this.selections.all::<MultiBufferPoint>(cx);
 8182                let snapshot = this.buffer.read(cx).snapshot(cx);
 8183
 8184                for selection in selections.iter() {
 8185                    let selection_start = snapshot.anchor_before(selection.start).text_anchor;
 8186                    let selection_end = snapshot.anchor_after(selection.end).text_anchor;
 8187                    if selection_start.buffer_id != selection_end.buffer_id {
 8188                        continue;
 8189                    }
 8190                    if let Some(ranges) =
 8191                        this.linked_editing_ranges_for(selection_start..selection_end, cx)
 8192                    {
 8193                        for (buffer, entries) in ranges {
 8194                            linked_ranges.entry(buffer).or_default().extend(entries);
 8195                        }
 8196                    }
 8197                }
 8198            }
 8199
 8200            let mut selections = this.selections.all::<MultiBufferPoint>(cx);
 8201            let display_map = this.display_map.update(cx, |map, cx| map.snapshot(cx));
 8202            for selection in &mut selections {
 8203                if selection.is_empty() {
 8204                    let old_head = selection.head();
 8205                    let mut new_head =
 8206                        movement::left(&display_map, old_head.to_display_point(&display_map))
 8207                            .to_point(&display_map);
 8208                    if let Some((buffer, line_buffer_range)) = display_map
 8209                        .buffer_snapshot
 8210                        .buffer_line_for_row(MultiBufferRow(old_head.row))
 8211                    {
 8212                        let indent_size = buffer.indent_size_for_line(line_buffer_range.start.row);
 8213                        let indent_len = match indent_size.kind {
 8214                            IndentKind::Space => {
 8215                                buffer.settings_at(line_buffer_range.start, cx).tab_size
 8216                            }
 8217                            IndentKind::Tab => NonZeroU32::new(1).unwrap(),
 8218                        };
 8219                        if old_head.column <= indent_size.len && old_head.column > 0 {
 8220                            let indent_len = indent_len.get();
 8221                            new_head = cmp::min(
 8222                                new_head,
 8223                                MultiBufferPoint::new(
 8224                                    old_head.row,
 8225                                    ((old_head.column - 1) / indent_len) * indent_len,
 8226                                ),
 8227                            );
 8228                        }
 8229                    }
 8230
 8231                    selection.set_head(new_head, SelectionGoal::None);
 8232                }
 8233            }
 8234
 8235            this.signature_help_state.set_backspace_pressed(true);
 8236            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8237                s.select(selections)
 8238            });
 8239            this.insert("", window, cx);
 8240            let empty_str: Arc<str> = Arc::from("");
 8241            for (buffer, edits) in linked_ranges {
 8242                let snapshot = buffer.read(cx).snapshot();
 8243                use text::ToPoint as TP;
 8244
 8245                let edits = edits
 8246                    .into_iter()
 8247                    .map(|range| {
 8248                        let end_point = TP::to_point(&range.end, &snapshot);
 8249                        let mut start_point = TP::to_point(&range.start, &snapshot);
 8250
 8251                        if end_point == start_point {
 8252                            let offset = text::ToOffset::to_offset(&range.start, &snapshot)
 8253                                .saturating_sub(1);
 8254                            start_point =
 8255                                snapshot.clip_point(TP::to_point(&offset, &snapshot), Bias::Left);
 8256                        };
 8257
 8258                        (start_point..end_point, empty_str.clone())
 8259                    })
 8260                    .sorted_by_key(|(range, _)| range.start)
 8261                    .collect::<Vec<_>>();
 8262                buffer.update(cx, |this, cx| {
 8263                    this.edit(edits, None, cx);
 8264                })
 8265            }
 8266            this.refresh_inline_completion(true, false, window, cx);
 8267            linked_editing_ranges::refresh_linked_ranges(this, window, cx);
 8268        });
 8269    }
 8270
 8271    pub fn delete(&mut self, _: &Delete, window: &mut Window, cx: &mut Context<Self>) {
 8272        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
 8273        self.transact(window, cx, |this, window, cx| {
 8274            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8275                s.move_with(|map, selection| {
 8276                    if selection.is_empty() {
 8277                        let cursor = movement::right(map, selection.head());
 8278                        selection.end = cursor;
 8279                        selection.reversed = true;
 8280                        selection.goal = SelectionGoal::None;
 8281                    }
 8282                })
 8283            });
 8284            this.insert("", window, cx);
 8285            this.refresh_inline_completion(true, false, window, cx);
 8286        });
 8287    }
 8288
 8289    pub fn backtab(&mut self, _: &Backtab, window: &mut Window, cx: &mut Context<Self>) {
 8290        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
 8291        if self.move_to_prev_snippet_tabstop(window, cx) {
 8292            return;
 8293        }
 8294        self.outdent(&Outdent, window, cx);
 8295    }
 8296
 8297    pub fn tab(&mut self, _: &Tab, window: &mut Window, cx: &mut Context<Self>) {
 8298        if self.move_to_next_snippet_tabstop(window, cx) {
 8299            self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
 8300            return;
 8301        }
 8302        if self.read_only(cx) {
 8303            return;
 8304        }
 8305        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
 8306        let mut selections = self.selections.all_adjusted(cx);
 8307        let buffer = self.buffer.read(cx);
 8308        let snapshot = buffer.snapshot(cx);
 8309        let rows_iter = selections.iter().map(|s| s.head().row);
 8310        let suggested_indents = snapshot.suggested_indents(rows_iter, cx);
 8311
 8312        let mut edits = Vec::new();
 8313        let mut prev_edited_row = 0;
 8314        let mut row_delta = 0;
 8315        for selection in &mut selections {
 8316            if selection.start.row != prev_edited_row {
 8317                row_delta = 0;
 8318            }
 8319            prev_edited_row = selection.end.row;
 8320
 8321            // If the selection is non-empty, then increase the indentation of the selected lines.
 8322            if !selection.is_empty() {
 8323                row_delta =
 8324                    Self::indent_selection(buffer, &snapshot, selection, &mut edits, row_delta, cx);
 8325                continue;
 8326            }
 8327
 8328            // If the selection is empty and the cursor is in the leading whitespace before the
 8329            // suggested indentation, then auto-indent the line.
 8330            let cursor = selection.head();
 8331            let current_indent = snapshot.indent_size_for_line(MultiBufferRow(cursor.row));
 8332            if let Some(suggested_indent) =
 8333                suggested_indents.get(&MultiBufferRow(cursor.row)).copied()
 8334            {
 8335                if cursor.column < suggested_indent.len
 8336                    && cursor.column <= current_indent.len
 8337                    && current_indent.len <= suggested_indent.len
 8338                {
 8339                    selection.start = Point::new(cursor.row, suggested_indent.len);
 8340                    selection.end = selection.start;
 8341                    if row_delta == 0 {
 8342                        edits.extend(Buffer::edit_for_indent_size_adjustment(
 8343                            cursor.row,
 8344                            current_indent,
 8345                            suggested_indent,
 8346                        ));
 8347                        row_delta = suggested_indent.len - current_indent.len;
 8348                    }
 8349                    continue;
 8350                }
 8351            }
 8352
 8353            // Otherwise, insert a hard or soft tab.
 8354            let settings = buffer.language_settings_at(cursor, cx);
 8355            let tab_size = if settings.hard_tabs {
 8356                IndentSize::tab()
 8357            } else {
 8358                let tab_size = settings.tab_size.get();
 8359                let indent_remainder = snapshot
 8360                    .text_for_range(Point::new(cursor.row, 0)..cursor)
 8361                    .flat_map(str::chars)
 8362                    .fold(row_delta % tab_size, |counter: u32, c| {
 8363                        if c == '\t' {
 8364                            0
 8365                        } else {
 8366                            (counter + 1) % tab_size
 8367                        }
 8368                    });
 8369
 8370                let chars_to_next_tab_stop = tab_size - indent_remainder;
 8371                IndentSize::spaces(chars_to_next_tab_stop)
 8372            };
 8373            selection.start = Point::new(cursor.row, cursor.column + row_delta + tab_size.len);
 8374            selection.end = selection.start;
 8375            edits.push((cursor..cursor, tab_size.chars().collect::<String>()));
 8376            row_delta += tab_size.len;
 8377        }
 8378
 8379        self.transact(window, cx, |this, window, cx| {
 8380            this.buffer.update(cx, |b, cx| b.edit(edits, None, cx));
 8381            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8382                s.select(selections)
 8383            });
 8384            this.refresh_inline_completion(true, false, window, cx);
 8385        });
 8386    }
 8387
 8388    pub fn indent(&mut self, _: &Indent, window: &mut Window, cx: &mut Context<Self>) {
 8389        if self.read_only(cx) {
 8390            return;
 8391        }
 8392        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
 8393        let mut selections = self.selections.all::<Point>(cx);
 8394        let mut prev_edited_row = 0;
 8395        let mut row_delta = 0;
 8396        let mut edits = Vec::new();
 8397        let buffer = self.buffer.read(cx);
 8398        let snapshot = buffer.snapshot(cx);
 8399        for selection in &mut selections {
 8400            if selection.start.row != prev_edited_row {
 8401                row_delta = 0;
 8402            }
 8403            prev_edited_row = selection.end.row;
 8404
 8405            row_delta =
 8406                Self::indent_selection(buffer, &snapshot, selection, &mut edits, row_delta, cx);
 8407        }
 8408
 8409        self.transact(window, cx, |this, window, cx| {
 8410            this.buffer.update(cx, |b, cx| b.edit(edits, None, cx));
 8411            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8412                s.select(selections)
 8413            });
 8414        });
 8415    }
 8416
 8417    fn indent_selection(
 8418        buffer: &MultiBuffer,
 8419        snapshot: &MultiBufferSnapshot,
 8420        selection: &mut Selection<Point>,
 8421        edits: &mut Vec<(Range<Point>, String)>,
 8422        delta_for_start_row: u32,
 8423        cx: &App,
 8424    ) -> u32 {
 8425        let settings = buffer.language_settings_at(selection.start, cx);
 8426        let tab_size = settings.tab_size.get();
 8427        let indent_kind = if settings.hard_tabs {
 8428            IndentKind::Tab
 8429        } else {
 8430            IndentKind::Space
 8431        };
 8432        let mut start_row = selection.start.row;
 8433        let mut end_row = selection.end.row + 1;
 8434
 8435        // If a selection ends at the beginning of a line, don't indent
 8436        // that last line.
 8437        if selection.end.column == 0 && selection.end.row > selection.start.row {
 8438            end_row -= 1;
 8439        }
 8440
 8441        // Avoid re-indenting a row that has already been indented by a
 8442        // previous selection, but still update this selection's column
 8443        // to reflect that indentation.
 8444        if delta_for_start_row > 0 {
 8445            start_row += 1;
 8446            selection.start.column += delta_for_start_row;
 8447            if selection.end.row == selection.start.row {
 8448                selection.end.column += delta_for_start_row;
 8449            }
 8450        }
 8451
 8452        let mut delta_for_end_row = 0;
 8453        let has_multiple_rows = start_row + 1 != end_row;
 8454        for row in start_row..end_row {
 8455            let current_indent = snapshot.indent_size_for_line(MultiBufferRow(row));
 8456            let indent_delta = match (current_indent.kind, indent_kind) {
 8457                (IndentKind::Space, IndentKind::Space) => {
 8458                    let columns_to_next_tab_stop = tab_size - (current_indent.len % tab_size);
 8459                    IndentSize::spaces(columns_to_next_tab_stop)
 8460                }
 8461                (IndentKind::Tab, IndentKind::Space) => IndentSize::spaces(tab_size),
 8462                (_, IndentKind::Tab) => IndentSize::tab(),
 8463            };
 8464
 8465            let start = if has_multiple_rows || current_indent.len < selection.start.column {
 8466                0
 8467            } else {
 8468                selection.start.column
 8469            };
 8470            let row_start = Point::new(row, start);
 8471            edits.push((
 8472                row_start..row_start,
 8473                indent_delta.chars().collect::<String>(),
 8474            ));
 8475
 8476            // Update this selection's endpoints to reflect the indentation.
 8477            if row == selection.start.row {
 8478                selection.start.column += indent_delta.len;
 8479            }
 8480            if row == selection.end.row {
 8481                selection.end.column += indent_delta.len;
 8482                delta_for_end_row = indent_delta.len;
 8483            }
 8484        }
 8485
 8486        if selection.start.row == selection.end.row {
 8487            delta_for_start_row + delta_for_end_row
 8488        } else {
 8489            delta_for_end_row
 8490        }
 8491    }
 8492
 8493    pub fn outdent(&mut self, _: &Outdent, window: &mut Window, cx: &mut Context<Self>) {
 8494        if self.read_only(cx) {
 8495            return;
 8496        }
 8497        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
 8498        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 8499        let selections = self.selections.all::<Point>(cx);
 8500        let mut deletion_ranges = Vec::new();
 8501        let mut last_outdent = None;
 8502        {
 8503            let buffer = self.buffer.read(cx);
 8504            let snapshot = buffer.snapshot(cx);
 8505            for selection in &selections {
 8506                let settings = buffer.language_settings_at(selection.start, cx);
 8507                let tab_size = settings.tab_size.get();
 8508                let mut rows = selection.spanned_rows(false, &display_map);
 8509
 8510                // Avoid re-outdenting a row that has already been outdented by a
 8511                // previous selection.
 8512                if let Some(last_row) = last_outdent {
 8513                    if last_row == rows.start {
 8514                        rows.start = rows.start.next_row();
 8515                    }
 8516                }
 8517                let has_multiple_rows = rows.len() > 1;
 8518                for row in rows.iter_rows() {
 8519                    let indent_size = snapshot.indent_size_for_line(row);
 8520                    if indent_size.len > 0 {
 8521                        let deletion_len = match indent_size.kind {
 8522                            IndentKind::Space => {
 8523                                let columns_to_prev_tab_stop = indent_size.len % tab_size;
 8524                                if columns_to_prev_tab_stop == 0 {
 8525                                    tab_size
 8526                                } else {
 8527                                    columns_to_prev_tab_stop
 8528                                }
 8529                            }
 8530                            IndentKind::Tab => 1,
 8531                        };
 8532                        let start = if has_multiple_rows
 8533                            || deletion_len > selection.start.column
 8534                            || indent_size.len < selection.start.column
 8535                        {
 8536                            0
 8537                        } else {
 8538                            selection.start.column - deletion_len
 8539                        };
 8540                        deletion_ranges.push(
 8541                            Point::new(row.0, start)..Point::new(row.0, start + deletion_len),
 8542                        );
 8543                        last_outdent = Some(row);
 8544                    }
 8545                }
 8546            }
 8547        }
 8548
 8549        self.transact(window, cx, |this, window, cx| {
 8550            this.buffer.update(cx, |buffer, cx| {
 8551                let empty_str: Arc<str> = Arc::default();
 8552                buffer.edit(
 8553                    deletion_ranges
 8554                        .into_iter()
 8555                        .map(|range| (range, empty_str.clone())),
 8556                    None,
 8557                    cx,
 8558                );
 8559            });
 8560            let selections = this.selections.all::<usize>(cx);
 8561            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8562                s.select(selections)
 8563            });
 8564        });
 8565    }
 8566
 8567    pub fn autoindent(&mut self, _: &AutoIndent, window: &mut Window, cx: &mut Context<Self>) {
 8568        if self.read_only(cx) {
 8569            return;
 8570        }
 8571        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
 8572        let selections = self
 8573            .selections
 8574            .all::<usize>(cx)
 8575            .into_iter()
 8576            .map(|s| s.range());
 8577
 8578        self.transact(window, cx, |this, window, cx| {
 8579            this.buffer.update(cx, |buffer, cx| {
 8580                buffer.autoindent_ranges(selections, cx);
 8581            });
 8582            let selections = this.selections.all::<usize>(cx);
 8583            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8584                s.select(selections)
 8585            });
 8586        });
 8587    }
 8588
 8589    pub fn delete_line(&mut self, _: &DeleteLine, window: &mut Window, cx: &mut Context<Self>) {
 8590        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
 8591        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 8592        let selections = self.selections.all::<Point>(cx);
 8593
 8594        let mut new_cursors = Vec::new();
 8595        let mut edit_ranges = Vec::new();
 8596        let mut selections = selections.iter().peekable();
 8597        while let Some(selection) = selections.next() {
 8598            let mut rows = selection.spanned_rows(false, &display_map);
 8599            let goal_display_column = selection.head().to_display_point(&display_map).column();
 8600
 8601            // Accumulate contiguous regions of rows that we want to delete.
 8602            while let Some(next_selection) = selections.peek() {
 8603                let next_rows = next_selection.spanned_rows(false, &display_map);
 8604                if next_rows.start <= rows.end {
 8605                    rows.end = next_rows.end;
 8606                    selections.next().unwrap();
 8607                } else {
 8608                    break;
 8609                }
 8610            }
 8611
 8612            let buffer = &display_map.buffer_snapshot;
 8613            let mut edit_start = Point::new(rows.start.0, 0).to_offset(buffer);
 8614            let edit_end;
 8615            let cursor_buffer_row;
 8616            if buffer.max_point().row >= rows.end.0 {
 8617                // If there's a line after the range, delete the \n from the end of the row range
 8618                // and position the cursor on the next line.
 8619                edit_end = Point::new(rows.end.0, 0).to_offset(buffer);
 8620                cursor_buffer_row = rows.end;
 8621            } else {
 8622                // If there isn't a line after the range, delete the \n from the line before the
 8623                // start of the row range and position the cursor there.
 8624                edit_start = edit_start.saturating_sub(1);
 8625                edit_end = buffer.len();
 8626                cursor_buffer_row = rows.start.previous_row();
 8627            }
 8628
 8629            let mut cursor = Point::new(cursor_buffer_row.0, 0).to_display_point(&display_map);
 8630            *cursor.column_mut() =
 8631                cmp::min(goal_display_column, display_map.line_len(cursor.row()));
 8632
 8633            new_cursors.push((
 8634                selection.id,
 8635                buffer.anchor_after(cursor.to_point(&display_map)),
 8636            ));
 8637            edit_ranges.push(edit_start..edit_end);
 8638        }
 8639
 8640        self.transact(window, cx, |this, window, cx| {
 8641            let buffer = this.buffer.update(cx, |buffer, cx| {
 8642                let empty_str: Arc<str> = Arc::default();
 8643                buffer.edit(
 8644                    edit_ranges
 8645                        .into_iter()
 8646                        .map(|range| (range, empty_str.clone())),
 8647                    None,
 8648                    cx,
 8649                );
 8650                buffer.snapshot(cx)
 8651            });
 8652            let new_selections = new_cursors
 8653                .into_iter()
 8654                .map(|(id, cursor)| {
 8655                    let cursor = cursor.to_point(&buffer);
 8656                    Selection {
 8657                        id,
 8658                        start: cursor,
 8659                        end: cursor,
 8660                        reversed: false,
 8661                        goal: SelectionGoal::None,
 8662                    }
 8663                })
 8664                .collect();
 8665
 8666            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8667                s.select(new_selections);
 8668            });
 8669        });
 8670    }
 8671
 8672    pub fn join_lines_impl(
 8673        &mut self,
 8674        insert_whitespace: bool,
 8675        window: &mut Window,
 8676        cx: &mut Context<Self>,
 8677    ) {
 8678        if self.read_only(cx) {
 8679            return;
 8680        }
 8681        let mut row_ranges = Vec::<Range<MultiBufferRow>>::new();
 8682        for selection in self.selections.all::<Point>(cx) {
 8683            let start = MultiBufferRow(selection.start.row);
 8684            // Treat single line selections as if they include the next line. Otherwise this action
 8685            // would do nothing for single line selections individual cursors.
 8686            let end = if selection.start.row == selection.end.row {
 8687                MultiBufferRow(selection.start.row + 1)
 8688            } else {
 8689                MultiBufferRow(selection.end.row)
 8690            };
 8691
 8692            if let Some(last_row_range) = row_ranges.last_mut() {
 8693                if start <= last_row_range.end {
 8694                    last_row_range.end = end;
 8695                    continue;
 8696                }
 8697            }
 8698            row_ranges.push(start..end);
 8699        }
 8700
 8701        let snapshot = self.buffer.read(cx).snapshot(cx);
 8702        let mut cursor_positions = Vec::new();
 8703        for row_range in &row_ranges {
 8704            let anchor = snapshot.anchor_before(Point::new(
 8705                row_range.end.previous_row().0,
 8706                snapshot.line_len(row_range.end.previous_row()),
 8707            ));
 8708            cursor_positions.push(anchor..anchor);
 8709        }
 8710
 8711        self.transact(window, cx, |this, window, cx| {
 8712            for row_range in row_ranges.into_iter().rev() {
 8713                for row in row_range.iter_rows().rev() {
 8714                    let end_of_line = Point::new(row.0, snapshot.line_len(row));
 8715                    let next_line_row = row.next_row();
 8716                    let indent = snapshot.indent_size_for_line(next_line_row);
 8717                    let start_of_next_line = Point::new(next_line_row.0, indent.len);
 8718
 8719                    let replace =
 8720                        if snapshot.line_len(next_line_row) > indent.len && insert_whitespace {
 8721                            " "
 8722                        } else {
 8723                            ""
 8724                        };
 8725
 8726                    this.buffer.update(cx, |buffer, cx| {
 8727                        buffer.edit([(end_of_line..start_of_next_line, replace)], None, cx)
 8728                    });
 8729                }
 8730            }
 8731
 8732            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8733                s.select_anchor_ranges(cursor_positions)
 8734            });
 8735        });
 8736    }
 8737
 8738    pub fn join_lines(&mut self, _: &JoinLines, window: &mut Window, cx: &mut Context<Self>) {
 8739        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
 8740        self.join_lines_impl(true, window, cx);
 8741    }
 8742
 8743    pub fn sort_lines_case_sensitive(
 8744        &mut self,
 8745        _: &SortLinesCaseSensitive,
 8746        window: &mut Window,
 8747        cx: &mut Context<Self>,
 8748    ) {
 8749        self.manipulate_lines(window, cx, |lines| lines.sort())
 8750    }
 8751
 8752    pub fn sort_lines_case_insensitive(
 8753        &mut self,
 8754        _: &SortLinesCaseInsensitive,
 8755        window: &mut Window,
 8756        cx: &mut Context<Self>,
 8757    ) {
 8758        self.manipulate_lines(window, cx, |lines| {
 8759            lines.sort_by_key(|line| line.to_lowercase())
 8760        })
 8761    }
 8762
 8763    pub fn unique_lines_case_insensitive(
 8764        &mut self,
 8765        _: &UniqueLinesCaseInsensitive,
 8766        window: &mut Window,
 8767        cx: &mut Context<Self>,
 8768    ) {
 8769        self.manipulate_lines(window, cx, |lines| {
 8770            let mut seen = HashSet::default();
 8771            lines.retain(|line| seen.insert(line.to_lowercase()));
 8772        })
 8773    }
 8774
 8775    pub fn unique_lines_case_sensitive(
 8776        &mut self,
 8777        _: &UniqueLinesCaseSensitive,
 8778        window: &mut Window,
 8779        cx: &mut Context<Self>,
 8780    ) {
 8781        self.manipulate_lines(window, cx, |lines| {
 8782            let mut seen = HashSet::default();
 8783            lines.retain(|line| seen.insert(*line));
 8784        })
 8785    }
 8786
 8787    pub fn reload_file(&mut self, _: &ReloadFile, window: &mut Window, cx: &mut Context<Self>) {
 8788        let Some(project) = self.project.clone() else {
 8789            return;
 8790        };
 8791        self.reload(project, window, cx)
 8792            .detach_and_notify_err(window, cx);
 8793    }
 8794
 8795    pub fn restore_file(
 8796        &mut self,
 8797        _: &::git::RestoreFile,
 8798        window: &mut Window,
 8799        cx: &mut Context<Self>,
 8800    ) {
 8801        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
 8802        let mut buffer_ids = HashSet::default();
 8803        let snapshot = self.buffer().read(cx).snapshot(cx);
 8804        for selection in self.selections.all::<usize>(cx) {
 8805            buffer_ids.extend(snapshot.buffer_ids_for_range(selection.range()))
 8806        }
 8807
 8808        let buffer = self.buffer().read(cx);
 8809        let ranges = buffer_ids
 8810            .into_iter()
 8811            .flat_map(|buffer_id| buffer.excerpt_ranges_for_buffer(buffer_id, cx))
 8812            .collect::<Vec<_>>();
 8813
 8814        self.restore_hunks_in_ranges(ranges, window, cx);
 8815    }
 8816
 8817    pub fn git_restore(&mut self, _: &Restore, window: &mut Window, cx: &mut Context<Self>) {
 8818        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
 8819        let selections = self
 8820            .selections
 8821            .all(cx)
 8822            .into_iter()
 8823            .map(|s| s.range())
 8824            .collect();
 8825        self.restore_hunks_in_ranges(selections, window, cx);
 8826    }
 8827
 8828    pub fn restore_hunks_in_ranges(
 8829        &mut self,
 8830        ranges: Vec<Range<Point>>,
 8831        window: &mut Window,
 8832        cx: &mut Context<Editor>,
 8833    ) {
 8834        let mut revert_changes = HashMap::default();
 8835        let chunk_by = self
 8836            .snapshot(window, cx)
 8837            .hunks_for_ranges(ranges)
 8838            .into_iter()
 8839            .chunk_by(|hunk| hunk.buffer_id);
 8840        for (buffer_id, hunks) in &chunk_by {
 8841            let hunks = hunks.collect::<Vec<_>>();
 8842            for hunk in &hunks {
 8843                self.prepare_restore_change(&mut revert_changes, hunk, cx);
 8844            }
 8845            self.do_stage_or_unstage(false, buffer_id, hunks.into_iter(), cx);
 8846        }
 8847        drop(chunk_by);
 8848        if !revert_changes.is_empty() {
 8849            self.transact(window, cx, |editor, window, cx| {
 8850                editor.restore(revert_changes, window, cx);
 8851            });
 8852        }
 8853    }
 8854
 8855    pub fn open_active_item_in_terminal(
 8856        &mut self,
 8857        _: &OpenInTerminal,
 8858        window: &mut Window,
 8859        cx: &mut Context<Self>,
 8860    ) {
 8861        if let Some(working_directory) = self.active_excerpt(cx).and_then(|(_, buffer, _)| {
 8862            let project_path = buffer.read(cx).project_path(cx)?;
 8863            let project = self.project.as_ref()?.read(cx);
 8864            let entry = project.entry_for_path(&project_path, cx)?;
 8865            let parent = match &entry.canonical_path {
 8866                Some(canonical_path) => canonical_path.to_path_buf(),
 8867                None => project.absolute_path(&project_path, cx)?,
 8868            }
 8869            .parent()?
 8870            .to_path_buf();
 8871            Some(parent)
 8872        }) {
 8873            window.dispatch_action(OpenTerminal { working_directory }.boxed_clone(), cx);
 8874        }
 8875    }
 8876
 8877    fn set_breakpoint_context_menu(
 8878        &mut self,
 8879        display_row: DisplayRow,
 8880        position: Option<Anchor>,
 8881        clicked_point: gpui::Point<Pixels>,
 8882        window: &mut Window,
 8883        cx: &mut Context<Self>,
 8884    ) {
 8885        if !cx.has_flag::<Debugger>() {
 8886            return;
 8887        }
 8888        let source = self
 8889            .buffer
 8890            .read(cx)
 8891            .snapshot(cx)
 8892            .anchor_before(Point::new(display_row.0, 0u32));
 8893
 8894        let context_menu = self.breakpoint_context_menu(position.unwrap_or(source), window, cx);
 8895
 8896        self.mouse_context_menu = MouseContextMenu::pinned_to_editor(
 8897            self,
 8898            source,
 8899            clicked_point,
 8900            context_menu,
 8901            window,
 8902            cx,
 8903        );
 8904    }
 8905
 8906    fn add_edit_breakpoint_block(
 8907        &mut self,
 8908        anchor: Anchor,
 8909        breakpoint: &Breakpoint,
 8910        edit_action: BreakpointPromptEditAction,
 8911        window: &mut Window,
 8912        cx: &mut Context<Self>,
 8913    ) {
 8914        let weak_editor = cx.weak_entity();
 8915        let bp_prompt = cx.new(|cx| {
 8916            BreakpointPromptEditor::new(
 8917                weak_editor,
 8918                anchor,
 8919                breakpoint.clone(),
 8920                edit_action,
 8921                window,
 8922                cx,
 8923            )
 8924        });
 8925
 8926        let height = bp_prompt.update(cx, |this, cx| {
 8927            this.prompt
 8928                .update(cx, |prompt, cx| prompt.max_point(cx).row().0 + 1 + 2)
 8929        });
 8930        let cloned_prompt = bp_prompt.clone();
 8931        let blocks = vec![BlockProperties {
 8932            style: BlockStyle::Sticky,
 8933            placement: BlockPlacement::Above(anchor),
 8934            height: Some(height),
 8935            render: Arc::new(move |cx| {
 8936                *cloned_prompt.read(cx).gutter_dimensions.lock() = *cx.gutter_dimensions;
 8937                cloned_prompt.clone().into_any_element()
 8938            }),
 8939            priority: 0,
 8940        }];
 8941
 8942        let focus_handle = bp_prompt.focus_handle(cx);
 8943        window.focus(&focus_handle);
 8944
 8945        let block_ids = self.insert_blocks(blocks, None, cx);
 8946        bp_prompt.update(cx, |prompt, _| {
 8947            prompt.add_block_ids(block_ids);
 8948        });
 8949    }
 8950
 8951    pub(crate) fn breakpoint_at_row(
 8952        &self,
 8953        row: u32,
 8954        window: &mut Window,
 8955        cx: &mut Context<Self>,
 8956    ) -> Option<(Anchor, Breakpoint)> {
 8957        let snapshot = self.snapshot(window, cx);
 8958        let breakpoint_position = snapshot.buffer_snapshot.anchor_before(Point::new(row, 0));
 8959
 8960        self.breakpoint_at_anchor(breakpoint_position, &snapshot, cx)
 8961    }
 8962
 8963    pub(crate) fn breakpoint_at_anchor(
 8964        &self,
 8965        breakpoint_position: Anchor,
 8966        snapshot: &EditorSnapshot,
 8967        cx: &mut Context<Self>,
 8968    ) -> Option<(Anchor, Breakpoint)> {
 8969        let project = self.project.clone()?;
 8970
 8971        let buffer_id = breakpoint_position.buffer_id.or_else(|| {
 8972            snapshot
 8973                .buffer_snapshot
 8974                .buffer_id_for_excerpt(breakpoint_position.excerpt_id)
 8975        })?;
 8976
 8977        let enclosing_excerpt = breakpoint_position.excerpt_id;
 8978        let buffer = project.read_with(cx, |project, cx| project.buffer_for_id(buffer_id, cx))?;
 8979        let buffer_snapshot = buffer.read(cx).snapshot();
 8980
 8981        let row = buffer_snapshot
 8982            .summary_for_anchor::<text::PointUtf16>(&breakpoint_position.text_anchor)
 8983            .row;
 8984
 8985        let line_len = snapshot.buffer_snapshot.line_len(MultiBufferRow(row));
 8986        let anchor_end = snapshot
 8987            .buffer_snapshot
 8988            .anchor_after(Point::new(row, line_len));
 8989
 8990        let bp = self
 8991            .breakpoint_store
 8992            .as_ref()?
 8993            .read_with(cx, |breakpoint_store, cx| {
 8994                breakpoint_store
 8995                    .breakpoints(
 8996                        &buffer,
 8997                        Some(breakpoint_position.text_anchor..anchor_end.text_anchor),
 8998                        &buffer_snapshot,
 8999                        cx,
 9000                    )
 9001                    .next()
 9002                    .and_then(|(anchor, bp)| {
 9003                        let breakpoint_row = buffer_snapshot
 9004                            .summary_for_anchor::<text::PointUtf16>(anchor)
 9005                            .row;
 9006
 9007                        if breakpoint_row == row {
 9008                            snapshot
 9009                                .buffer_snapshot
 9010                                .anchor_in_excerpt(enclosing_excerpt, *anchor)
 9011                                .map(|anchor| (anchor, bp.clone()))
 9012                        } else {
 9013                            None
 9014                        }
 9015                    })
 9016            });
 9017        bp
 9018    }
 9019
 9020    pub fn edit_log_breakpoint(
 9021        &mut self,
 9022        _: &EditLogBreakpoint,
 9023        window: &mut Window,
 9024        cx: &mut Context<Self>,
 9025    ) {
 9026        for (anchor, breakpoint) in self.breakpoints_at_cursors(window, cx) {
 9027            let breakpoint = breakpoint.unwrap_or_else(|| Breakpoint {
 9028                message: None,
 9029                state: BreakpointState::Enabled,
 9030                condition: None,
 9031                hit_condition: None,
 9032            });
 9033
 9034            self.add_edit_breakpoint_block(
 9035                anchor,
 9036                &breakpoint,
 9037                BreakpointPromptEditAction::Log,
 9038                window,
 9039                cx,
 9040            );
 9041        }
 9042    }
 9043
 9044    fn breakpoints_at_cursors(
 9045        &self,
 9046        window: &mut Window,
 9047        cx: &mut Context<Self>,
 9048    ) -> Vec<(Anchor, Option<Breakpoint>)> {
 9049        let snapshot = self.snapshot(window, cx);
 9050        let cursors = self
 9051            .selections
 9052            .disjoint_anchors()
 9053            .into_iter()
 9054            .map(|selection| {
 9055                let cursor_position: Point = selection.head().to_point(&snapshot.buffer_snapshot);
 9056
 9057                let breakpoint_position = self
 9058                    .breakpoint_at_row(cursor_position.row, window, cx)
 9059                    .map(|bp| bp.0)
 9060                    .unwrap_or_else(|| {
 9061                        snapshot
 9062                            .display_snapshot
 9063                            .buffer_snapshot
 9064                            .anchor_after(Point::new(cursor_position.row, 0))
 9065                    });
 9066
 9067                let breakpoint = self
 9068                    .breakpoint_at_anchor(breakpoint_position, &snapshot, cx)
 9069                    .map(|(anchor, breakpoint)| (anchor, Some(breakpoint)));
 9070
 9071                breakpoint.unwrap_or_else(|| (breakpoint_position, None))
 9072            })
 9073            // 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.
 9074            .collect::<HashMap<Anchor, _>>();
 9075
 9076        cursors.into_iter().collect()
 9077    }
 9078
 9079    pub fn enable_breakpoint(
 9080        &mut self,
 9081        _: &crate::actions::EnableBreakpoint,
 9082        window: &mut Window,
 9083        cx: &mut Context<Self>,
 9084    ) {
 9085        for (anchor, breakpoint) in self.breakpoints_at_cursors(window, cx) {
 9086            let Some(breakpoint) = breakpoint.filter(|breakpoint| breakpoint.is_disabled()) else {
 9087                continue;
 9088            };
 9089            self.edit_breakpoint_at_anchor(
 9090                anchor,
 9091                breakpoint,
 9092                BreakpointEditAction::InvertState,
 9093                cx,
 9094            );
 9095        }
 9096    }
 9097
 9098    pub fn disable_breakpoint(
 9099        &mut self,
 9100        _: &crate::actions::DisableBreakpoint,
 9101        window: &mut Window,
 9102        cx: &mut Context<Self>,
 9103    ) {
 9104        for (anchor, breakpoint) in self.breakpoints_at_cursors(window, cx) {
 9105            let Some(breakpoint) = breakpoint.filter(|breakpoint| breakpoint.is_enabled()) else {
 9106                continue;
 9107            };
 9108            self.edit_breakpoint_at_anchor(
 9109                anchor,
 9110                breakpoint,
 9111                BreakpointEditAction::InvertState,
 9112                cx,
 9113            );
 9114        }
 9115    }
 9116
 9117    pub fn toggle_breakpoint(
 9118        &mut self,
 9119        _: &crate::actions::ToggleBreakpoint,
 9120        window: &mut Window,
 9121        cx: &mut Context<Self>,
 9122    ) {
 9123        for (anchor, breakpoint) in self.breakpoints_at_cursors(window, cx) {
 9124            if let Some(breakpoint) = breakpoint {
 9125                self.edit_breakpoint_at_anchor(
 9126                    anchor,
 9127                    breakpoint,
 9128                    BreakpointEditAction::Toggle,
 9129                    cx,
 9130                );
 9131            } else {
 9132                self.edit_breakpoint_at_anchor(
 9133                    anchor,
 9134                    Breakpoint::new_standard(),
 9135                    BreakpointEditAction::Toggle,
 9136                    cx,
 9137                );
 9138            }
 9139        }
 9140    }
 9141
 9142    pub fn edit_breakpoint_at_anchor(
 9143        &mut self,
 9144        breakpoint_position: Anchor,
 9145        breakpoint: Breakpoint,
 9146        edit_action: BreakpointEditAction,
 9147        cx: &mut Context<Self>,
 9148    ) {
 9149        let Some(breakpoint_store) = &self.breakpoint_store else {
 9150            return;
 9151        };
 9152
 9153        let Some(buffer_id) = breakpoint_position.buffer_id.or_else(|| {
 9154            if breakpoint_position == Anchor::min() {
 9155                self.buffer()
 9156                    .read(cx)
 9157                    .excerpt_buffer_ids()
 9158                    .into_iter()
 9159                    .next()
 9160            } else {
 9161                None
 9162            }
 9163        }) else {
 9164            return;
 9165        };
 9166
 9167        let Some(buffer) = self.buffer().read(cx).buffer(buffer_id) else {
 9168            return;
 9169        };
 9170
 9171        breakpoint_store.update(cx, |breakpoint_store, cx| {
 9172            breakpoint_store.toggle_breakpoint(
 9173                buffer,
 9174                (breakpoint_position.text_anchor, breakpoint),
 9175                edit_action,
 9176                cx,
 9177            );
 9178        });
 9179
 9180        cx.notify();
 9181    }
 9182
 9183    #[cfg(any(test, feature = "test-support"))]
 9184    pub fn breakpoint_store(&self) -> Option<Entity<BreakpointStore>> {
 9185        self.breakpoint_store.clone()
 9186    }
 9187
 9188    pub fn prepare_restore_change(
 9189        &self,
 9190        revert_changes: &mut HashMap<BufferId, Vec<(Range<text::Anchor>, Rope)>>,
 9191        hunk: &MultiBufferDiffHunk,
 9192        cx: &mut App,
 9193    ) -> Option<()> {
 9194        if hunk.is_created_file() {
 9195            return None;
 9196        }
 9197        let buffer = self.buffer.read(cx);
 9198        let diff = buffer.diff_for(hunk.buffer_id)?;
 9199        let buffer = buffer.buffer(hunk.buffer_id)?;
 9200        let buffer = buffer.read(cx);
 9201        let original_text = diff
 9202            .read(cx)
 9203            .base_text()
 9204            .as_rope()
 9205            .slice(hunk.diff_base_byte_range.clone());
 9206        let buffer_snapshot = buffer.snapshot();
 9207        let buffer_revert_changes = revert_changes.entry(buffer.remote_id()).or_default();
 9208        if let Err(i) = buffer_revert_changes.binary_search_by(|probe| {
 9209            probe
 9210                .0
 9211                .start
 9212                .cmp(&hunk.buffer_range.start, &buffer_snapshot)
 9213                .then(probe.0.end.cmp(&hunk.buffer_range.end, &buffer_snapshot))
 9214        }) {
 9215            buffer_revert_changes.insert(i, (hunk.buffer_range.clone(), original_text));
 9216            Some(())
 9217        } else {
 9218            None
 9219        }
 9220    }
 9221
 9222    pub fn reverse_lines(&mut self, _: &ReverseLines, window: &mut Window, cx: &mut Context<Self>) {
 9223        self.manipulate_lines(window, cx, |lines| lines.reverse())
 9224    }
 9225
 9226    pub fn shuffle_lines(&mut self, _: &ShuffleLines, window: &mut Window, cx: &mut Context<Self>) {
 9227        self.manipulate_lines(window, cx, |lines| lines.shuffle(&mut thread_rng()))
 9228    }
 9229
 9230    fn manipulate_lines<Fn>(
 9231        &mut self,
 9232        window: &mut Window,
 9233        cx: &mut Context<Self>,
 9234        mut callback: Fn,
 9235    ) where
 9236        Fn: FnMut(&mut Vec<&str>),
 9237    {
 9238        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
 9239
 9240        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 9241        let buffer = self.buffer.read(cx).snapshot(cx);
 9242
 9243        let mut edits = Vec::new();
 9244
 9245        let selections = self.selections.all::<Point>(cx);
 9246        let mut selections = selections.iter().peekable();
 9247        let mut contiguous_row_selections = Vec::new();
 9248        let mut new_selections = Vec::new();
 9249        let mut added_lines = 0;
 9250        let mut removed_lines = 0;
 9251
 9252        while let Some(selection) = selections.next() {
 9253            let (start_row, end_row) = consume_contiguous_rows(
 9254                &mut contiguous_row_selections,
 9255                selection,
 9256                &display_map,
 9257                &mut selections,
 9258            );
 9259
 9260            let start_point = Point::new(start_row.0, 0);
 9261            let end_point = Point::new(
 9262                end_row.previous_row().0,
 9263                buffer.line_len(end_row.previous_row()),
 9264            );
 9265            let text = buffer
 9266                .text_for_range(start_point..end_point)
 9267                .collect::<String>();
 9268
 9269            let mut lines = text.split('\n').collect_vec();
 9270
 9271            let lines_before = lines.len();
 9272            callback(&mut lines);
 9273            let lines_after = lines.len();
 9274
 9275            edits.push((start_point..end_point, lines.join("\n")));
 9276
 9277            // Selections must change based on added and removed line count
 9278            let start_row =
 9279                MultiBufferRow(start_point.row + added_lines as u32 - removed_lines as u32);
 9280            let end_row = MultiBufferRow(start_row.0 + lines_after.saturating_sub(1) as u32);
 9281            new_selections.push(Selection {
 9282                id: selection.id,
 9283                start: start_row,
 9284                end: end_row,
 9285                goal: SelectionGoal::None,
 9286                reversed: selection.reversed,
 9287            });
 9288
 9289            if lines_after > lines_before {
 9290                added_lines += lines_after - lines_before;
 9291            } else if lines_before > lines_after {
 9292                removed_lines += lines_before - lines_after;
 9293            }
 9294        }
 9295
 9296        self.transact(window, cx, |this, window, cx| {
 9297            let buffer = this.buffer.update(cx, |buffer, cx| {
 9298                buffer.edit(edits, None, cx);
 9299                buffer.snapshot(cx)
 9300            });
 9301
 9302            // Recalculate offsets on newly edited buffer
 9303            let new_selections = new_selections
 9304                .iter()
 9305                .map(|s| {
 9306                    let start_point = Point::new(s.start.0, 0);
 9307                    let end_point = Point::new(s.end.0, buffer.line_len(s.end));
 9308                    Selection {
 9309                        id: s.id,
 9310                        start: buffer.point_to_offset(start_point),
 9311                        end: buffer.point_to_offset(end_point),
 9312                        goal: s.goal,
 9313                        reversed: s.reversed,
 9314                    }
 9315                })
 9316                .collect();
 9317
 9318            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9319                s.select(new_selections);
 9320            });
 9321
 9322            this.request_autoscroll(Autoscroll::fit(), cx);
 9323        });
 9324    }
 9325
 9326    pub fn toggle_case(&mut self, _: &ToggleCase, window: &mut Window, cx: &mut Context<Self>) {
 9327        self.manipulate_text(window, cx, |text| {
 9328            let has_upper_case_characters = text.chars().any(|c| c.is_uppercase());
 9329            if has_upper_case_characters {
 9330                text.to_lowercase()
 9331            } else {
 9332                text.to_uppercase()
 9333            }
 9334        })
 9335    }
 9336
 9337    pub fn convert_to_upper_case(
 9338        &mut self,
 9339        _: &ConvertToUpperCase,
 9340        window: &mut Window,
 9341        cx: &mut Context<Self>,
 9342    ) {
 9343        self.manipulate_text(window, cx, |text| text.to_uppercase())
 9344    }
 9345
 9346    pub fn convert_to_lower_case(
 9347        &mut self,
 9348        _: &ConvertToLowerCase,
 9349        window: &mut Window,
 9350        cx: &mut Context<Self>,
 9351    ) {
 9352        self.manipulate_text(window, cx, |text| text.to_lowercase())
 9353    }
 9354
 9355    pub fn convert_to_title_case(
 9356        &mut self,
 9357        _: &ConvertToTitleCase,
 9358        window: &mut Window,
 9359        cx: &mut Context<Self>,
 9360    ) {
 9361        self.manipulate_text(window, cx, |text| {
 9362            text.split('\n')
 9363                .map(|line| line.to_case(Case::Title))
 9364                .join("\n")
 9365        })
 9366    }
 9367
 9368    pub fn convert_to_snake_case(
 9369        &mut self,
 9370        _: &ConvertToSnakeCase,
 9371        window: &mut Window,
 9372        cx: &mut Context<Self>,
 9373    ) {
 9374        self.manipulate_text(window, cx, |text| text.to_case(Case::Snake))
 9375    }
 9376
 9377    pub fn convert_to_kebab_case(
 9378        &mut self,
 9379        _: &ConvertToKebabCase,
 9380        window: &mut Window,
 9381        cx: &mut Context<Self>,
 9382    ) {
 9383        self.manipulate_text(window, cx, |text| text.to_case(Case::Kebab))
 9384    }
 9385
 9386    pub fn convert_to_upper_camel_case(
 9387        &mut self,
 9388        _: &ConvertToUpperCamelCase,
 9389        window: &mut Window,
 9390        cx: &mut Context<Self>,
 9391    ) {
 9392        self.manipulate_text(window, cx, |text| {
 9393            text.split('\n')
 9394                .map(|line| line.to_case(Case::UpperCamel))
 9395                .join("\n")
 9396        })
 9397    }
 9398
 9399    pub fn convert_to_lower_camel_case(
 9400        &mut self,
 9401        _: &ConvertToLowerCamelCase,
 9402        window: &mut Window,
 9403        cx: &mut Context<Self>,
 9404    ) {
 9405        self.manipulate_text(window, cx, |text| text.to_case(Case::Camel))
 9406    }
 9407
 9408    pub fn convert_to_opposite_case(
 9409        &mut self,
 9410        _: &ConvertToOppositeCase,
 9411        window: &mut Window,
 9412        cx: &mut Context<Self>,
 9413    ) {
 9414        self.manipulate_text(window, cx, |text| {
 9415            text.chars()
 9416                .fold(String::with_capacity(text.len()), |mut t, c| {
 9417                    if c.is_uppercase() {
 9418                        t.extend(c.to_lowercase());
 9419                    } else {
 9420                        t.extend(c.to_uppercase());
 9421                    }
 9422                    t
 9423                })
 9424        })
 9425    }
 9426
 9427    pub fn convert_to_rot13(
 9428        &mut self,
 9429        _: &ConvertToRot13,
 9430        window: &mut Window,
 9431        cx: &mut Context<Self>,
 9432    ) {
 9433        self.manipulate_text(window, cx, |text| {
 9434            text.chars()
 9435                .map(|c| match c {
 9436                    'A'..='M' | 'a'..='m' => ((c as u8) + 13) as char,
 9437                    'N'..='Z' | 'n'..='z' => ((c as u8) - 13) as char,
 9438                    _ => c,
 9439                })
 9440                .collect()
 9441        })
 9442    }
 9443
 9444    pub fn convert_to_rot47(
 9445        &mut self,
 9446        _: &ConvertToRot47,
 9447        window: &mut Window,
 9448        cx: &mut Context<Self>,
 9449    ) {
 9450        self.manipulate_text(window, cx, |text| {
 9451            text.chars()
 9452                .map(|c| {
 9453                    let code_point = c as u32;
 9454                    if code_point >= 33 && code_point <= 126 {
 9455                        return char::from_u32(33 + ((code_point + 14) % 94)).unwrap();
 9456                    }
 9457                    c
 9458                })
 9459                .collect()
 9460        })
 9461    }
 9462
 9463    fn manipulate_text<Fn>(&mut self, window: &mut Window, cx: &mut Context<Self>, mut callback: Fn)
 9464    where
 9465        Fn: FnMut(&str) -> String,
 9466    {
 9467        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 9468        let buffer = self.buffer.read(cx).snapshot(cx);
 9469
 9470        let mut new_selections = Vec::new();
 9471        let mut edits = Vec::new();
 9472        let mut selection_adjustment = 0i32;
 9473
 9474        for selection in self.selections.all::<usize>(cx) {
 9475            let selection_is_empty = selection.is_empty();
 9476
 9477            let (start, end) = if selection_is_empty {
 9478                let word_range = movement::surrounding_word(
 9479                    &display_map,
 9480                    selection.start.to_display_point(&display_map),
 9481                );
 9482                let start = word_range.start.to_offset(&display_map, Bias::Left);
 9483                let end = word_range.end.to_offset(&display_map, Bias::Left);
 9484                (start, end)
 9485            } else {
 9486                (selection.start, selection.end)
 9487            };
 9488
 9489            let text = buffer.text_for_range(start..end).collect::<String>();
 9490            let old_length = text.len() as i32;
 9491            let text = callback(&text);
 9492
 9493            new_selections.push(Selection {
 9494                start: (start as i32 - selection_adjustment) as usize,
 9495                end: ((start + text.len()) as i32 - selection_adjustment) as usize,
 9496                goal: SelectionGoal::None,
 9497                ..selection
 9498            });
 9499
 9500            selection_adjustment += old_length - text.len() as i32;
 9501
 9502            edits.push((start..end, text));
 9503        }
 9504
 9505        self.transact(window, cx, |this, window, cx| {
 9506            this.buffer.update(cx, |buffer, cx| {
 9507                buffer.edit(edits, None, cx);
 9508            });
 9509
 9510            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9511                s.select(new_selections);
 9512            });
 9513
 9514            this.request_autoscroll(Autoscroll::fit(), cx);
 9515        });
 9516    }
 9517
 9518    pub fn duplicate(
 9519        &mut self,
 9520        upwards: bool,
 9521        whole_lines: bool,
 9522        window: &mut Window,
 9523        cx: &mut Context<Self>,
 9524    ) {
 9525        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
 9526
 9527        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 9528        let buffer = &display_map.buffer_snapshot;
 9529        let selections = self.selections.all::<Point>(cx);
 9530
 9531        let mut edits = Vec::new();
 9532        let mut selections_iter = selections.iter().peekable();
 9533        while let Some(selection) = selections_iter.next() {
 9534            let mut rows = selection.spanned_rows(false, &display_map);
 9535            // duplicate line-wise
 9536            if whole_lines || selection.start == selection.end {
 9537                // Avoid duplicating the same lines twice.
 9538                while let Some(next_selection) = selections_iter.peek() {
 9539                    let next_rows = next_selection.spanned_rows(false, &display_map);
 9540                    if next_rows.start < rows.end {
 9541                        rows.end = next_rows.end;
 9542                        selections_iter.next().unwrap();
 9543                    } else {
 9544                        break;
 9545                    }
 9546                }
 9547
 9548                // Copy the text from the selected row region and splice it either at the start
 9549                // or end of the region.
 9550                let start = Point::new(rows.start.0, 0);
 9551                let end = Point::new(
 9552                    rows.end.previous_row().0,
 9553                    buffer.line_len(rows.end.previous_row()),
 9554                );
 9555                let text = buffer
 9556                    .text_for_range(start..end)
 9557                    .chain(Some("\n"))
 9558                    .collect::<String>();
 9559                let insert_location = if upwards {
 9560                    Point::new(rows.end.0, 0)
 9561                } else {
 9562                    start
 9563                };
 9564                edits.push((insert_location..insert_location, text));
 9565            } else {
 9566                // duplicate character-wise
 9567                let start = selection.start;
 9568                let end = selection.end;
 9569                let text = buffer.text_for_range(start..end).collect::<String>();
 9570                edits.push((selection.end..selection.end, text));
 9571            }
 9572        }
 9573
 9574        self.transact(window, cx, |this, _, cx| {
 9575            this.buffer.update(cx, |buffer, cx| {
 9576                buffer.edit(edits, None, cx);
 9577            });
 9578
 9579            this.request_autoscroll(Autoscroll::fit(), cx);
 9580        });
 9581    }
 9582
 9583    pub fn duplicate_line_up(
 9584        &mut self,
 9585        _: &DuplicateLineUp,
 9586        window: &mut Window,
 9587        cx: &mut Context<Self>,
 9588    ) {
 9589        self.duplicate(true, true, window, cx);
 9590    }
 9591
 9592    pub fn duplicate_line_down(
 9593        &mut self,
 9594        _: &DuplicateLineDown,
 9595        window: &mut Window,
 9596        cx: &mut Context<Self>,
 9597    ) {
 9598        self.duplicate(false, true, window, cx);
 9599    }
 9600
 9601    pub fn duplicate_selection(
 9602        &mut self,
 9603        _: &DuplicateSelection,
 9604        window: &mut Window,
 9605        cx: &mut Context<Self>,
 9606    ) {
 9607        self.duplicate(false, false, window, cx);
 9608    }
 9609
 9610    pub fn move_line_up(&mut self, _: &MoveLineUp, window: &mut Window, cx: &mut Context<Self>) {
 9611        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
 9612
 9613        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 9614        let buffer = self.buffer.read(cx).snapshot(cx);
 9615
 9616        let mut edits = Vec::new();
 9617        let mut unfold_ranges = Vec::new();
 9618        let mut refold_creases = Vec::new();
 9619
 9620        let selections = self.selections.all::<Point>(cx);
 9621        let mut selections = selections.iter().peekable();
 9622        let mut contiguous_row_selections = Vec::new();
 9623        let mut new_selections = Vec::new();
 9624
 9625        while let Some(selection) = selections.next() {
 9626            // Find all the selections that span a contiguous row range
 9627            let (start_row, end_row) = consume_contiguous_rows(
 9628                &mut contiguous_row_selections,
 9629                selection,
 9630                &display_map,
 9631                &mut selections,
 9632            );
 9633
 9634            // Move the text spanned by the row range to be before the line preceding the row range
 9635            if start_row.0 > 0 {
 9636                let range_to_move = Point::new(
 9637                    start_row.previous_row().0,
 9638                    buffer.line_len(start_row.previous_row()),
 9639                )
 9640                    ..Point::new(
 9641                        end_row.previous_row().0,
 9642                        buffer.line_len(end_row.previous_row()),
 9643                    );
 9644                let insertion_point = display_map
 9645                    .prev_line_boundary(Point::new(start_row.previous_row().0, 0))
 9646                    .0;
 9647
 9648                // Don't move lines across excerpts
 9649                if buffer
 9650                    .excerpt_containing(insertion_point..range_to_move.end)
 9651                    .is_some()
 9652                {
 9653                    let text = buffer
 9654                        .text_for_range(range_to_move.clone())
 9655                        .flat_map(|s| s.chars())
 9656                        .skip(1)
 9657                        .chain(['\n'])
 9658                        .collect::<String>();
 9659
 9660                    edits.push((
 9661                        buffer.anchor_after(range_to_move.start)
 9662                            ..buffer.anchor_before(range_to_move.end),
 9663                        String::new(),
 9664                    ));
 9665                    let insertion_anchor = buffer.anchor_after(insertion_point);
 9666                    edits.push((insertion_anchor..insertion_anchor, text));
 9667
 9668                    let row_delta = range_to_move.start.row - insertion_point.row + 1;
 9669
 9670                    // Move selections up
 9671                    new_selections.extend(contiguous_row_selections.drain(..).map(
 9672                        |mut selection| {
 9673                            selection.start.row -= row_delta;
 9674                            selection.end.row -= row_delta;
 9675                            selection
 9676                        },
 9677                    ));
 9678
 9679                    // Move folds up
 9680                    unfold_ranges.push(range_to_move.clone());
 9681                    for fold in display_map.folds_in_range(
 9682                        buffer.anchor_before(range_to_move.start)
 9683                            ..buffer.anchor_after(range_to_move.end),
 9684                    ) {
 9685                        let mut start = fold.range.start.to_point(&buffer);
 9686                        let mut end = fold.range.end.to_point(&buffer);
 9687                        start.row -= row_delta;
 9688                        end.row -= row_delta;
 9689                        refold_creases.push(Crease::simple(start..end, fold.placeholder.clone()));
 9690                    }
 9691                }
 9692            }
 9693
 9694            // If we didn't move line(s), preserve the existing selections
 9695            new_selections.append(&mut contiguous_row_selections);
 9696        }
 9697
 9698        self.transact(window, cx, |this, window, cx| {
 9699            this.unfold_ranges(&unfold_ranges, true, true, cx);
 9700            this.buffer.update(cx, |buffer, cx| {
 9701                for (range, text) in edits {
 9702                    buffer.edit([(range, text)], None, cx);
 9703                }
 9704            });
 9705            this.fold_creases(refold_creases, true, window, cx);
 9706            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9707                s.select(new_selections);
 9708            })
 9709        });
 9710    }
 9711
 9712    pub fn move_line_down(
 9713        &mut self,
 9714        _: &MoveLineDown,
 9715        window: &mut Window,
 9716        cx: &mut Context<Self>,
 9717    ) {
 9718        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
 9719
 9720        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 9721        let buffer = self.buffer.read(cx).snapshot(cx);
 9722
 9723        let mut edits = Vec::new();
 9724        let mut unfold_ranges = Vec::new();
 9725        let mut refold_creases = Vec::new();
 9726
 9727        let selections = self.selections.all::<Point>(cx);
 9728        let mut selections = selections.iter().peekable();
 9729        let mut contiguous_row_selections = Vec::new();
 9730        let mut new_selections = Vec::new();
 9731
 9732        while let Some(selection) = selections.next() {
 9733            // Find all the selections that span a contiguous row range
 9734            let (start_row, end_row) = consume_contiguous_rows(
 9735                &mut contiguous_row_selections,
 9736                selection,
 9737                &display_map,
 9738                &mut selections,
 9739            );
 9740
 9741            // Move the text spanned by the row range to be after the last line of the row range
 9742            if end_row.0 <= buffer.max_point().row {
 9743                let range_to_move =
 9744                    MultiBufferPoint::new(start_row.0, 0)..MultiBufferPoint::new(end_row.0, 0);
 9745                let insertion_point = display_map
 9746                    .next_line_boundary(MultiBufferPoint::new(end_row.0, 0))
 9747                    .0;
 9748
 9749                // Don't move lines across excerpt boundaries
 9750                if buffer
 9751                    .excerpt_containing(range_to_move.start..insertion_point)
 9752                    .is_some()
 9753                {
 9754                    let mut text = String::from("\n");
 9755                    text.extend(buffer.text_for_range(range_to_move.clone()));
 9756                    text.pop(); // Drop trailing newline
 9757                    edits.push((
 9758                        buffer.anchor_after(range_to_move.start)
 9759                            ..buffer.anchor_before(range_to_move.end),
 9760                        String::new(),
 9761                    ));
 9762                    let insertion_anchor = buffer.anchor_after(insertion_point);
 9763                    edits.push((insertion_anchor..insertion_anchor, text));
 9764
 9765                    let row_delta = insertion_point.row - range_to_move.end.row + 1;
 9766
 9767                    // Move selections down
 9768                    new_selections.extend(contiguous_row_selections.drain(..).map(
 9769                        |mut selection| {
 9770                            selection.start.row += row_delta;
 9771                            selection.end.row += row_delta;
 9772                            selection
 9773                        },
 9774                    ));
 9775
 9776                    // Move folds down
 9777                    unfold_ranges.push(range_to_move.clone());
 9778                    for fold in display_map.folds_in_range(
 9779                        buffer.anchor_before(range_to_move.start)
 9780                            ..buffer.anchor_after(range_to_move.end),
 9781                    ) {
 9782                        let mut start = fold.range.start.to_point(&buffer);
 9783                        let mut end = fold.range.end.to_point(&buffer);
 9784                        start.row += row_delta;
 9785                        end.row += row_delta;
 9786                        refold_creases.push(Crease::simple(start..end, fold.placeholder.clone()));
 9787                    }
 9788                }
 9789            }
 9790
 9791            // If we didn't move line(s), preserve the existing selections
 9792            new_selections.append(&mut contiguous_row_selections);
 9793        }
 9794
 9795        self.transact(window, cx, |this, window, cx| {
 9796            this.unfold_ranges(&unfold_ranges, true, true, cx);
 9797            this.buffer.update(cx, |buffer, cx| {
 9798                for (range, text) in edits {
 9799                    buffer.edit([(range, text)], None, cx);
 9800                }
 9801            });
 9802            this.fold_creases(refold_creases, true, window, cx);
 9803            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9804                s.select(new_selections)
 9805            });
 9806        });
 9807    }
 9808
 9809    pub fn transpose(&mut self, _: &Transpose, window: &mut Window, cx: &mut Context<Self>) {
 9810        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
 9811        let text_layout_details = &self.text_layout_details(window);
 9812        self.transact(window, cx, |this, window, cx| {
 9813            let edits = this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9814                let mut edits: Vec<(Range<usize>, String)> = Default::default();
 9815                s.move_with(|display_map, selection| {
 9816                    if !selection.is_empty() {
 9817                        return;
 9818                    }
 9819
 9820                    let mut head = selection.head();
 9821                    let mut transpose_offset = head.to_offset(display_map, Bias::Right);
 9822                    if head.column() == display_map.line_len(head.row()) {
 9823                        transpose_offset = display_map
 9824                            .buffer_snapshot
 9825                            .clip_offset(transpose_offset.saturating_sub(1), Bias::Left);
 9826                    }
 9827
 9828                    if transpose_offset == 0 {
 9829                        return;
 9830                    }
 9831
 9832                    *head.column_mut() += 1;
 9833                    head = display_map.clip_point(head, Bias::Right);
 9834                    let goal = SelectionGoal::HorizontalPosition(
 9835                        display_map
 9836                            .x_for_display_point(head, text_layout_details)
 9837                            .into(),
 9838                    );
 9839                    selection.collapse_to(head, goal);
 9840
 9841                    let transpose_start = display_map
 9842                        .buffer_snapshot
 9843                        .clip_offset(transpose_offset.saturating_sub(1), Bias::Left);
 9844                    if edits.last().map_or(true, |e| e.0.end <= transpose_start) {
 9845                        let transpose_end = display_map
 9846                            .buffer_snapshot
 9847                            .clip_offset(transpose_offset + 1, Bias::Right);
 9848                        if let Some(ch) =
 9849                            display_map.buffer_snapshot.chars_at(transpose_start).next()
 9850                        {
 9851                            edits.push((transpose_start..transpose_offset, String::new()));
 9852                            edits.push((transpose_end..transpose_end, ch.to_string()));
 9853                        }
 9854                    }
 9855                });
 9856                edits
 9857            });
 9858            this.buffer
 9859                .update(cx, |buffer, cx| buffer.edit(edits, None, cx));
 9860            let selections = this.selections.all::<usize>(cx);
 9861            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9862                s.select(selections);
 9863            });
 9864        });
 9865    }
 9866
 9867    pub fn rewrap(&mut self, _: &Rewrap, _: &mut Window, cx: &mut Context<Self>) {
 9868        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
 9869        self.rewrap_impl(RewrapOptions::default(), cx)
 9870    }
 9871
 9872    pub fn rewrap_impl(&mut self, options: RewrapOptions, cx: &mut Context<Self>) {
 9873        let buffer = self.buffer.read(cx).snapshot(cx);
 9874        let selections = self.selections.all::<Point>(cx);
 9875        let mut selections = selections.iter().peekable();
 9876
 9877        let mut edits = Vec::new();
 9878        let mut rewrapped_row_ranges = Vec::<RangeInclusive<u32>>::new();
 9879
 9880        while let Some(selection) = selections.next() {
 9881            let mut start_row = selection.start.row;
 9882            let mut end_row = selection.end.row;
 9883
 9884            // Skip selections that overlap with a range that has already been rewrapped.
 9885            let selection_range = start_row..end_row;
 9886            if rewrapped_row_ranges
 9887                .iter()
 9888                .any(|range| range.overlaps(&selection_range))
 9889            {
 9890                continue;
 9891            }
 9892
 9893            let tab_size = buffer.language_settings_at(selection.head(), cx).tab_size;
 9894
 9895            // Since not all lines in the selection may be at the same indent
 9896            // level, choose the indent size that is the most common between all
 9897            // of the lines.
 9898            //
 9899            // If there is a tie, we use the deepest indent.
 9900            let (indent_size, indent_end) = {
 9901                let mut indent_size_occurrences = HashMap::default();
 9902                let mut rows_by_indent_size = HashMap::<IndentSize, Vec<u32>>::default();
 9903
 9904                for row in start_row..=end_row {
 9905                    let indent = buffer.indent_size_for_line(MultiBufferRow(row));
 9906                    rows_by_indent_size.entry(indent).or_default().push(row);
 9907                    *indent_size_occurrences.entry(indent).or_insert(0) += 1;
 9908                }
 9909
 9910                let indent_size = indent_size_occurrences
 9911                    .into_iter()
 9912                    .max_by_key(|(indent, count)| (*count, indent.len_with_expanded_tabs(tab_size)))
 9913                    .map(|(indent, _)| indent)
 9914                    .unwrap_or_default();
 9915                let row = rows_by_indent_size[&indent_size][0];
 9916                let indent_end = Point::new(row, indent_size.len);
 9917
 9918                (indent_size, indent_end)
 9919            };
 9920
 9921            let mut line_prefix = indent_size.chars().collect::<String>();
 9922
 9923            let mut inside_comment = false;
 9924            if let Some(comment_prefix) =
 9925                buffer
 9926                    .language_scope_at(selection.head())
 9927                    .and_then(|language| {
 9928                        language
 9929                            .line_comment_prefixes()
 9930                            .iter()
 9931                            .find(|prefix| buffer.contains_str_at(indent_end, prefix))
 9932                            .cloned()
 9933                    })
 9934            {
 9935                line_prefix.push_str(&comment_prefix);
 9936                inside_comment = true;
 9937            }
 9938
 9939            let language_settings = buffer.language_settings_at(selection.head(), cx);
 9940            let allow_rewrap_based_on_language = match language_settings.allow_rewrap {
 9941                RewrapBehavior::InComments => inside_comment,
 9942                RewrapBehavior::InSelections => !selection.is_empty(),
 9943                RewrapBehavior::Anywhere => true,
 9944            };
 9945
 9946            let should_rewrap = options.override_language_settings
 9947                || allow_rewrap_based_on_language
 9948                || self.hard_wrap.is_some();
 9949            if !should_rewrap {
 9950                continue;
 9951            }
 9952
 9953            if selection.is_empty() {
 9954                'expand_upwards: while start_row > 0 {
 9955                    let prev_row = start_row - 1;
 9956                    if buffer.contains_str_at(Point::new(prev_row, 0), &line_prefix)
 9957                        && buffer.line_len(MultiBufferRow(prev_row)) as usize > line_prefix.len()
 9958                    {
 9959                        start_row = prev_row;
 9960                    } else {
 9961                        break 'expand_upwards;
 9962                    }
 9963                }
 9964
 9965                'expand_downwards: while end_row < buffer.max_point().row {
 9966                    let next_row = end_row + 1;
 9967                    if buffer.contains_str_at(Point::new(next_row, 0), &line_prefix)
 9968                        && buffer.line_len(MultiBufferRow(next_row)) as usize > line_prefix.len()
 9969                    {
 9970                        end_row = next_row;
 9971                    } else {
 9972                        break 'expand_downwards;
 9973                    }
 9974                }
 9975            }
 9976
 9977            let start = Point::new(start_row, 0);
 9978            let start_offset = start.to_offset(&buffer);
 9979            let end = Point::new(end_row, buffer.line_len(MultiBufferRow(end_row)));
 9980            let selection_text = buffer.text_for_range(start..end).collect::<String>();
 9981            let Some(lines_without_prefixes) = selection_text
 9982                .lines()
 9983                .map(|line| {
 9984                    line.strip_prefix(&line_prefix)
 9985                        .or_else(|| line.trim_start().strip_prefix(&line_prefix.trim_start()))
 9986                        .ok_or_else(|| {
 9987                            anyhow!("line did not start with prefix {line_prefix:?}: {line:?}")
 9988                        })
 9989                })
 9990                .collect::<Result<Vec<_>, _>>()
 9991                .log_err()
 9992            else {
 9993                continue;
 9994            };
 9995
 9996            let wrap_column = self.hard_wrap.unwrap_or_else(|| {
 9997                buffer
 9998                    .language_settings_at(Point::new(start_row, 0), cx)
 9999                    .preferred_line_length as usize
10000            });
10001            let wrapped_text = wrap_with_prefix(
10002                line_prefix,
10003                lines_without_prefixes.join("\n"),
10004                wrap_column,
10005                tab_size,
10006                options.preserve_existing_whitespace,
10007            );
10008
10009            // TODO: should always use char-based diff while still supporting cursor behavior that
10010            // matches vim.
10011            let mut diff_options = DiffOptions::default();
10012            if options.override_language_settings {
10013                diff_options.max_word_diff_len = 0;
10014                diff_options.max_word_diff_line_count = 0;
10015            } else {
10016                diff_options.max_word_diff_len = usize::MAX;
10017                diff_options.max_word_diff_line_count = usize::MAX;
10018            }
10019
10020            for (old_range, new_text) in
10021                text_diff_with_options(&selection_text, &wrapped_text, diff_options)
10022            {
10023                let edit_start = buffer.anchor_after(start_offset + old_range.start);
10024                let edit_end = buffer.anchor_after(start_offset + old_range.end);
10025                edits.push((edit_start..edit_end, new_text));
10026            }
10027
10028            rewrapped_row_ranges.push(start_row..=end_row);
10029        }
10030
10031        self.buffer
10032            .update(cx, |buffer, cx| buffer.edit(edits, None, cx));
10033    }
10034
10035    pub fn cut_common(&mut self, window: &mut Window, cx: &mut Context<Self>) -> ClipboardItem {
10036        let mut text = String::new();
10037        let buffer = self.buffer.read(cx).snapshot(cx);
10038        let mut selections = self.selections.all::<Point>(cx);
10039        let mut clipboard_selections = Vec::with_capacity(selections.len());
10040        {
10041            let max_point = buffer.max_point();
10042            let mut is_first = true;
10043            for selection in &mut selections {
10044                let is_entire_line = selection.is_empty() || self.selections.line_mode;
10045                if is_entire_line {
10046                    selection.start = Point::new(selection.start.row, 0);
10047                    if !selection.is_empty() && selection.end.column == 0 {
10048                        selection.end = cmp::min(max_point, selection.end);
10049                    } else {
10050                        selection.end = cmp::min(max_point, Point::new(selection.end.row + 1, 0));
10051                    }
10052                    selection.goal = SelectionGoal::None;
10053                }
10054                if is_first {
10055                    is_first = false;
10056                } else {
10057                    text += "\n";
10058                }
10059                let mut len = 0;
10060                for chunk in buffer.text_for_range(selection.start..selection.end) {
10061                    text.push_str(chunk);
10062                    len += chunk.len();
10063                }
10064                clipboard_selections.push(ClipboardSelection {
10065                    len,
10066                    is_entire_line,
10067                    first_line_indent: buffer
10068                        .indent_size_for_line(MultiBufferRow(selection.start.row))
10069                        .len,
10070                });
10071            }
10072        }
10073
10074        self.transact(window, cx, |this, window, cx| {
10075            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10076                s.select(selections);
10077            });
10078            this.insert("", window, cx);
10079        });
10080        ClipboardItem::new_string_with_json_metadata(text, clipboard_selections)
10081    }
10082
10083    pub fn cut(&mut self, _: &Cut, window: &mut Window, cx: &mut Context<Self>) {
10084        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
10085        let item = self.cut_common(window, cx);
10086        cx.write_to_clipboard(item);
10087    }
10088
10089    pub fn kill_ring_cut(&mut self, _: &KillRingCut, window: &mut Window, cx: &mut Context<Self>) {
10090        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
10091        self.change_selections(None, window, cx, |s| {
10092            s.move_with(|snapshot, sel| {
10093                if sel.is_empty() {
10094                    sel.end = DisplayPoint::new(sel.end.row(), snapshot.line_len(sel.end.row()))
10095                }
10096            });
10097        });
10098        let item = self.cut_common(window, cx);
10099        cx.set_global(KillRing(item))
10100    }
10101
10102    pub fn kill_ring_yank(
10103        &mut self,
10104        _: &KillRingYank,
10105        window: &mut Window,
10106        cx: &mut Context<Self>,
10107    ) {
10108        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
10109        let (text, metadata) = if let Some(KillRing(item)) = cx.try_global() {
10110            if let Some(ClipboardEntry::String(kill_ring)) = item.entries().first() {
10111                (kill_ring.text().to_string(), kill_ring.metadata_json())
10112            } else {
10113                return;
10114            }
10115        } else {
10116            return;
10117        };
10118        self.do_paste(&text, metadata, false, window, cx);
10119    }
10120
10121    pub fn copy_and_trim(&mut self, _: &CopyAndTrim, _: &mut Window, cx: &mut Context<Self>) {
10122        self.do_copy(true, cx);
10123    }
10124
10125    pub fn copy(&mut self, _: &Copy, _: &mut Window, cx: &mut Context<Self>) {
10126        self.do_copy(false, cx);
10127    }
10128
10129    fn do_copy(&self, strip_leading_indents: bool, cx: &mut Context<Self>) {
10130        let selections = self.selections.all::<Point>(cx);
10131        let buffer = self.buffer.read(cx).read(cx);
10132        let mut text = String::new();
10133
10134        let mut clipboard_selections = Vec::with_capacity(selections.len());
10135        {
10136            let max_point = buffer.max_point();
10137            let mut is_first = true;
10138            for selection in &selections {
10139                let mut start = selection.start;
10140                let mut end = selection.end;
10141                let is_entire_line = selection.is_empty() || self.selections.line_mode;
10142                if is_entire_line {
10143                    start = Point::new(start.row, 0);
10144                    end = cmp::min(max_point, Point::new(end.row + 1, 0));
10145                }
10146
10147                let mut trimmed_selections = Vec::new();
10148                if strip_leading_indents && end.row.saturating_sub(start.row) > 0 {
10149                    let row = MultiBufferRow(start.row);
10150                    let first_indent = buffer.indent_size_for_line(row);
10151                    if first_indent.len == 0 || start.column > first_indent.len {
10152                        trimmed_selections.push(start..end);
10153                    } else {
10154                        trimmed_selections.push(
10155                            Point::new(row.0, first_indent.len)
10156                                ..Point::new(row.0, buffer.line_len(row)),
10157                        );
10158                        for row in start.row + 1..=end.row {
10159                            let mut line_len = buffer.line_len(MultiBufferRow(row));
10160                            if row == end.row {
10161                                line_len = end.column;
10162                            }
10163                            if line_len == 0 {
10164                                trimmed_selections
10165                                    .push(Point::new(row, 0)..Point::new(row, line_len));
10166                                continue;
10167                            }
10168                            let row_indent_size = buffer.indent_size_for_line(MultiBufferRow(row));
10169                            if row_indent_size.len >= first_indent.len {
10170                                trimmed_selections.push(
10171                                    Point::new(row, first_indent.len)..Point::new(row, line_len),
10172                                );
10173                            } else {
10174                                trimmed_selections.clear();
10175                                trimmed_selections.push(start..end);
10176                                break;
10177                            }
10178                        }
10179                    }
10180                } else {
10181                    trimmed_selections.push(start..end);
10182                }
10183
10184                for trimmed_range in trimmed_selections {
10185                    if is_first {
10186                        is_first = false;
10187                    } else {
10188                        text += "\n";
10189                    }
10190                    let mut len = 0;
10191                    for chunk in buffer.text_for_range(trimmed_range.start..trimmed_range.end) {
10192                        text.push_str(chunk);
10193                        len += chunk.len();
10194                    }
10195                    clipboard_selections.push(ClipboardSelection {
10196                        len,
10197                        is_entire_line,
10198                        first_line_indent: buffer
10199                            .indent_size_for_line(MultiBufferRow(trimmed_range.start.row))
10200                            .len,
10201                    });
10202                }
10203            }
10204        }
10205
10206        cx.write_to_clipboard(ClipboardItem::new_string_with_json_metadata(
10207            text,
10208            clipboard_selections,
10209        ));
10210    }
10211
10212    pub fn do_paste(
10213        &mut self,
10214        text: &String,
10215        clipboard_selections: Option<Vec<ClipboardSelection>>,
10216        handle_entire_lines: bool,
10217        window: &mut Window,
10218        cx: &mut Context<Self>,
10219    ) {
10220        if self.read_only(cx) {
10221            return;
10222        }
10223
10224        let clipboard_text = Cow::Borrowed(text);
10225
10226        self.transact(window, cx, |this, window, cx| {
10227            if let Some(mut clipboard_selections) = clipboard_selections {
10228                let old_selections = this.selections.all::<usize>(cx);
10229                let all_selections_were_entire_line =
10230                    clipboard_selections.iter().all(|s| s.is_entire_line);
10231                let first_selection_indent_column =
10232                    clipboard_selections.first().map(|s| s.first_line_indent);
10233                if clipboard_selections.len() != old_selections.len() {
10234                    clipboard_selections.drain(..);
10235                }
10236                let cursor_offset = this.selections.last::<usize>(cx).head();
10237                let mut auto_indent_on_paste = true;
10238
10239                this.buffer.update(cx, |buffer, cx| {
10240                    let snapshot = buffer.read(cx);
10241                    auto_indent_on_paste = snapshot
10242                        .language_settings_at(cursor_offset, cx)
10243                        .auto_indent_on_paste;
10244
10245                    let mut start_offset = 0;
10246                    let mut edits = Vec::new();
10247                    let mut original_indent_columns = Vec::new();
10248                    for (ix, selection) in old_selections.iter().enumerate() {
10249                        let to_insert;
10250                        let entire_line;
10251                        let original_indent_column;
10252                        if let Some(clipboard_selection) = clipboard_selections.get(ix) {
10253                            let end_offset = start_offset + clipboard_selection.len;
10254                            to_insert = &clipboard_text[start_offset..end_offset];
10255                            entire_line = clipboard_selection.is_entire_line;
10256                            start_offset = end_offset + 1;
10257                            original_indent_column = Some(clipboard_selection.first_line_indent);
10258                        } else {
10259                            to_insert = clipboard_text.as_str();
10260                            entire_line = all_selections_were_entire_line;
10261                            original_indent_column = first_selection_indent_column
10262                        }
10263
10264                        // If the corresponding selection was empty when this slice of the
10265                        // clipboard text was written, then the entire line containing the
10266                        // selection was copied. If this selection is also currently empty,
10267                        // then paste the line before the current line of the buffer.
10268                        let range = if selection.is_empty() && handle_entire_lines && entire_line {
10269                            let column = selection.start.to_point(&snapshot).column as usize;
10270                            let line_start = selection.start - column;
10271                            line_start..line_start
10272                        } else {
10273                            selection.range()
10274                        };
10275
10276                        edits.push((range, to_insert));
10277                        original_indent_columns.push(original_indent_column);
10278                    }
10279                    drop(snapshot);
10280
10281                    buffer.edit(
10282                        edits,
10283                        if auto_indent_on_paste {
10284                            Some(AutoindentMode::Block {
10285                                original_indent_columns,
10286                            })
10287                        } else {
10288                            None
10289                        },
10290                        cx,
10291                    );
10292                });
10293
10294                let selections = this.selections.all::<usize>(cx);
10295                this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10296                    s.select(selections)
10297                });
10298            } else {
10299                this.insert(&clipboard_text, window, cx);
10300            }
10301        });
10302    }
10303
10304    pub fn paste(&mut self, _: &Paste, window: &mut Window, cx: &mut Context<Self>) {
10305        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
10306        if let Some(item) = cx.read_from_clipboard() {
10307            let entries = item.entries();
10308
10309            match entries.first() {
10310                // For now, we only support applying metadata if there's one string. In the future, we can incorporate all the selections
10311                // of all the pasted entries.
10312                Some(ClipboardEntry::String(clipboard_string)) if entries.len() == 1 => self
10313                    .do_paste(
10314                        clipboard_string.text(),
10315                        clipboard_string.metadata_json::<Vec<ClipboardSelection>>(),
10316                        true,
10317                        window,
10318                        cx,
10319                    ),
10320                _ => self.do_paste(&item.text().unwrap_or_default(), None, true, window, cx),
10321            }
10322        }
10323    }
10324
10325    pub fn undo(&mut self, _: &Undo, window: &mut Window, cx: &mut Context<Self>) {
10326        if self.read_only(cx) {
10327            return;
10328        }
10329
10330        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
10331
10332        if let Some(transaction_id) = self.buffer.update(cx, |buffer, cx| buffer.undo(cx)) {
10333            if let Some((selections, _)) =
10334                self.selection_history.transaction(transaction_id).cloned()
10335            {
10336                self.change_selections(None, window, cx, |s| {
10337                    s.select_anchors(selections.to_vec());
10338                });
10339            } else {
10340                log::error!(
10341                    "No entry in selection_history found for undo. \
10342                     This may correspond to a bug where undo does not update the selection. \
10343                     If this is occurring, please add details to \
10344                     https://github.com/zed-industries/zed/issues/22692"
10345                );
10346            }
10347            self.request_autoscroll(Autoscroll::fit(), cx);
10348            self.unmark_text(window, cx);
10349            self.refresh_inline_completion(true, false, window, cx);
10350            cx.emit(EditorEvent::Edited { transaction_id });
10351            cx.emit(EditorEvent::TransactionUndone { transaction_id });
10352        }
10353    }
10354
10355    pub fn redo(&mut self, _: &Redo, window: &mut Window, cx: &mut Context<Self>) {
10356        if self.read_only(cx) {
10357            return;
10358        }
10359
10360        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
10361
10362        if let Some(transaction_id) = self.buffer.update(cx, |buffer, cx| buffer.redo(cx)) {
10363            if let Some((_, Some(selections))) =
10364                self.selection_history.transaction(transaction_id).cloned()
10365            {
10366                self.change_selections(None, window, cx, |s| {
10367                    s.select_anchors(selections.to_vec());
10368                });
10369            } else {
10370                log::error!(
10371                    "No entry in selection_history found for redo. \
10372                     This may correspond to a bug where undo does not update the selection. \
10373                     If this is occurring, please add details to \
10374                     https://github.com/zed-industries/zed/issues/22692"
10375                );
10376            }
10377            self.request_autoscroll(Autoscroll::fit(), cx);
10378            self.unmark_text(window, cx);
10379            self.refresh_inline_completion(true, false, window, cx);
10380            cx.emit(EditorEvent::Edited { transaction_id });
10381        }
10382    }
10383
10384    pub fn finalize_last_transaction(&mut self, cx: &mut Context<Self>) {
10385        self.buffer
10386            .update(cx, |buffer, cx| buffer.finalize_last_transaction(cx));
10387    }
10388
10389    pub fn group_until_transaction(&mut self, tx_id: TransactionId, cx: &mut Context<Self>) {
10390        self.buffer
10391            .update(cx, |buffer, cx| buffer.group_until_transaction(tx_id, cx));
10392    }
10393
10394    pub fn move_left(&mut self, _: &MoveLeft, window: &mut Window, cx: &mut Context<Self>) {
10395        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
10396        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10397            s.move_with(|map, selection| {
10398                let cursor = if selection.is_empty() {
10399                    movement::left(map, selection.start)
10400                } else {
10401                    selection.start
10402                };
10403                selection.collapse_to(cursor, SelectionGoal::None);
10404            });
10405        })
10406    }
10407
10408    pub fn select_left(&mut self, _: &SelectLeft, window: &mut Window, cx: &mut Context<Self>) {
10409        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
10410        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10411            s.move_heads_with(|map, head, _| (movement::left(map, head), SelectionGoal::None));
10412        })
10413    }
10414
10415    pub fn move_right(&mut self, _: &MoveRight, window: &mut Window, cx: &mut Context<Self>) {
10416        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
10417        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10418            s.move_with(|map, selection| {
10419                let cursor = if selection.is_empty() {
10420                    movement::right(map, selection.end)
10421                } else {
10422                    selection.end
10423                };
10424                selection.collapse_to(cursor, SelectionGoal::None)
10425            });
10426        })
10427    }
10428
10429    pub fn select_right(&mut self, _: &SelectRight, window: &mut Window, cx: &mut Context<Self>) {
10430        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
10431        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10432            s.move_heads_with(|map, head, _| (movement::right(map, head), SelectionGoal::None));
10433        })
10434    }
10435
10436    pub fn move_up(&mut self, _: &MoveUp, window: &mut Window, cx: &mut Context<Self>) {
10437        if self.take_rename(true, window, cx).is_some() {
10438            return;
10439        }
10440
10441        if matches!(self.mode, EditorMode::SingleLine { .. }) {
10442            cx.propagate();
10443            return;
10444        }
10445
10446        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
10447
10448        let text_layout_details = &self.text_layout_details(window);
10449        let selection_count = self.selections.count();
10450        let first_selection = self.selections.first_anchor();
10451
10452        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10453            s.move_with(|map, selection| {
10454                if !selection.is_empty() {
10455                    selection.goal = SelectionGoal::None;
10456                }
10457                let (cursor, goal) = movement::up(
10458                    map,
10459                    selection.start,
10460                    selection.goal,
10461                    false,
10462                    text_layout_details,
10463                );
10464                selection.collapse_to(cursor, goal);
10465            });
10466        });
10467
10468        if selection_count == 1 && first_selection.range() == self.selections.first_anchor().range()
10469        {
10470            cx.propagate();
10471        }
10472    }
10473
10474    pub fn move_up_by_lines(
10475        &mut self,
10476        action: &MoveUpByLines,
10477        window: &mut Window,
10478        cx: &mut Context<Self>,
10479    ) {
10480        if self.take_rename(true, window, cx).is_some() {
10481            return;
10482        }
10483
10484        if matches!(self.mode, EditorMode::SingleLine { .. }) {
10485            cx.propagate();
10486            return;
10487        }
10488
10489        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
10490
10491        let text_layout_details = &self.text_layout_details(window);
10492
10493        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10494            s.move_with(|map, selection| {
10495                if !selection.is_empty() {
10496                    selection.goal = SelectionGoal::None;
10497                }
10498                let (cursor, goal) = movement::up_by_rows(
10499                    map,
10500                    selection.start,
10501                    action.lines,
10502                    selection.goal,
10503                    false,
10504                    text_layout_details,
10505                );
10506                selection.collapse_to(cursor, goal);
10507            });
10508        })
10509    }
10510
10511    pub fn move_down_by_lines(
10512        &mut self,
10513        action: &MoveDownByLines,
10514        window: &mut Window,
10515        cx: &mut Context<Self>,
10516    ) {
10517        if self.take_rename(true, window, cx).is_some() {
10518            return;
10519        }
10520
10521        if matches!(self.mode, EditorMode::SingleLine { .. }) {
10522            cx.propagate();
10523            return;
10524        }
10525
10526        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
10527
10528        let text_layout_details = &self.text_layout_details(window);
10529
10530        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10531            s.move_with(|map, selection| {
10532                if !selection.is_empty() {
10533                    selection.goal = SelectionGoal::None;
10534                }
10535                let (cursor, goal) = movement::down_by_rows(
10536                    map,
10537                    selection.start,
10538                    action.lines,
10539                    selection.goal,
10540                    false,
10541                    text_layout_details,
10542                );
10543                selection.collapse_to(cursor, goal);
10544            });
10545        })
10546    }
10547
10548    pub fn select_down_by_lines(
10549        &mut self,
10550        action: &SelectDownByLines,
10551        window: &mut Window,
10552        cx: &mut Context<Self>,
10553    ) {
10554        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
10555        let text_layout_details = &self.text_layout_details(window);
10556        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10557            s.move_heads_with(|map, head, goal| {
10558                movement::down_by_rows(map, head, action.lines, goal, false, text_layout_details)
10559            })
10560        })
10561    }
10562
10563    pub fn select_up_by_lines(
10564        &mut self,
10565        action: &SelectUpByLines,
10566        window: &mut Window,
10567        cx: &mut Context<Self>,
10568    ) {
10569        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
10570        let text_layout_details = &self.text_layout_details(window);
10571        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10572            s.move_heads_with(|map, head, goal| {
10573                movement::up_by_rows(map, head, action.lines, goal, false, text_layout_details)
10574            })
10575        })
10576    }
10577
10578    pub fn select_page_up(
10579        &mut self,
10580        _: &SelectPageUp,
10581        window: &mut Window,
10582        cx: &mut Context<Self>,
10583    ) {
10584        let Some(row_count) = self.visible_row_count() else {
10585            return;
10586        };
10587
10588        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
10589
10590        let text_layout_details = &self.text_layout_details(window);
10591
10592        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10593            s.move_heads_with(|map, head, goal| {
10594                movement::up_by_rows(map, head, row_count, goal, false, text_layout_details)
10595            })
10596        })
10597    }
10598
10599    pub fn move_page_up(
10600        &mut self,
10601        action: &MovePageUp,
10602        window: &mut Window,
10603        cx: &mut Context<Self>,
10604    ) {
10605        if self.take_rename(true, window, cx).is_some() {
10606            return;
10607        }
10608
10609        if self
10610            .context_menu
10611            .borrow_mut()
10612            .as_mut()
10613            .map(|menu| menu.select_first(self.completion_provider.as_deref(), cx))
10614            .unwrap_or(false)
10615        {
10616            return;
10617        }
10618
10619        if matches!(self.mode, EditorMode::SingleLine { .. }) {
10620            cx.propagate();
10621            return;
10622        }
10623
10624        let Some(row_count) = self.visible_row_count() else {
10625            return;
10626        };
10627
10628        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
10629
10630        let autoscroll = if action.center_cursor {
10631            Autoscroll::center()
10632        } else {
10633            Autoscroll::fit()
10634        };
10635
10636        let text_layout_details = &self.text_layout_details(window);
10637
10638        self.change_selections(Some(autoscroll), window, cx, |s| {
10639            s.move_with(|map, selection| {
10640                if !selection.is_empty() {
10641                    selection.goal = SelectionGoal::None;
10642                }
10643                let (cursor, goal) = movement::up_by_rows(
10644                    map,
10645                    selection.end,
10646                    row_count,
10647                    selection.goal,
10648                    false,
10649                    text_layout_details,
10650                );
10651                selection.collapse_to(cursor, goal);
10652            });
10653        });
10654    }
10655
10656    pub fn select_up(&mut self, _: &SelectUp, window: &mut Window, cx: &mut Context<Self>) {
10657        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
10658        let text_layout_details = &self.text_layout_details(window);
10659        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10660            s.move_heads_with(|map, head, goal| {
10661                movement::up(map, head, goal, false, text_layout_details)
10662            })
10663        })
10664    }
10665
10666    pub fn move_down(&mut self, _: &MoveDown, window: &mut Window, cx: &mut Context<Self>) {
10667        self.take_rename(true, window, cx);
10668
10669        if matches!(self.mode, EditorMode::SingleLine { .. }) {
10670            cx.propagate();
10671            return;
10672        }
10673
10674        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
10675
10676        let text_layout_details = &self.text_layout_details(window);
10677        let selection_count = self.selections.count();
10678        let first_selection = self.selections.first_anchor();
10679
10680        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10681            s.move_with(|map, selection| {
10682                if !selection.is_empty() {
10683                    selection.goal = SelectionGoal::None;
10684                }
10685                let (cursor, goal) = movement::down(
10686                    map,
10687                    selection.end,
10688                    selection.goal,
10689                    false,
10690                    text_layout_details,
10691                );
10692                selection.collapse_to(cursor, goal);
10693            });
10694        });
10695
10696        if selection_count == 1 && first_selection.range() == self.selections.first_anchor().range()
10697        {
10698            cx.propagate();
10699        }
10700    }
10701
10702    pub fn select_page_down(
10703        &mut self,
10704        _: &SelectPageDown,
10705        window: &mut Window,
10706        cx: &mut Context<Self>,
10707    ) {
10708        let Some(row_count) = self.visible_row_count() else {
10709            return;
10710        };
10711
10712        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
10713
10714        let text_layout_details = &self.text_layout_details(window);
10715
10716        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10717            s.move_heads_with(|map, head, goal| {
10718                movement::down_by_rows(map, head, row_count, goal, false, text_layout_details)
10719            })
10720        })
10721    }
10722
10723    pub fn move_page_down(
10724        &mut self,
10725        action: &MovePageDown,
10726        window: &mut Window,
10727        cx: &mut Context<Self>,
10728    ) {
10729        if self.take_rename(true, window, cx).is_some() {
10730            return;
10731        }
10732
10733        if self
10734            .context_menu
10735            .borrow_mut()
10736            .as_mut()
10737            .map(|menu| menu.select_last(self.completion_provider.as_deref(), cx))
10738            .unwrap_or(false)
10739        {
10740            return;
10741        }
10742
10743        if matches!(self.mode, EditorMode::SingleLine { .. }) {
10744            cx.propagate();
10745            return;
10746        }
10747
10748        let Some(row_count) = self.visible_row_count() else {
10749            return;
10750        };
10751
10752        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
10753
10754        let autoscroll = if action.center_cursor {
10755            Autoscroll::center()
10756        } else {
10757            Autoscroll::fit()
10758        };
10759
10760        let text_layout_details = &self.text_layout_details(window);
10761        self.change_selections(Some(autoscroll), window, cx, |s| {
10762            s.move_with(|map, selection| {
10763                if !selection.is_empty() {
10764                    selection.goal = SelectionGoal::None;
10765                }
10766                let (cursor, goal) = movement::down_by_rows(
10767                    map,
10768                    selection.end,
10769                    row_count,
10770                    selection.goal,
10771                    false,
10772                    text_layout_details,
10773                );
10774                selection.collapse_to(cursor, goal);
10775            });
10776        });
10777    }
10778
10779    pub fn select_down(&mut self, _: &SelectDown, window: &mut Window, cx: &mut Context<Self>) {
10780        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
10781        let text_layout_details = &self.text_layout_details(window);
10782        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10783            s.move_heads_with(|map, head, goal| {
10784                movement::down(map, head, goal, false, text_layout_details)
10785            })
10786        });
10787    }
10788
10789    pub fn context_menu_first(
10790        &mut self,
10791        _: &ContextMenuFirst,
10792        _window: &mut Window,
10793        cx: &mut Context<Self>,
10794    ) {
10795        if let Some(context_menu) = self.context_menu.borrow_mut().as_mut() {
10796            context_menu.select_first(self.completion_provider.as_deref(), cx);
10797        }
10798    }
10799
10800    pub fn context_menu_prev(
10801        &mut self,
10802        _: &ContextMenuPrevious,
10803        _window: &mut Window,
10804        cx: &mut Context<Self>,
10805    ) {
10806        if let Some(context_menu) = self.context_menu.borrow_mut().as_mut() {
10807            context_menu.select_prev(self.completion_provider.as_deref(), cx);
10808        }
10809    }
10810
10811    pub fn context_menu_next(
10812        &mut self,
10813        _: &ContextMenuNext,
10814        _window: &mut Window,
10815        cx: &mut Context<Self>,
10816    ) {
10817        if let Some(context_menu) = self.context_menu.borrow_mut().as_mut() {
10818            context_menu.select_next(self.completion_provider.as_deref(), cx);
10819        }
10820    }
10821
10822    pub fn context_menu_last(
10823        &mut self,
10824        _: &ContextMenuLast,
10825        _window: &mut Window,
10826        cx: &mut Context<Self>,
10827    ) {
10828        if let Some(context_menu) = self.context_menu.borrow_mut().as_mut() {
10829            context_menu.select_last(self.completion_provider.as_deref(), cx);
10830        }
10831    }
10832
10833    pub fn move_to_previous_word_start(
10834        &mut self,
10835        _: &MoveToPreviousWordStart,
10836        window: &mut Window,
10837        cx: &mut Context<Self>,
10838    ) {
10839        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
10840        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10841            s.move_cursors_with(|map, head, _| {
10842                (
10843                    movement::previous_word_start(map, head),
10844                    SelectionGoal::None,
10845                )
10846            });
10847        })
10848    }
10849
10850    pub fn move_to_previous_subword_start(
10851        &mut self,
10852        _: &MoveToPreviousSubwordStart,
10853        window: &mut Window,
10854        cx: &mut Context<Self>,
10855    ) {
10856        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
10857        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10858            s.move_cursors_with(|map, head, _| {
10859                (
10860                    movement::previous_subword_start(map, head),
10861                    SelectionGoal::None,
10862                )
10863            });
10864        })
10865    }
10866
10867    pub fn select_to_previous_word_start(
10868        &mut self,
10869        _: &SelectToPreviousWordStart,
10870        window: &mut Window,
10871        cx: &mut Context<Self>,
10872    ) {
10873        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
10874        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10875            s.move_heads_with(|map, head, _| {
10876                (
10877                    movement::previous_word_start(map, head),
10878                    SelectionGoal::None,
10879                )
10880            });
10881        })
10882    }
10883
10884    pub fn select_to_previous_subword_start(
10885        &mut self,
10886        _: &SelectToPreviousSubwordStart,
10887        window: &mut Window,
10888        cx: &mut Context<Self>,
10889    ) {
10890        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
10891        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10892            s.move_heads_with(|map, head, _| {
10893                (
10894                    movement::previous_subword_start(map, head),
10895                    SelectionGoal::None,
10896                )
10897            });
10898        })
10899    }
10900
10901    pub fn delete_to_previous_word_start(
10902        &mut self,
10903        action: &DeleteToPreviousWordStart,
10904        window: &mut Window,
10905        cx: &mut Context<Self>,
10906    ) {
10907        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
10908        self.transact(window, cx, |this, window, cx| {
10909            this.select_autoclose_pair(window, cx);
10910            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10911                s.move_with(|map, selection| {
10912                    if selection.is_empty() {
10913                        let cursor = if action.ignore_newlines {
10914                            movement::previous_word_start(map, selection.head())
10915                        } else {
10916                            movement::previous_word_start_or_newline(map, selection.head())
10917                        };
10918                        selection.set_head(cursor, SelectionGoal::None);
10919                    }
10920                });
10921            });
10922            this.insert("", window, cx);
10923        });
10924    }
10925
10926    pub fn delete_to_previous_subword_start(
10927        &mut self,
10928        _: &DeleteToPreviousSubwordStart,
10929        window: &mut Window,
10930        cx: &mut Context<Self>,
10931    ) {
10932        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
10933        self.transact(window, cx, |this, window, cx| {
10934            this.select_autoclose_pair(window, cx);
10935            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10936                s.move_with(|map, selection| {
10937                    if selection.is_empty() {
10938                        let cursor = movement::previous_subword_start(map, selection.head());
10939                        selection.set_head(cursor, SelectionGoal::None);
10940                    }
10941                });
10942            });
10943            this.insert("", window, cx);
10944        });
10945    }
10946
10947    pub fn move_to_next_word_end(
10948        &mut self,
10949        _: &MoveToNextWordEnd,
10950        window: &mut Window,
10951        cx: &mut Context<Self>,
10952    ) {
10953        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
10954        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10955            s.move_cursors_with(|map, head, _| {
10956                (movement::next_word_end(map, head), SelectionGoal::None)
10957            });
10958        })
10959    }
10960
10961    pub fn move_to_next_subword_end(
10962        &mut self,
10963        _: &MoveToNextSubwordEnd,
10964        window: &mut Window,
10965        cx: &mut Context<Self>,
10966    ) {
10967        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
10968        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10969            s.move_cursors_with(|map, head, _| {
10970                (movement::next_subword_end(map, head), SelectionGoal::None)
10971            });
10972        })
10973    }
10974
10975    pub fn select_to_next_word_end(
10976        &mut self,
10977        _: &SelectToNextWordEnd,
10978        window: &mut Window,
10979        cx: &mut Context<Self>,
10980    ) {
10981        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
10982        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10983            s.move_heads_with(|map, head, _| {
10984                (movement::next_word_end(map, head), SelectionGoal::None)
10985            });
10986        })
10987    }
10988
10989    pub fn select_to_next_subword_end(
10990        &mut self,
10991        _: &SelectToNextSubwordEnd,
10992        window: &mut Window,
10993        cx: &mut Context<Self>,
10994    ) {
10995        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
10996        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10997            s.move_heads_with(|map, head, _| {
10998                (movement::next_subword_end(map, head), SelectionGoal::None)
10999            });
11000        })
11001    }
11002
11003    pub fn delete_to_next_word_end(
11004        &mut self,
11005        action: &DeleteToNextWordEnd,
11006        window: &mut Window,
11007        cx: &mut Context<Self>,
11008    ) {
11009        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
11010        self.transact(window, cx, |this, window, cx| {
11011            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11012                s.move_with(|map, selection| {
11013                    if selection.is_empty() {
11014                        let cursor = if action.ignore_newlines {
11015                            movement::next_word_end(map, selection.head())
11016                        } else {
11017                            movement::next_word_end_or_newline(map, selection.head())
11018                        };
11019                        selection.set_head(cursor, SelectionGoal::None);
11020                    }
11021                });
11022            });
11023            this.insert("", window, cx);
11024        });
11025    }
11026
11027    pub fn delete_to_next_subword_end(
11028        &mut self,
11029        _: &DeleteToNextSubwordEnd,
11030        window: &mut Window,
11031        cx: &mut Context<Self>,
11032    ) {
11033        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
11034        self.transact(window, cx, |this, window, cx| {
11035            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11036                s.move_with(|map, selection| {
11037                    if selection.is_empty() {
11038                        let cursor = movement::next_subword_end(map, selection.head());
11039                        selection.set_head(cursor, SelectionGoal::None);
11040                    }
11041                });
11042            });
11043            this.insert("", window, cx);
11044        });
11045    }
11046
11047    pub fn move_to_beginning_of_line(
11048        &mut self,
11049        action: &MoveToBeginningOfLine,
11050        window: &mut Window,
11051        cx: &mut Context<Self>,
11052    ) {
11053        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11054        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11055            s.move_cursors_with(|map, head, _| {
11056                (
11057                    movement::indented_line_beginning(
11058                        map,
11059                        head,
11060                        action.stop_at_soft_wraps,
11061                        action.stop_at_indent,
11062                    ),
11063                    SelectionGoal::None,
11064                )
11065            });
11066        })
11067    }
11068
11069    pub fn select_to_beginning_of_line(
11070        &mut self,
11071        action: &SelectToBeginningOfLine,
11072        window: &mut Window,
11073        cx: &mut Context<Self>,
11074    ) {
11075        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11076        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11077            s.move_heads_with(|map, head, _| {
11078                (
11079                    movement::indented_line_beginning(
11080                        map,
11081                        head,
11082                        action.stop_at_soft_wraps,
11083                        action.stop_at_indent,
11084                    ),
11085                    SelectionGoal::None,
11086                )
11087            });
11088        });
11089    }
11090
11091    pub fn delete_to_beginning_of_line(
11092        &mut self,
11093        action: &DeleteToBeginningOfLine,
11094        window: &mut Window,
11095        cx: &mut Context<Self>,
11096    ) {
11097        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
11098        self.transact(window, cx, |this, window, cx| {
11099            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11100                s.move_with(|_, selection| {
11101                    selection.reversed = true;
11102                });
11103            });
11104
11105            this.select_to_beginning_of_line(
11106                &SelectToBeginningOfLine {
11107                    stop_at_soft_wraps: false,
11108                    stop_at_indent: action.stop_at_indent,
11109                },
11110                window,
11111                cx,
11112            );
11113            this.backspace(&Backspace, window, cx);
11114        });
11115    }
11116
11117    pub fn move_to_end_of_line(
11118        &mut self,
11119        action: &MoveToEndOfLine,
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_cursors_with(|map, head, _| {
11126                (
11127                    movement::line_end(map, head, action.stop_at_soft_wraps),
11128                    SelectionGoal::None,
11129                )
11130            });
11131        })
11132    }
11133
11134    pub fn select_to_end_of_line(
11135        &mut self,
11136        action: &SelectToEndOfLine,
11137        window: &mut Window,
11138        cx: &mut Context<Self>,
11139    ) {
11140        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11141        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11142            s.move_heads_with(|map, head, _| {
11143                (
11144                    movement::line_end(map, head, action.stop_at_soft_wraps),
11145                    SelectionGoal::None,
11146                )
11147            });
11148        })
11149    }
11150
11151    pub fn delete_to_end_of_line(
11152        &mut self,
11153        _: &DeleteToEndOfLine,
11154        window: &mut Window,
11155        cx: &mut Context<Self>,
11156    ) {
11157        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
11158        self.transact(window, cx, |this, window, cx| {
11159            this.select_to_end_of_line(
11160                &SelectToEndOfLine {
11161                    stop_at_soft_wraps: false,
11162                },
11163                window,
11164                cx,
11165            );
11166            this.delete(&Delete, window, cx);
11167        });
11168    }
11169
11170    pub fn cut_to_end_of_line(
11171        &mut self,
11172        _: &CutToEndOfLine,
11173        window: &mut Window,
11174        cx: &mut Context<Self>,
11175    ) {
11176        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
11177        self.transact(window, cx, |this, window, cx| {
11178            this.select_to_end_of_line(
11179                &SelectToEndOfLine {
11180                    stop_at_soft_wraps: false,
11181                },
11182                window,
11183                cx,
11184            );
11185            this.cut(&Cut, window, cx);
11186        });
11187    }
11188
11189    pub fn move_to_start_of_paragraph(
11190        &mut self,
11191        _: &MoveToStartOfParagraph,
11192        window: &mut Window,
11193        cx: &mut Context<Self>,
11194    ) {
11195        if matches!(self.mode, EditorMode::SingleLine { .. }) {
11196            cx.propagate();
11197            return;
11198        }
11199        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11200        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11201            s.move_with(|map, selection| {
11202                selection.collapse_to(
11203                    movement::start_of_paragraph(map, selection.head(), 1),
11204                    SelectionGoal::None,
11205                )
11206            });
11207        })
11208    }
11209
11210    pub fn move_to_end_of_paragraph(
11211        &mut self,
11212        _: &MoveToEndOfParagraph,
11213        window: &mut Window,
11214        cx: &mut Context<Self>,
11215    ) {
11216        if matches!(self.mode, EditorMode::SingleLine { .. }) {
11217            cx.propagate();
11218            return;
11219        }
11220        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11221        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11222            s.move_with(|map, selection| {
11223                selection.collapse_to(
11224                    movement::end_of_paragraph(map, selection.head(), 1),
11225                    SelectionGoal::None,
11226                )
11227            });
11228        })
11229    }
11230
11231    pub fn select_to_start_of_paragraph(
11232        &mut self,
11233        _: &SelectToStartOfParagraph,
11234        window: &mut Window,
11235        cx: &mut Context<Self>,
11236    ) {
11237        if matches!(self.mode, EditorMode::SingleLine { .. }) {
11238            cx.propagate();
11239            return;
11240        }
11241        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11242        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11243            s.move_heads_with(|map, head, _| {
11244                (
11245                    movement::start_of_paragraph(map, head, 1),
11246                    SelectionGoal::None,
11247                )
11248            });
11249        })
11250    }
11251
11252    pub fn select_to_end_of_paragraph(
11253        &mut self,
11254        _: &SelectToEndOfParagraph,
11255        window: &mut Window,
11256        cx: &mut Context<Self>,
11257    ) {
11258        if matches!(self.mode, EditorMode::SingleLine { .. }) {
11259            cx.propagate();
11260            return;
11261        }
11262        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11263        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11264            s.move_heads_with(|map, head, _| {
11265                (
11266                    movement::end_of_paragraph(map, head, 1),
11267                    SelectionGoal::None,
11268                )
11269            });
11270        })
11271    }
11272
11273    pub fn move_to_start_of_excerpt(
11274        &mut self,
11275        _: &MoveToStartOfExcerpt,
11276        window: &mut Window,
11277        cx: &mut Context<Self>,
11278    ) {
11279        if matches!(self.mode, EditorMode::SingleLine { .. }) {
11280            cx.propagate();
11281            return;
11282        }
11283        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11284        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11285            s.move_with(|map, selection| {
11286                selection.collapse_to(
11287                    movement::start_of_excerpt(
11288                        map,
11289                        selection.head(),
11290                        workspace::searchable::Direction::Prev,
11291                    ),
11292                    SelectionGoal::None,
11293                )
11294            });
11295        })
11296    }
11297
11298    pub fn move_to_start_of_next_excerpt(
11299        &mut self,
11300        _: &MoveToStartOfNextExcerpt,
11301        window: &mut Window,
11302        cx: &mut Context<Self>,
11303    ) {
11304        if matches!(self.mode, EditorMode::SingleLine { .. }) {
11305            cx.propagate();
11306            return;
11307        }
11308
11309        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11310            s.move_with(|map, selection| {
11311                selection.collapse_to(
11312                    movement::start_of_excerpt(
11313                        map,
11314                        selection.head(),
11315                        workspace::searchable::Direction::Next,
11316                    ),
11317                    SelectionGoal::None,
11318                )
11319            });
11320        })
11321    }
11322
11323    pub fn move_to_end_of_excerpt(
11324        &mut self,
11325        _: &MoveToEndOfExcerpt,
11326        window: &mut Window,
11327        cx: &mut Context<Self>,
11328    ) {
11329        if matches!(self.mode, EditorMode::SingleLine { .. }) {
11330            cx.propagate();
11331            return;
11332        }
11333        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11334        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11335            s.move_with(|map, selection| {
11336                selection.collapse_to(
11337                    movement::end_of_excerpt(
11338                        map,
11339                        selection.head(),
11340                        workspace::searchable::Direction::Next,
11341                    ),
11342                    SelectionGoal::None,
11343                )
11344            });
11345        })
11346    }
11347
11348    pub fn move_to_end_of_previous_excerpt(
11349        &mut self,
11350        _: &MoveToEndOfPreviousExcerpt,
11351        window: &mut Window,
11352        cx: &mut Context<Self>,
11353    ) {
11354        if matches!(self.mode, EditorMode::SingleLine { .. }) {
11355            cx.propagate();
11356            return;
11357        }
11358        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11359        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11360            s.move_with(|map, selection| {
11361                selection.collapse_to(
11362                    movement::end_of_excerpt(
11363                        map,
11364                        selection.head(),
11365                        workspace::searchable::Direction::Prev,
11366                    ),
11367                    SelectionGoal::None,
11368                )
11369            });
11370        })
11371    }
11372
11373    pub fn select_to_start_of_excerpt(
11374        &mut self,
11375        _: &SelectToStartOfExcerpt,
11376        window: &mut Window,
11377        cx: &mut Context<Self>,
11378    ) {
11379        if matches!(self.mode, EditorMode::SingleLine { .. }) {
11380            cx.propagate();
11381            return;
11382        }
11383        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11384        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11385            s.move_heads_with(|map, head, _| {
11386                (
11387                    movement::start_of_excerpt(map, head, workspace::searchable::Direction::Prev),
11388                    SelectionGoal::None,
11389                )
11390            });
11391        })
11392    }
11393
11394    pub fn select_to_start_of_next_excerpt(
11395        &mut self,
11396        _: &SelectToStartOfNextExcerpt,
11397        window: &mut Window,
11398        cx: &mut Context<Self>,
11399    ) {
11400        if matches!(self.mode, EditorMode::SingleLine { .. }) {
11401            cx.propagate();
11402            return;
11403        }
11404        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11405        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11406            s.move_heads_with(|map, head, _| {
11407                (
11408                    movement::start_of_excerpt(map, head, workspace::searchable::Direction::Next),
11409                    SelectionGoal::None,
11410                )
11411            });
11412        })
11413    }
11414
11415    pub fn select_to_end_of_excerpt(
11416        &mut self,
11417        _: &SelectToEndOfExcerpt,
11418        window: &mut Window,
11419        cx: &mut Context<Self>,
11420    ) {
11421        if matches!(self.mode, EditorMode::SingleLine { .. }) {
11422            cx.propagate();
11423            return;
11424        }
11425        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11426        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11427            s.move_heads_with(|map, head, _| {
11428                (
11429                    movement::end_of_excerpt(map, head, workspace::searchable::Direction::Next),
11430                    SelectionGoal::None,
11431                )
11432            });
11433        })
11434    }
11435
11436    pub fn select_to_end_of_previous_excerpt(
11437        &mut self,
11438        _: &SelectToEndOfPreviousExcerpt,
11439        window: &mut Window,
11440        cx: &mut Context<Self>,
11441    ) {
11442        if matches!(self.mode, EditorMode::SingleLine { .. }) {
11443            cx.propagate();
11444            return;
11445        }
11446        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11447        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11448            s.move_heads_with(|map, head, _| {
11449                (
11450                    movement::end_of_excerpt(map, head, workspace::searchable::Direction::Prev),
11451                    SelectionGoal::None,
11452                )
11453            });
11454        })
11455    }
11456
11457    pub fn move_to_beginning(
11458        &mut self,
11459        _: &MoveToBeginning,
11460        window: &mut Window,
11461        cx: &mut Context<Self>,
11462    ) {
11463        if matches!(self.mode, EditorMode::SingleLine { .. }) {
11464            cx.propagate();
11465            return;
11466        }
11467        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11468        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11469            s.select_ranges(vec![0..0]);
11470        });
11471    }
11472
11473    pub fn select_to_beginning(
11474        &mut self,
11475        _: &SelectToBeginning,
11476        window: &mut Window,
11477        cx: &mut Context<Self>,
11478    ) {
11479        let mut selection = self.selections.last::<Point>(cx);
11480        selection.set_head(Point::zero(), SelectionGoal::None);
11481        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11482        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11483            s.select(vec![selection]);
11484        });
11485    }
11486
11487    pub fn move_to_end(&mut self, _: &MoveToEnd, window: &mut Window, cx: &mut Context<Self>) {
11488        if matches!(self.mode, EditorMode::SingleLine { .. }) {
11489            cx.propagate();
11490            return;
11491        }
11492        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11493        let cursor = self.buffer.read(cx).read(cx).len();
11494        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11495            s.select_ranges(vec![cursor..cursor])
11496        });
11497    }
11498
11499    pub fn set_nav_history(&mut self, nav_history: Option<ItemNavHistory>) {
11500        self.nav_history = nav_history;
11501    }
11502
11503    pub fn nav_history(&self) -> Option<&ItemNavHistory> {
11504        self.nav_history.as_ref()
11505    }
11506
11507    pub fn create_nav_history_entry(&mut self, cx: &mut Context<Self>) {
11508        self.push_to_nav_history(self.selections.newest_anchor().head(), None, false, cx);
11509    }
11510
11511    fn push_to_nav_history(
11512        &mut self,
11513        cursor_anchor: Anchor,
11514        new_position: Option<Point>,
11515        is_deactivate: bool,
11516        cx: &mut Context<Self>,
11517    ) {
11518        if let Some(nav_history) = self.nav_history.as_mut() {
11519            let buffer = self.buffer.read(cx).read(cx);
11520            let cursor_position = cursor_anchor.to_point(&buffer);
11521            let scroll_state = self.scroll_manager.anchor();
11522            let scroll_top_row = scroll_state.top_row(&buffer);
11523            drop(buffer);
11524
11525            if let Some(new_position) = new_position {
11526                let row_delta = (new_position.row as i64 - cursor_position.row as i64).abs();
11527                if row_delta < MIN_NAVIGATION_HISTORY_ROW_DELTA {
11528                    return;
11529                }
11530            }
11531
11532            nav_history.push(
11533                Some(NavigationData {
11534                    cursor_anchor,
11535                    cursor_position,
11536                    scroll_anchor: scroll_state,
11537                    scroll_top_row,
11538                }),
11539                cx,
11540            );
11541            cx.emit(EditorEvent::PushedToNavHistory {
11542                anchor: cursor_anchor,
11543                is_deactivate,
11544            })
11545        }
11546    }
11547
11548    pub fn select_to_end(&mut self, _: &SelectToEnd, window: &mut Window, cx: &mut Context<Self>) {
11549        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11550        let buffer = self.buffer.read(cx).snapshot(cx);
11551        let mut selection = self.selections.first::<usize>(cx);
11552        selection.set_head(buffer.len(), SelectionGoal::None);
11553        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11554            s.select(vec![selection]);
11555        });
11556    }
11557
11558    pub fn select_all(&mut self, _: &SelectAll, window: &mut Window, cx: &mut Context<Self>) {
11559        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11560        let end = self.buffer.read(cx).read(cx).len();
11561        self.change_selections(None, window, cx, |s| {
11562            s.select_ranges(vec![0..end]);
11563        });
11564    }
11565
11566    pub fn select_line(&mut self, _: &SelectLine, window: &mut Window, cx: &mut Context<Self>) {
11567        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11568        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
11569        let mut selections = self.selections.all::<Point>(cx);
11570        let max_point = display_map.buffer_snapshot.max_point();
11571        for selection in &mut selections {
11572            let rows = selection.spanned_rows(true, &display_map);
11573            selection.start = Point::new(rows.start.0, 0);
11574            selection.end = cmp::min(max_point, Point::new(rows.end.0, 0));
11575            selection.reversed = false;
11576        }
11577        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11578            s.select(selections);
11579        });
11580    }
11581
11582    pub fn split_selection_into_lines(
11583        &mut self,
11584        _: &SplitSelectionIntoLines,
11585        window: &mut Window,
11586        cx: &mut Context<Self>,
11587    ) {
11588        let selections = self
11589            .selections
11590            .all::<Point>(cx)
11591            .into_iter()
11592            .map(|selection| selection.start..selection.end)
11593            .collect::<Vec<_>>();
11594        self.unfold_ranges(&selections, true, true, cx);
11595
11596        let mut new_selection_ranges = Vec::new();
11597        {
11598            let buffer = self.buffer.read(cx).read(cx);
11599            for selection in selections {
11600                for row in selection.start.row..selection.end.row {
11601                    let cursor = Point::new(row, buffer.line_len(MultiBufferRow(row)));
11602                    new_selection_ranges.push(cursor..cursor);
11603                }
11604
11605                let is_multiline_selection = selection.start.row != selection.end.row;
11606                // Don't insert last one if it's a multi-line selection ending at the start of a line,
11607                // so this action feels more ergonomic when paired with other selection operations
11608                let should_skip_last = is_multiline_selection && selection.end.column == 0;
11609                if !should_skip_last {
11610                    new_selection_ranges.push(selection.end..selection.end);
11611                }
11612            }
11613        }
11614        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11615            s.select_ranges(new_selection_ranges);
11616        });
11617    }
11618
11619    pub fn add_selection_above(
11620        &mut self,
11621        _: &AddSelectionAbove,
11622        window: &mut Window,
11623        cx: &mut Context<Self>,
11624    ) {
11625        self.add_selection(true, window, cx);
11626    }
11627
11628    pub fn add_selection_below(
11629        &mut self,
11630        _: &AddSelectionBelow,
11631        window: &mut Window,
11632        cx: &mut Context<Self>,
11633    ) {
11634        self.add_selection(false, window, cx);
11635    }
11636
11637    fn add_selection(&mut self, above: bool, window: &mut Window, cx: &mut Context<Self>) {
11638        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11639
11640        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
11641        let mut selections = self.selections.all::<Point>(cx);
11642        let text_layout_details = self.text_layout_details(window);
11643        let mut state = self.add_selections_state.take().unwrap_or_else(|| {
11644            let oldest_selection = selections.iter().min_by_key(|s| s.id).unwrap().clone();
11645            let range = oldest_selection.display_range(&display_map).sorted();
11646
11647            let start_x = display_map.x_for_display_point(range.start, &text_layout_details);
11648            let end_x = display_map.x_for_display_point(range.end, &text_layout_details);
11649            let positions = start_x.min(end_x)..start_x.max(end_x);
11650
11651            selections.clear();
11652            let mut stack = Vec::new();
11653            for row in range.start.row().0..=range.end.row().0 {
11654                if let Some(selection) = self.selections.build_columnar_selection(
11655                    &display_map,
11656                    DisplayRow(row),
11657                    &positions,
11658                    oldest_selection.reversed,
11659                    &text_layout_details,
11660                ) {
11661                    stack.push(selection.id);
11662                    selections.push(selection);
11663                }
11664            }
11665
11666            if above {
11667                stack.reverse();
11668            }
11669
11670            AddSelectionsState { above, stack }
11671        });
11672
11673        let last_added_selection = *state.stack.last().unwrap();
11674        let mut new_selections = Vec::new();
11675        if above == state.above {
11676            let end_row = if above {
11677                DisplayRow(0)
11678            } else {
11679                display_map.max_point().row()
11680            };
11681
11682            'outer: for selection in selections {
11683                if selection.id == last_added_selection {
11684                    let range = selection.display_range(&display_map).sorted();
11685                    debug_assert_eq!(range.start.row(), range.end.row());
11686                    let mut row = range.start.row();
11687                    let positions =
11688                        if let SelectionGoal::HorizontalRange { start, end } = selection.goal {
11689                            px(start)..px(end)
11690                        } else {
11691                            let start_x =
11692                                display_map.x_for_display_point(range.start, &text_layout_details);
11693                            let end_x =
11694                                display_map.x_for_display_point(range.end, &text_layout_details);
11695                            start_x.min(end_x)..start_x.max(end_x)
11696                        };
11697
11698                    while row != end_row {
11699                        if above {
11700                            row.0 -= 1;
11701                        } else {
11702                            row.0 += 1;
11703                        }
11704
11705                        if let Some(new_selection) = self.selections.build_columnar_selection(
11706                            &display_map,
11707                            row,
11708                            &positions,
11709                            selection.reversed,
11710                            &text_layout_details,
11711                        ) {
11712                            state.stack.push(new_selection.id);
11713                            if above {
11714                                new_selections.push(new_selection);
11715                                new_selections.push(selection);
11716                            } else {
11717                                new_selections.push(selection);
11718                                new_selections.push(new_selection);
11719                            }
11720
11721                            continue 'outer;
11722                        }
11723                    }
11724                }
11725
11726                new_selections.push(selection);
11727            }
11728        } else {
11729            new_selections = selections;
11730            new_selections.retain(|s| s.id != last_added_selection);
11731            state.stack.pop();
11732        }
11733
11734        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11735            s.select(new_selections);
11736        });
11737        if state.stack.len() > 1 {
11738            self.add_selections_state = Some(state);
11739        }
11740    }
11741
11742    pub fn select_next_match_internal(
11743        &mut self,
11744        display_map: &DisplaySnapshot,
11745        replace_newest: bool,
11746        autoscroll: Option<Autoscroll>,
11747        window: &mut Window,
11748        cx: &mut Context<Self>,
11749    ) -> Result<()> {
11750        fn select_next_match_ranges(
11751            this: &mut Editor,
11752            range: Range<usize>,
11753            replace_newest: bool,
11754            auto_scroll: Option<Autoscroll>,
11755            window: &mut Window,
11756            cx: &mut Context<Editor>,
11757        ) {
11758            this.unfold_ranges(&[range.clone()], false, auto_scroll.is_some(), cx);
11759            this.change_selections(auto_scroll, window, cx, |s| {
11760                if replace_newest {
11761                    s.delete(s.newest_anchor().id);
11762                }
11763                s.insert_range(range.clone());
11764            });
11765        }
11766
11767        let buffer = &display_map.buffer_snapshot;
11768        let mut selections = self.selections.all::<usize>(cx);
11769        if let Some(mut select_next_state) = self.select_next_state.take() {
11770            let query = &select_next_state.query;
11771            if !select_next_state.done {
11772                let first_selection = selections.iter().min_by_key(|s| s.id).unwrap();
11773                let last_selection = selections.iter().max_by_key(|s| s.id).unwrap();
11774                let mut next_selected_range = None;
11775
11776                let bytes_after_last_selection =
11777                    buffer.bytes_in_range(last_selection.end..buffer.len());
11778                let bytes_before_first_selection = buffer.bytes_in_range(0..first_selection.start);
11779                let query_matches = query
11780                    .stream_find_iter(bytes_after_last_selection)
11781                    .map(|result| (last_selection.end, result))
11782                    .chain(
11783                        query
11784                            .stream_find_iter(bytes_before_first_selection)
11785                            .map(|result| (0, result)),
11786                    );
11787
11788                for (start_offset, query_match) in query_matches {
11789                    let query_match = query_match.unwrap(); // can only fail due to I/O
11790                    let offset_range =
11791                        start_offset + query_match.start()..start_offset + query_match.end();
11792                    let display_range = offset_range.start.to_display_point(display_map)
11793                        ..offset_range.end.to_display_point(display_map);
11794
11795                    if !select_next_state.wordwise
11796                        || (!movement::is_inside_word(display_map, display_range.start)
11797                            && !movement::is_inside_word(display_map, display_range.end))
11798                    {
11799                        // TODO: This is n^2, because we might check all the selections
11800                        if !selections
11801                            .iter()
11802                            .any(|selection| selection.range().overlaps(&offset_range))
11803                        {
11804                            next_selected_range = Some(offset_range);
11805                            break;
11806                        }
11807                    }
11808                }
11809
11810                if let Some(next_selected_range) = next_selected_range {
11811                    select_next_match_ranges(
11812                        self,
11813                        next_selected_range,
11814                        replace_newest,
11815                        autoscroll,
11816                        window,
11817                        cx,
11818                    );
11819                } else {
11820                    select_next_state.done = true;
11821                }
11822            }
11823
11824            self.select_next_state = Some(select_next_state);
11825        } else {
11826            let mut only_carets = true;
11827            let mut same_text_selected = true;
11828            let mut selected_text = None;
11829
11830            let mut selections_iter = selections.iter().peekable();
11831            while let Some(selection) = selections_iter.next() {
11832                if selection.start != selection.end {
11833                    only_carets = false;
11834                }
11835
11836                if same_text_selected {
11837                    if selected_text.is_none() {
11838                        selected_text =
11839                            Some(buffer.text_for_range(selection.range()).collect::<String>());
11840                    }
11841
11842                    if let Some(next_selection) = selections_iter.peek() {
11843                        if next_selection.range().len() == selection.range().len() {
11844                            let next_selected_text = buffer
11845                                .text_for_range(next_selection.range())
11846                                .collect::<String>();
11847                            if Some(next_selected_text) != selected_text {
11848                                same_text_selected = false;
11849                                selected_text = None;
11850                            }
11851                        } else {
11852                            same_text_selected = false;
11853                            selected_text = None;
11854                        }
11855                    }
11856                }
11857            }
11858
11859            if only_carets {
11860                for selection in &mut selections {
11861                    let word_range = movement::surrounding_word(
11862                        display_map,
11863                        selection.start.to_display_point(display_map),
11864                    );
11865                    selection.start = word_range.start.to_offset(display_map, Bias::Left);
11866                    selection.end = word_range.end.to_offset(display_map, Bias::Left);
11867                    selection.goal = SelectionGoal::None;
11868                    selection.reversed = false;
11869                    select_next_match_ranges(
11870                        self,
11871                        selection.start..selection.end,
11872                        replace_newest,
11873                        autoscroll,
11874                        window,
11875                        cx,
11876                    );
11877                }
11878
11879                if selections.len() == 1 {
11880                    let selection = selections
11881                        .last()
11882                        .expect("ensured that there's only one selection");
11883                    let query = buffer
11884                        .text_for_range(selection.start..selection.end)
11885                        .collect::<String>();
11886                    let is_empty = query.is_empty();
11887                    let select_state = SelectNextState {
11888                        query: AhoCorasick::new(&[query])?,
11889                        wordwise: true,
11890                        done: is_empty,
11891                    };
11892                    self.select_next_state = Some(select_state);
11893                } else {
11894                    self.select_next_state = None;
11895                }
11896            } else if let Some(selected_text) = selected_text {
11897                self.select_next_state = Some(SelectNextState {
11898                    query: AhoCorasick::new(&[selected_text])?,
11899                    wordwise: false,
11900                    done: false,
11901                });
11902                self.select_next_match_internal(
11903                    display_map,
11904                    replace_newest,
11905                    autoscroll,
11906                    window,
11907                    cx,
11908                )?;
11909            }
11910        }
11911        Ok(())
11912    }
11913
11914    pub fn select_all_matches(
11915        &mut self,
11916        _action: &SelectAllMatches,
11917        window: &mut Window,
11918        cx: &mut Context<Self>,
11919    ) -> Result<()> {
11920        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11921
11922        self.push_to_selection_history();
11923        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
11924
11925        self.select_next_match_internal(&display_map, false, None, window, cx)?;
11926        let Some(select_next_state) = self.select_next_state.as_mut() else {
11927            return Ok(());
11928        };
11929        if select_next_state.done {
11930            return Ok(());
11931        }
11932
11933        let mut new_selections = Vec::new();
11934
11935        let reversed = self.selections.oldest::<usize>(cx).reversed;
11936        let buffer = &display_map.buffer_snapshot;
11937        let query_matches = select_next_state
11938            .query
11939            .stream_find_iter(buffer.bytes_in_range(0..buffer.len()));
11940
11941        for query_match in query_matches.into_iter() {
11942            let query_match = query_match.context("query match for select all action")?; // can only fail due to I/O
11943            let offset_range = if reversed {
11944                query_match.end()..query_match.start()
11945            } else {
11946                query_match.start()..query_match.end()
11947            };
11948            let display_range = offset_range.start.to_display_point(&display_map)
11949                ..offset_range.end.to_display_point(&display_map);
11950
11951            if !select_next_state.wordwise
11952                || (!movement::is_inside_word(&display_map, display_range.start)
11953                    && !movement::is_inside_word(&display_map, display_range.end))
11954            {
11955                new_selections.push(offset_range.start..offset_range.end);
11956            }
11957        }
11958
11959        select_next_state.done = true;
11960        self.unfold_ranges(&new_selections.clone(), false, false, cx);
11961        self.change_selections(None, window, cx, |selections| {
11962            selections.select_ranges(new_selections)
11963        });
11964
11965        Ok(())
11966    }
11967
11968    pub fn select_next(
11969        &mut self,
11970        action: &SelectNext,
11971        window: &mut Window,
11972        cx: &mut Context<Self>,
11973    ) -> Result<()> {
11974        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11975        self.push_to_selection_history();
11976        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
11977        self.select_next_match_internal(
11978            &display_map,
11979            action.replace_newest,
11980            Some(Autoscroll::newest()),
11981            window,
11982            cx,
11983        )?;
11984        Ok(())
11985    }
11986
11987    pub fn select_previous(
11988        &mut self,
11989        action: &SelectPrevious,
11990        window: &mut Window,
11991        cx: &mut Context<Self>,
11992    ) -> Result<()> {
11993        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11994        self.push_to_selection_history();
11995        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
11996        let buffer = &display_map.buffer_snapshot;
11997        let mut selections = self.selections.all::<usize>(cx);
11998        if let Some(mut select_prev_state) = self.select_prev_state.take() {
11999            let query = &select_prev_state.query;
12000            if !select_prev_state.done {
12001                let first_selection = selections.iter().min_by_key(|s| s.id).unwrap();
12002                let last_selection = selections.iter().max_by_key(|s| s.id).unwrap();
12003                let mut next_selected_range = None;
12004                // When we're iterating matches backwards, the oldest match will actually be the furthest one in the buffer.
12005                let bytes_before_last_selection =
12006                    buffer.reversed_bytes_in_range(0..last_selection.start);
12007                let bytes_after_first_selection =
12008                    buffer.reversed_bytes_in_range(first_selection.end..buffer.len());
12009                let query_matches = query
12010                    .stream_find_iter(bytes_before_last_selection)
12011                    .map(|result| (last_selection.start, result))
12012                    .chain(
12013                        query
12014                            .stream_find_iter(bytes_after_first_selection)
12015                            .map(|result| (buffer.len(), result)),
12016                    );
12017                for (end_offset, query_match) in query_matches {
12018                    let query_match = query_match.unwrap(); // can only fail due to I/O
12019                    let offset_range =
12020                        end_offset - query_match.end()..end_offset - query_match.start();
12021                    let display_range = offset_range.start.to_display_point(&display_map)
12022                        ..offset_range.end.to_display_point(&display_map);
12023
12024                    if !select_prev_state.wordwise
12025                        || (!movement::is_inside_word(&display_map, display_range.start)
12026                            && !movement::is_inside_word(&display_map, display_range.end))
12027                    {
12028                        next_selected_range = Some(offset_range);
12029                        break;
12030                    }
12031                }
12032
12033                if let Some(next_selected_range) = next_selected_range {
12034                    self.unfold_ranges(&[next_selected_range.clone()], false, true, cx);
12035                    self.change_selections(Some(Autoscroll::newest()), window, cx, |s| {
12036                        if action.replace_newest {
12037                            s.delete(s.newest_anchor().id);
12038                        }
12039                        s.insert_range(next_selected_range);
12040                    });
12041                } else {
12042                    select_prev_state.done = true;
12043                }
12044            }
12045
12046            self.select_prev_state = Some(select_prev_state);
12047        } else {
12048            let mut only_carets = true;
12049            let mut same_text_selected = true;
12050            let mut selected_text = None;
12051
12052            let mut selections_iter = selections.iter().peekable();
12053            while let Some(selection) = selections_iter.next() {
12054                if selection.start != selection.end {
12055                    only_carets = false;
12056                }
12057
12058                if same_text_selected {
12059                    if selected_text.is_none() {
12060                        selected_text =
12061                            Some(buffer.text_for_range(selection.range()).collect::<String>());
12062                    }
12063
12064                    if let Some(next_selection) = selections_iter.peek() {
12065                        if next_selection.range().len() == selection.range().len() {
12066                            let next_selected_text = buffer
12067                                .text_for_range(next_selection.range())
12068                                .collect::<String>();
12069                            if Some(next_selected_text) != selected_text {
12070                                same_text_selected = false;
12071                                selected_text = None;
12072                            }
12073                        } else {
12074                            same_text_selected = false;
12075                            selected_text = None;
12076                        }
12077                    }
12078                }
12079            }
12080
12081            if only_carets {
12082                for selection in &mut selections {
12083                    let word_range = movement::surrounding_word(
12084                        &display_map,
12085                        selection.start.to_display_point(&display_map),
12086                    );
12087                    selection.start = word_range.start.to_offset(&display_map, Bias::Left);
12088                    selection.end = word_range.end.to_offset(&display_map, Bias::Left);
12089                    selection.goal = SelectionGoal::None;
12090                    selection.reversed = false;
12091                }
12092                if selections.len() == 1 {
12093                    let selection = selections
12094                        .last()
12095                        .expect("ensured that there's only one selection");
12096                    let query = buffer
12097                        .text_for_range(selection.start..selection.end)
12098                        .collect::<String>();
12099                    let is_empty = query.is_empty();
12100                    let select_state = SelectNextState {
12101                        query: AhoCorasick::new(&[query.chars().rev().collect::<String>()])?,
12102                        wordwise: true,
12103                        done: is_empty,
12104                    };
12105                    self.select_prev_state = Some(select_state);
12106                } else {
12107                    self.select_prev_state = None;
12108                }
12109
12110                self.unfold_ranges(
12111                    &selections.iter().map(|s| s.range()).collect::<Vec<_>>(),
12112                    false,
12113                    true,
12114                    cx,
12115                );
12116                self.change_selections(Some(Autoscroll::newest()), window, cx, |s| {
12117                    s.select(selections);
12118                });
12119            } else if let Some(selected_text) = selected_text {
12120                self.select_prev_state = Some(SelectNextState {
12121                    query: AhoCorasick::new(&[selected_text.chars().rev().collect::<String>()])?,
12122                    wordwise: false,
12123                    done: false,
12124                });
12125                self.select_previous(action, window, cx)?;
12126            }
12127        }
12128        Ok(())
12129    }
12130
12131    pub fn find_next_match(
12132        &mut self,
12133        _: &FindNextMatch,
12134        window: &mut Window,
12135        cx: &mut Context<Self>,
12136    ) -> Result<()> {
12137        let selections = self.selections.disjoint_anchors();
12138        match selections.first() {
12139            Some(first) if selections.len() >= 2 => {
12140                self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
12141                    s.select_ranges([first.range()]);
12142                });
12143            }
12144            _ => self.select_next(
12145                &SelectNext {
12146                    replace_newest: true,
12147                },
12148                window,
12149                cx,
12150            )?,
12151        }
12152        Ok(())
12153    }
12154
12155    pub fn find_previous_match(
12156        &mut self,
12157        _: &FindPreviousMatch,
12158        window: &mut Window,
12159        cx: &mut Context<Self>,
12160    ) -> Result<()> {
12161        let selections = self.selections.disjoint_anchors();
12162        match selections.last() {
12163            Some(last) if selections.len() >= 2 => {
12164                self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
12165                    s.select_ranges([last.range()]);
12166                });
12167            }
12168            _ => self.select_previous(
12169                &SelectPrevious {
12170                    replace_newest: true,
12171                },
12172                window,
12173                cx,
12174            )?,
12175        }
12176        Ok(())
12177    }
12178
12179    pub fn toggle_comments(
12180        &mut self,
12181        action: &ToggleComments,
12182        window: &mut Window,
12183        cx: &mut Context<Self>,
12184    ) {
12185        if self.read_only(cx) {
12186            return;
12187        }
12188        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
12189        let text_layout_details = &self.text_layout_details(window);
12190        self.transact(window, cx, |this, window, cx| {
12191            let mut selections = this.selections.all::<MultiBufferPoint>(cx);
12192            let mut edits = Vec::new();
12193            let mut selection_edit_ranges = Vec::new();
12194            let mut last_toggled_row = None;
12195            let snapshot = this.buffer.read(cx).read(cx);
12196            let empty_str: Arc<str> = Arc::default();
12197            let mut suffixes_inserted = Vec::new();
12198            let ignore_indent = action.ignore_indent;
12199
12200            fn comment_prefix_range(
12201                snapshot: &MultiBufferSnapshot,
12202                row: MultiBufferRow,
12203                comment_prefix: &str,
12204                comment_prefix_whitespace: &str,
12205                ignore_indent: bool,
12206            ) -> Range<Point> {
12207                let indent_size = if ignore_indent {
12208                    0
12209                } else {
12210                    snapshot.indent_size_for_line(row).len
12211                };
12212
12213                let start = Point::new(row.0, indent_size);
12214
12215                let mut line_bytes = snapshot
12216                    .bytes_in_range(start..snapshot.max_point())
12217                    .flatten()
12218                    .copied();
12219
12220                // If this line currently begins with the line comment prefix, then record
12221                // the range containing the prefix.
12222                if line_bytes
12223                    .by_ref()
12224                    .take(comment_prefix.len())
12225                    .eq(comment_prefix.bytes())
12226                {
12227                    // Include any whitespace that matches the comment prefix.
12228                    let matching_whitespace_len = line_bytes
12229                        .zip(comment_prefix_whitespace.bytes())
12230                        .take_while(|(a, b)| a == b)
12231                        .count() as u32;
12232                    let end = Point::new(
12233                        start.row,
12234                        start.column + comment_prefix.len() as u32 + matching_whitespace_len,
12235                    );
12236                    start..end
12237                } else {
12238                    start..start
12239                }
12240            }
12241
12242            fn comment_suffix_range(
12243                snapshot: &MultiBufferSnapshot,
12244                row: MultiBufferRow,
12245                comment_suffix: &str,
12246                comment_suffix_has_leading_space: bool,
12247            ) -> Range<Point> {
12248                let end = Point::new(row.0, snapshot.line_len(row));
12249                let suffix_start_column = end.column.saturating_sub(comment_suffix.len() as u32);
12250
12251                let mut line_end_bytes = snapshot
12252                    .bytes_in_range(Point::new(end.row, suffix_start_column.saturating_sub(1))..end)
12253                    .flatten()
12254                    .copied();
12255
12256                let leading_space_len = if suffix_start_column > 0
12257                    && line_end_bytes.next() == Some(b' ')
12258                    && comment_suffix_has_leading_space
12259                {
12260                    1
12261                } else {
12262                    0
12263                };
12264
12265                // If this line currently begins with the line comment prefix, then record
12266                // the range containing the prefix.
12267                if line_end_bytes.by_ref().eq(comment_suffix.bytes()) {
12268                    let start = Point::new(end.row, suffix_start_column - leading_space_len);
12269                    start..end
12270                } else {
12271                    end..end
12272                }
12273            }
12274
12275            // TODO: Handle selections that cross excerpts
12276            for selection in &mut selections {
12277                let start_column = snapshot
12278                    .indent_size_for_line(MultiBufferRow(selection.start.row))
12279                    .len;
12280                let language = if let Some(language) =
12281                    snapshot.language_scope_at(Point::new(selection.start.row, start_column))
12282                {
12283                    language
12284                } else {
12285                    continue;
12286                };
12287
12288                selection_edit_ranges.clear();
12289
12290                // If multiple selections contain a given row, avoid processing that
12291                // row more than once.
12292                let mut start_row = MultiBufferRow(selection.start.row);
12293                if last_toggled_row == Some(start_row) {
12294                    start_row = start_row.next_row();
12295                }
12296                let end_row =
12297                    if selection.end.row > selection.start.row && selection.end.column == 0 {
12298                        MultiBufferRow(selection.end.row - 1)
12299                    } else {
12300                        MultiBufferRow(selection.end.row)
12301                    };
12302                last_toggled_row = Some(end_row);
12303
12304                if start_row > end_row {
12305                    continue;
12306                }
12307
12308                // If the language has line comments, toggle those.
12309                let mut full_comment_prefixes = language.line_comment_prefixes().to_vec();
12310
12311                // If ignore_indent is set, trim spaces from the right side of all full_comment_prefixes
12312                if ignore_indent {
12313                    full_comment_prefixes = full_comment_prefixes
12314                        .into_iter()
12315                        .map(|s| Arc::from(s.trim_end()))
12316                        .collect();
12317                }
12318
12319                if !full_comment_prefixes.is_empty() {
12320                    let first_prefix = full_comment_prefixes
12321                        .first()
12322                        .expect("prefixes is non-empty");
12323                    let prefix_trimmed_lengths = full_comment_prefixes
12324                        .iter()
12325                        .map(|p| p.trim_end_matches(' ').len())
12326                        .collect::<SmallVec<[usize; 4]>>();
12327
12328                    let mut all_selection_lines_are_comments = true;
12329
12330                    for row in start_row.0..=end_row.0 {
12331                        let row = MultiBufferRow(row);
12332                        if start_row < end_row && snapshot.is_line_blank(row) {
12333                            continue;
12334                        }
12335
12336                        let prefix_range = full_comment_prefixes
12337                            .iter()
12338                            .zip(prefix_trimmed_lengths.iter().copied())
12339                            .map(|(prefix, trimmed_prefix_len)| {
12340                                comment_prefix_range(
12341                                    snapshot.deref(),
12342                                    row,
12343                                    &prefix[..trimmed_prefix_len],
12344                                    &prefix[trimmed_prefix_len..],
12345                                    ignore_indent,
12346                                )
12347                            })
12348                            .max_by_key(|range| range.end.column - range.start.column)
12349                            .expect("prefixes is non-empty");
12350
12351                        if prefix_range.is_empty() {
12352                            all_selection_lines_are_comments = false;
12353                        }
12354
12355                        selection_edit_ranges.push(prefix_range);
12356                    }
12357
12358                    if all_selection_lines_are_comments {
12359                        edits.extend(
12360                            selection_edit_ranges
12361                                .iter()
12362                                .cloned()
12363                                .map(|range| (range, empty_str.clone())),
12364                        );
12365                    } else {
12366                        let min_column = selection_edit_ranges
12367                            .iter()
12368                            .map(|range| range.start.column)
12369                            .min()
12370                            .unwrap_or(0);
12371                        edits.extend(selection_edit_ranges.iter().map(|range| {
12372                            let position = Point::new(range.start.row, min_column);
12373                            (position..position, first_prefix.clone())
12374                        }));
12375                    }
12376                } else if let Some((full_comment_prefix, comment_suffix)) =
12377                    language.block_comment_delimiters()
12378                {
12379                    let comment_prefix = full_comment_prefix.trim_end_matches(' ');
12380                    let comment_prefix_whitespace = &full_comment_prefix[comment_prefix.len()..];
12381                    let prefix_range = comment_prefix_range(
12382                        snapshot.deref(),
12383                        start_row,
12384                        comment_prefix,
12385                        comment_prefix_whitespace,
12386                        ignore_indent,
12387                    );
12388                    let suffix_range = comment_suffix_range(
12389                        snapshot.deref(),
12390                        end_row,
12391                        comment_suffix.trim_start_matches(' '),
12392                        comment_suffix.starts_with(' '),
12393                    );
12394
12395                    if prefix_range.is_empty() || suffix_range.is_empty() {
12396                        edits.push((
12397                            prefix_range.start..prefix_range.start,
12398                            full_comment_prefix.clone(),
12399                        ));
12400                        edits.push((suffix_range.end..suffix_range.end, comment_suffix.clone()));
12401                        suffixes_inserted.push((end_row, comment_suffix.len()));
12402                    } else {
12403                        edits.push((prefix_range, empty_str.clone()));
12404                        edits.push((suffix_range, empty_str.clone()));
12405                    }
12406                } else {
12407                    continue;
12408                }
12409            }
12410
12411            drop(snapshot);
12412            this.buffer.update(cx, |buffer, cx| {
12413                buffer.edit(edits, None, cx);
12414            });
12415
12416            // Adjust selections so that they end before any comment suffixes that
12417            // were inserted.
12418            let mut suffixes_inserted = suffixes_inserted.into_iter().peekable();
12419            let mut selections = this.selections.all::<Point>(cx);
12420            let snapshot = this.buffer.read(cx).read(cx);
12421            for selection in &mut selections {
12422                while let Some((row, suffix_len)) = suffixes_inserted.peek().copied() {
12423                    match row.cmp(&MultiBufferRow(selection.end.row)) {
12424                        Ordering::Less => {
12425                            suffixes_inserted.next();
12426                            continue;
12427                        }
12428                        Ordering::Greater => break,
12429                        Ordering::Equal => {
12430                            if selection.end.column == snapshot.line_len(row) {
12431                                if selection.is_empty() {
12432                                    selection.start.column -= suffix_len as u32;
12433                                }
12434                                selection.end.column -= suffix_len as u32;
12435                            }
12436                            break;
12437                        }
12438                    }
12439                }
12440            }
12441
12442            drop(snapshot);
12443            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
12444                s.select(selections)
12445            });
12446
12447            let selections = this.selections.all::<Point>(cx);
12448            let selections_on_single_row = selections.windows(2).all(|selections| {
12449                selections[0].start.row == selections[1].start.row
12450                    && selections[0].end.row == selections[1].end.row
12451                    && selections[0].start.row == selections[0].end.row
12452            });
12453            let selections_selecting = selections
12454                .iter()
12455                .any(|selection| selection.start != selection.end);
12456            let advance_downwards = action.advance_downwards
12457                && selections_on_single_row
12458                && !selections_selecting
12459                && !matches!(this.mode, EditorMode::SingleLine { .. });
12460
12461            if advance_downwards {
12462                let snapshot = this.buffer.read(cx).snapshot(cx);
12463
12464                this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
12465                    s.move_cursors_with(|display_snapshot, display_point, _| {
12466                        let mut point = display_point.to_point(display_snapshot);
12467                        point.row += 1;
12468                        point = snapshot.clip_point(point, Bias::Left);
12469                        let display_point = point.to_display_point(display_snapshot);
12470                        let goal = SelectionGoal::HorizontalPosition(
12471                            display_snapshot
12472                                .x_for_display_point(display_point, text_layout_details)
12473                                .into(),
12474                        );
12475                        (display_point, goal)
12476                    })
12477                });
12478            }
12479        });
12480    }
12481
12482    pub fn select_enclosing_symbol(
12483        &mut self,
12484        _: &SelectEnclosingSymbol,
12485        window: &mut Window,
12486        cx: &mut Context<Self>,
12487    ) {
12488        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
12489
12490        let buffer = self.buffer.read(cx).snapshot(cx);
12491        let old_selections = self.selections.all::<usize>(cx).into_boxed_slice();
12492
12493        fn update_selection(
12494            selection: &Selection<usize>,
12495            buffer_snap: &MultiBufferSnapshot,
12496        ) -> Option<Selection<usize>> {
12497            let cursor = selection.head();
12498            let (_buffer_id, symbols) = buffer_snap.symbols_containing(cursor, None)?;
12499            for symbol in symbols.iter().rev() {
12500                let start = symbol.range.start.to_offset(buffer_snap);
12501                let end = symbol.range.end.to_offset(buffer_snap);
12502                let new_range = start..end;
12503                if start < selection.start || end > selection.end {
12504                    return Some(Selection {
12505                        id: selection.id,
12506                        start: new_range.start,
12507                        end: new_range.end,
12508                        goal: SelectionGoal::None,
12509                        reversed: selection.reversed,
12510                    });
12511                }
12512            }
12513            None
12514        }
12515
12516        let mut selected_larger_symbol = false;
12517        let new_selections = old_selections
12518            .iter()
12519            .map(|selection| match update_selection(selection, &buffer) {
12520                Some(new_selection) => {
12521                    if new_selection.range() != selection.range() {
12522                        selected_larger_symbol = true;
12523                    }
12524                    new_selection
12525                }
12526                None => selection.clone(),
12527            })
12528            .collect::<Vec<_>>();
12529
12530        if selected_larger_symbol {
12531            self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
12532                s.select(new_selections);
12533            });
12534        }
12535    }
12536
12537    pub fn select_larger_syntax_node(
12538        &mut self,
12539        _: &SelectLargerSyntaxNode,
12540        window: &mut Window,
12541        cx: &mut Context<Self>,
12542    ) {
12543        let Some(visible_row_count) = self.visible_row_count() else {
12544            return;
12545        };
12546        let old_selections: Box<[_]> = self.selections.all::<usize>(cx).into();
12547        if old_selections.is_empty() {
12548            return;
12549        }
12550
12551        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
12552
12553        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
12554        let buffer = self.buffer.read(cx).snapshot(cx);
12555
12556        let mut selected_larger_node = false;
12557        let mut new_selections = old_selections
12558            .iter()
12559            .map(|selection| {
12560                let old_range = selection.start..selection.end;
12561
12562                if let Some((node, _)) = buffer.syntax_ancestor(old_range.clone()) {
12563                    // manually select word at selection
12564                    if ["string_content", "inline"].contains(&node.kind()) {
12565                        let word_range = {
12566                            let display_point = buffer
12567                                .offset_to_point(old_range.start)
12568                                .to_display_point(&display_map);
12569                            let Range { start, end } =
12570                                movement::surrounding_word(&display_map, display_point);
12571                            start.to_point(&display_map).to_offset(&buffer)
12572                                ..end.to_point(&display_map).to_offset(&buffer)
12573                        };
12574                        // ignore if word is already selected
12575                        if !word_range.is_empty() && old_range != word_range {
12576                            let last_word_range = {
12577                                let display_point = buffer
12578                                    .offset_to_point(old_range.end)
12579                                    .to_display_point(&display_map);
12580                                let Range { start, end } =
12581                                    movement::surrounding_word(&display_map, display_point);
12582                                start.to_point(&display_map).to_offset(&buffer)
12583                                    ..end.to_point(&display_map).to_offset(&buffer)
12584                            };
12585                            // only select word if start and end point belongs to same word
12586                            if word_range == last_word_range {
12587                                selected_larger_node = true;
12588                                return Selection {
12589                                    id: selection.id,
12590                                    start: word_range.start,
12591                                    end: word_range.end,
12592                                    goal: SelectionGoal::None,
12593                                    reversed: selection.reversed,
12594                                };
12595                            }
12596                        }
12597                    }
12598                }
12599
12600                let mut new_range = old_range.clone();
12601                let mut new_node = None;
12602                while let Some((node, containing_range)) = buffer.syntax_ancestor(new_range.clone())
12603                {
12604                    new_node = Some(node);
12605                    new_range = match containing_range {
12606                        MultiOrSingleBufferOffsetRange::Single(_) => break,
12607                        MultiOrSingleBufferOffsetRange::Multi(range) => range,
12608                    };
12609                    if !display_map.intersects_fold(new_range.start)
12610                        && !display_map.intersects_fold(new_range.end)
12611                    {
12612                        break;
12613                    }
12614                }
12615
12616                if let Some(node) = new_node {
12617                    // Log the ancestor, to support using this action as a way to explore TreeSitter
12618                    // nodes. Parent and grandparent are also logged because this operation will not
12619                    // visit nodes that have the same range as their parent.
12620                    log::info!("Node: {node:?}");
12621                    let parent = node.parent();
12622                    log::info!("Parent: {parent:?}");
12623                    let grandparent = parent.and_then(|x| x.parent());
12624                    log::info!("Grandparent: {grandparent:?}");
12625                }
12626
12627                selected_larger_node |= new_range != old_range;
12628                Selection {
12629                    id: selection.id,
12630                    start: new_range.start,
12631                    end: new_range.end,
12632                    goal: SelectionGoal::None,
12633                    reversed: selection.reversed,
12634                }
12635            })
12636            .collect::<Vec<_>>();
12637
12638        if !selected_larger_node {
12639            return; // don't put this call in the history
12640        }
12641
12642        // scroll based on transformation done to the last selection created by the user
12643        let (last_old, last_new) = old_selections
12644            .last()
12645            .zip(new_selections.last().cloned())
12646            .expect("old_selections isn't empty");
12647
12648        // revert selection
12649        let is_selection_reversed = {
12650            let should_newest_selection_be_reversed = last_old.start != last_new.start;
12651            new_selections.last_mut().expect("checked above").reversed =
12652                should_newest_selection_be_reversed;
12653            should_newest_selection_be_reversed
12654        };
12655
12656        if selected_larger_node {
12657            self.select_syntax_node_history.disable_clearing = true;
12658            self.change_selections(None, window, cx, |s| {
12659                s.select(new_selections.clone());
12660            });
12661            self.select_syntax_node_history.disable_clearing = false;
12662        }
12663
12664        let start_row = last_new.start.to_display_point(&display_map).row().0;
12665        let end_row = last_new.end.to_display_point(&display_map).row().0;
12666        let selection_height = end_row - start_row + 1;
12667        let scroll_margin_rows = self.vertical_scroll_margin() as u32;
12668
12669        let fits_on_the_screen = visible_row_count >= selection_height + scroll_margin_rows * 2;
12670        let scroll_behavior = if fits_on_the_screen {
12671            self.request_autoscroll(Autoscroll::fit(), cx);
12672            SelectSyntaxNodeScrollBehavior::FitSelection
12673        } else if is_selection_reversed {
12674            self.scroll_cursor_top(&ScrollCursorTop, window, cx);
12675            SelectSyntaxNodeScrollBehavior::CursorTop
12676        } else {
12677            self.scroll_cursor_bottom(&ScrollCursorBottom, window, cx);
12678            SelectSyntaxNodeScrollBehavior::CursorBottom
12679        };
12680
12681        self.select_syntax_node_history.push((
12682            old_selections,
12683            scroll_behavior,
12684            is_selection_reversed,
12685        ));
12686    }
12687
12688    pub fn select_smaller_syntax_node(
12689        &mut self,
12690        _: &SelectSmallerSyntaxNode,
12691        window: &mut Window,
12692        cx: &mut Context<Self>,
12693    ) {
12694        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
12695
12696        if let Some((mut selections, scroll_behavior, is_selection_reversed)) =
12697            self.select_syntax_node_history.pop()
12698        {
12699            if let Some(selection) = selections.last_mut() {
12700                selection.reversed = is_selection_reversed;
12701            }
12702
12703            self.select_syntax_node_history.disable_clearing = true;
12704            self.change_selections(None, window, cx, |s| {
12705                s.select(selections.to_vec());
12706            });
12707            self.select_syntax_node_history.disable_clearing = false;
12708
12709            match scroll_behavior {
12710                SelectSyntaxNodeScrollBehavior::CursorTop => {
12711                    self.scroll_cursor_top(&ScrollCursorTop, window, cx);
12712                }
12713                SelectSyntaxNodeScrollBehavior::FitSelection => {
12714                    self.request_autoscroll(Autoscroll::fit(), cx);
12715                }
12716                SelectSyntaxNodeScrollBehavior::CursorBottom => {
12717                    self.scroll_cursor_bottom(&ScrollCursorBottom, window, cx);
12718                }
12719            }
12720        }
12721    }
12722
12723    fn refresh_runnables(&mut self, window: &mut Window, cx: &mut Context<Self>) -> Task<()> {
12724        if !EditorSettings::get_global(cx).gutter.runnables {
12725            self.clear_tasks();
12726            return Task::ready(());
12727        }
12728        let project = self.project.as_ref().map(Entity::downgrade);
12729        let task_sources = self.lsp_task_sources(cx);
12730        cx.spawn_in(window, async move |editor, cx| {
12731            cx.background_executor().timer(UPDATE_DEBOUNCE).await;
12732            let Some(project) = project.and_then(|p| p.upgrade()) else {
12733                return;
12734            };
12735            let Ok(display_snapshot) = editor.update(cx, |this, cx| {
12736                this.display_map.update(cx, |map, cx| map.snapshot(cx))
12737            }) else {
12738                return;
12739            };
12740
12741            let hide_runnables = project
12742                .update(cx, |project, cx| {
12743                    // Do not display any test indicators in non-dev server remote projects.
12744                    project.is_via_collab() && project.ssh_connection_string(cx).is_none()
12745                })
12746                .unwrap_or(true);
12747            if hide_runnables {
12748                return;
12749            }
12750            let new_rows =
12751                cx.background_spawn({
12752                    let snapshot = display_snapshot.clone();
12753                    async move {
12754                        Self::fetch_runnable_ranges(&snapshot, Anchor::min()..Anchor::max())
12755                    }
12756                })
12757                    .await;
12758            let Ok(lsp_tasks) =
12759                cx.update(|_, cx| crate::lsp_tasks(project.clone(), &task_sources, None, cx))
12760            else {
12761                return;
12762            };
12763            let lsp_tasks = lsp_tasks.await;
12764
12765            let Ok(mut lsp_tasks_by_rows) = cx.update(|_, cx| {
12766                lsp_tasks
12767                    .into_iter()
12768                    .flat_map(|(kind, tasks)| {
12769                        tasks.into_iter().filter_map(move |(location, task)| {
12770                            Some((kind.clone(), location?, task))
12771                        })
12772                    })
12773                    .fold(HashMap::default(), |mut acc, (kind, location, task)| {
12774                        let buffer = location.target.buffer;
12775                        let buffer_snapshot = buffer.read(cx).snapshot();
12776                        let offset = display_snapshot.buffer_snapshot.excerpts().find_map(
12777                            |(excerpt_id, snapshot, _)| {
12778                                if snapshot.remote_id() == buffer_snapshot.remote_id() {
12779                                    display_snapshot
12780                                        .buffer_snapshot
12781                                        .anchor_in_excerpt(excerpt_id, location.target.range.start)
12782                                } else {
12783                                    None
12784                                }
12785                            },
12786                        );
12787                        if let Some(offset) = offset {
12788                            let task_buffer_range =
12789                                location.target.range.to_point(&buffer_snapshot);
12790                            let context_buffer_range =
12791                                task_buffer_range.to_offset(&buffer_snapshot);
12792                            let context_range = BufferOffset(context_buffer_range.start)
12793                                ..BufferOffset(context_buffer_range.end);
12794
12795                            acc.entry((buffer_snapshot.remote_id(), task_buffer_range.start.row))
12796                                .or_insert_with(|| RunnableTasks {
12797                                    templates: Vec::new(),
12798                                    offset,
12799                                    column: task_buffer_range.start.column,
12800                                    extra_variables: HashMap::default(),
12801                                    context_range,
12802                                })
12803                                .templates
12804                                .push((kind, task.original_task().clone()));
12805                        }
12806
12807                        acc
12808                    })
12809            }) else {
12810                return;
12811            };
12812
12813            let rows = Self::runnable_rows(project, display_snapshot, new_rows, cx.clone());
12814            editor
12815                .update(cx, |editor, _| {
12816                    editor.clear_tasks();
12817                    for (key, mut value) in rows {
12818                        if let Some(lsp_tasks) = lsp_tasks_by_rows.remove(&key) {
12819                            value.templates.extend(lsp_tasks.templates);
12820                        }
12821
12822                        editor.insert_tasks(key, value);
12823                    }
12824                    for (key, value) in lsp_tasks_by_rows {
12825                        editor.insert_tasks(key, value);
12826                    }
12827                })
12828                .ok();
12829        })
12830    }
12831    fn fetch_runnable_ranges(
12832        snapshot: &DisplaySnapshot,
12833        range: Range<Anchor>,
12834    ) -> Vec<language::RunnableRange> {
12835        snapshot.buffer_snapshot.runnable_ranges(range).collect()
12836    }
12837
12838    fn runnable_rows(
12839        project: Entity<Project>,
12840        snapshot: DisplaySnapshot,
12841        runnable_ranges: Vec<RunnableRange>,
12842        mut cx: AsyncWindowContext,
12843    ) -> Vec<((BufferId, BufferRow), RunnableTasks)> {
12844        runnable_ranges
12845            .into_iter()
12846            .filter_map(|mut runnable| {
12847                let tasks = cx
12848                    .update(|_, cx| Self::templates_with_tags(&project, &mut runnable.runnable, cx))
12849                    .ok()?;
12850                if tasks.is_empty() {
12851                    return None;
12852                }
12853
12854                let point = runnable.run_range.start.to_point(&snapshot.buffer_snapshot);
12855
12856                let row = snapshot
12857                    .buffer_snapshot
12858                    .buffer_line_for_row(MultiBufferRow(point.row))?
12859                    .1
12860                    .start
12861                    .row;
12862
12863                let context_range =
12864                    BufferOffset(runnable.full_range.start)..BufferOffset(runnable.full_range.end);
12865                Some((
12866                    (runnable.buffer_id, row),
12867                    RunnableTasks {
12868                        templates: tasks,
12869                        offset: snapshot
12870                            .buffer_snapshot
12871                            .anchor_before(runnable.run_range.start),
12872                        context_range,
12873                        column: point.column,
12874                        extra_variables: runnable.extra_captures,
12875                    },
12876                ))
12877            })
12878            .collect()
12879    }
12880
12881    fn templates_with_tags(
12882        project: &Entity<Project>,
12883        runnable: &mut Runnable,
12884        cx: &mut App,
12885    ) -> Vec<(TaskSourceKind, TaskTemplate)> {
12886        let (inventory, worktree_id, file) = project.read_with(cx, |project, cx| {
12887            let (worktree_id, file) = project
12888                .buffer_for_id(runnable.buffer, cx)
12889                .and_then(|buffer| buffer.read(cx).file())
12890                .map(|file| (file.worktree_id(cx), file.clone()))
12891                .unzip();
12892
12893            (
12894                project.task_store().read(cx).task_inventory().cloned(),
12895                worktree_id,
12896                file,
12897            )
12898        });
12899
12900        let mut templates_with_tags = mem::take(&mut runnable.tags)
12901            .into_iter()
12902            .flat_map(|RunnableTag(tag)| {
12903                inventory
12904                    .as_ref()
12905                    .into_iter()
12906                    .flat_map(|inventory| {
12907                        inventory.read(cx).list_tasks(
12908                            file.clone(),
12909                            Some(runnable.language.clone()),
12910                            worktree_id,
12911                            cx,
12912                        )
12913                    })
12914                    .filter(move |(_, template)| {
12915                        template.tags.iter().any(|source_tag| source_tag == &tag)
12916                    })
12917            })
12918            .sorted_by_key(|(kind, _)| kind.to_owned())
12919            .collect::<Vec<_>>();
12920        if let Some((leading_tag_source, _)) = templates_with_tags.first() {
12921            // Strongest source wins; if we have worktree tag binding, prefer that to
12922            // global and language bindings;
12923            // if we have a global binding, prefer that to language binding.
12924            let first_mismatch = templates_with_tags
12925                .iter()
12926                .position(|(tag_source, _)| tag_source != leading_tag_source);
12927            if let Some(index) = first_mismatch {
12928                templates_with_tags.truncate(index);
12929            }
12930        }
12931
12932        templates_with_tags
12933    }
12934
12935    pub fn move_to_enclosing_bracket(
12936        &mut self,
12937        _: &MoveToEnclosingBracket,
12938        window: &mut Window,
12939        cx: &mut Context<Self>,
12940    ) {
12941        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
12942        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
12943            s.move_offsets_with(|snapshot, selection| {
12944                let Some(enclosing_bracket_ranges) =
12945                    snapshot.enclosing_bracket_ranges(selection.start..selection.end)
12946                else {
12947                    return;
12948                };
12949
12950                let mut best_length = usize::MAX;
12951                let mut best_inside = false;
12952                let mut best_in_bracket_range = false;
12953                let mut best_destination = None;
12954                for (open, close) in enclosing_bracket_ranges {
12955                    let close = close.to_inclusive();
12956                    let length = close.end() - open.start;
12957                    let inside = selection.start >= open.end && selection.end <= *close.start();
12958                    let in_bracket_range = open.to_inclusive().contains(&selection.head())
12959                        || close.contains(&selection.head());
12960
12961                    // If best is next to a bracket and current isn't, skip
12962                    if !in_bracket_range && best_in_bracket_range {
12963                        continue;
12964                    }
12965
12966                    // Prefer smaller lengths unless best is inside and current isn't
12967                    if length > best_length && (best_inside || !inside) {
12968                        continue;
12969                    }
12970
12971                    best_length = length;
12972                    best_inside = inside;
12973                    best_in_bracket_range = in_bracket_range;
12974                    best_destination = Some(
12975                        if close.contains(&selection.start) && close.contains(&selection.end) {
12976                            if inside { open.end } else { open.start }
12977                        } else if inside {
12978                            *close.start()
12979                        } else {
12980                            *close.end()
12981                        },
12982                    );
12983                }
12984
12985                if let Some(destination) = best_destination {
12986                    selection.collapse_to(destination, SelectionGoal::None);
12987                }
12988            })
12989        });
12990    }
12991
12992    pub fn undo_selection(
12993        &mut self,
12994        _: &UndoSelection,
12995        window: &mut Window,
12996        cx: &mut Context<Self>,
12997    ) {
12998        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
12999        self.end_selection(window, cx);
13000        self.selection_history.mode = SelectionHistoryMode::Undoing;
13001        if let Some(entry) = self.selection_history.undo_stack.pop_back() {
13002            self.change_selections(None, window, cx, |s| {
13003                s.select_anchors(entry.selections.to_vec())
13004            });
13005            self.select_next_state = entry.select_next_state;
13006            self.select_prev_state = entry.select_prev_state;
13007            self.add_selections_state = entry.add_selections_state;
13008            self.request_autoscroll(Autoscroll::newest(), cx);
13009        }
13010        self.selection_history.mode = SelectionHistoryMode::Normal;
13011    }
13012
13013    pub fn redo_selection(
13014        &mut self,
13015        _: &RedoSelection,
13016        window: &mut Window,
13017        cx: &mut Context<Self>,
13018    ) {
13019        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
13020        self.end_selection(window, cx);
13021        self.selection_history.mode = SelectionHistoryMode::Redoing;
13022        if let Some(entry) = self.selection_history.redo_stack.pop_back() {
13023            self.change_selections(None, window, cx, |s| {
13024                s.select_anchors(entry.selections.to_vec())
13025            });
13026            self.select_next_state = entry.select_next_state;
13027            self.select_prev_state = entry.select_prev_state;
13028            self.add_selections_state = entry.add_selections_state;
13029            self.request_autoscroll(Autoscroll::newest(), cx);
13030        }
13031        self.selection_history.mode = SelectionHistoryMode::Normal;
13032    }
13033
13034    pub fn expand_excerpts(
13035        &mut self,
13036        action: &ExpandExcerpts,
13037        _: &mut Window,
13038        cx: &mut Context<Self>,
13039    ) {
13040        self.expand_excerpts_for_direction(action.lines, ExpandExcerptDirection::UpAndDown, cx)
13041    }
13042
13043    pub fn expand_excerpts_down(
13044        &mut self,
13045        action: &ExpandExcerptsDown,
13046        _: &mut Window,
13047        cx: &mut Context<Self>,
13048    ) {
13049        self.expand_excerpts_for_direction(action.lines, ExpandExcerptDirection::Down, cx)
13050    }
13051
13052    pub fn expand_excerpts_up(
13053        &mut self,
13054        action: &ExpandExcerptsUp,
13055        _: &mut Window,
13056        cx: &mut Context<Self>,
13057    ) {
13058        self.expand_excerpts_for_direction(action.lines, ExpandExcerptDirection::Up, cx)
13059    }
13060
13061    pub fn expand_excerpts_for_direction(
13062        &mut self,
13063        lines: u32,
13064        direction: ExpandExcerptDirection,
13065
13066        cx: &mut Context<Self>,
13067    ) {
13068        let selections = self.selections.disjoint_anchors();
13069
13070        let lines = if lines == 0 {
13071            EditorSettings::get_global(cx).expand_excerpt_lines
13072        } else {
13073            lines
13074        };
13075
13076        self.buffer.update(cx, |buffer, cx| {
13077            let snapshot = buffer.snapshot(cx);
13078            let mut excerpt_ids = selections
13079                .iter()
13080                .flat_map(|selection| snapshot.excerpt_ids_for_range(selection.range()))
13081                .collect::<Vec<_>>();
13082            excerpt_ids.sort();
13083            excerpt_ids.dedup();
13084            buffer.expand_excerpts(excerpt_ids, lines, direction, cx)
13085        })
13086    }
13087
13088    pub fn expand_excerpt(
13089        &mut self,
13090        excerpt: ExcerptId,
13091        direction: ExpandExcerptDirection,
13092        window: &mut Window,
13093        cx: &mut Context<Self>,
13094    ) {
13095        let current_scroll_position = self.scroll_position(cx);
13096        let lines_to_expand = EditorSettings::get_global(cx).expand_excerpt_lines;
13097        let mut should_scroll_up = false;
13098
13099        if direction == ExpandExcerptDirection::Down {
13100            let multi_buffer = self.buffer.read(cx);
13101            let snapshot = multi_buffer.snapshot(cx);
13102            if let Some(buffer_id) = snapshot.buffer_id_for_excerpt(excerpt) {
13103                if let Some(buffer) = multi_buffer.buffer(buffer_id) {
13104                    if let Some(excerpt_range) = snapshot.buffer_range_for_excerpt(excerpt) {
13105                        let buffer_snapshot = buffer.read(cx).snapshot();
13106                        let excerpt_end_row =
13107                            Point::from_anchor(&excerpt_range.end, &buffer_snapshot).row;
13108                        let last_row = buffer_snapshot.max_point().row;
13109                        let lines_below = last_row.saturating_sub(excerpt_end_row);
13110                        should_scroll_up = lines_below >= lines_to_expand;
13111                    }
13112                }
13113            }
13114        }
13115
13116        self.buffer.update(cx, |buffer, cx| {
13117            buffer.expand_excerpts([excerpt], lines_to_expand, direction, cx)
13118        });
13119
13120        if should_scroll_up {
13121            let new_scroll_position =
13122                current_scroll_position + gpui::Point::new(0.0, lines_to_expand as f32);
13123            self.set_scroll_position(new_scroll_position, window, cx);
13124        }
13125    }
13126
13127    pub fn go_to_singleton_buffer_point(
13128        &mut self,
13129        point: Point,
13130        window: &mut Window,
13131        cx: &mut Context<Self>,
13132    ) {
13133        self.go_to_singleton_buffer_range(point..point, window, cx);
13134    }
13135
13136    pub fn go_to_singleton_buffer_range(
13137        &mut self,
13138        range: Range<Point>,
13139        window: &mut Window,
13140        cx: &mut Context<Self>,
13141    ) {
13142        let multibuffer = self.buffer().read(cx);
13143        let Some(buffer) = multibuffer.as_singleton() else {
13144            return;
13145        };
13146        let Some(start) = multibuffer.buffer_point_to_anchor(&buffer, range.start, cx) else {
13147            return;
13148        };
13149        let Some(end) = multibuffer.buffer_point_to_anchor(&buffer, range.end, cx) else {
13150            return;
13151        };
13152        self.change_selections(Some(Autoscroll::center()), window, cx, |s| {
13153            s.select_anchor_ranges([start..end])
13154        });
13155    }
13156
13157    pub fn go_to_diagnostic(
13158        &mut self,
13159        _: &GoToDiagnostic,
13160        window: &mut Window,
13161        cx: &mut Context<Self>,
13162    ) {
13163        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
13164        self.go_to_diagnostic_impl(Direction::Next, window, cx)
13165    }
13166
13167    pub fn go_to_prev_diagnostic(
13168        &mut self,
13169        _: &GoToPreviousDiagnostic,
13170        window: &mut Window,
13171        cx: &mut Context<Self>,
13172    ) {
13173        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
13174        self.go_to_diagnostic_impl(Direction::Prev, window, cx)
13175    }
13176
13177    pub fn go_to_diagnostic_impl(
13178        &mut self,
13179        direction: Direction,
13180        window: &mut Window,
13181        cx: &mut Context<Self>,
13182    ) {
13183        let buffer = self.buffer.read(cx).snapshot(cx);
13184        let selection = self.selections.newest::<usize>(cx);
13185
13186        let mut active_group_id = None;
13187        if let ActiveDiagnostic::Group(active_group) = &self.active_diagnostics {
13188            if active_group.active_range.start.to_offset(&buffer) == selection.start {
13189                active_group_id = Some(active_group.group_id);
13190            }
13191        }
13192
13193        fn filtered(
13194            snapshot: EditorSnapshot,
13195            diagnostics: impl Iterator<Item = DiagnosticEntry<usize>>,
13196        ) -> impl Iterator<Item = DiagnosticEntry<usize>> {
13197            diagnostics
13198                .filter(|entry| entry.range.start != entry.range.end)
13199                .filter(|entry| !entry.diagnostic.is_unnecessary)
13200                .filter(move |entry| !snapshot.intersects_fold(entry.range.start))
13201        }
13202
13203        let snapshot = self.snapshot(window, cx);
13204        let before = filtered(
13205            snapshot.clone(),
13206            buffer
13207                .diagnostics_in_range(0..selection.start)
13208                .filter(|entry| entry.range.start <= selection.start),
13209        );
13210        let after = filtered(
13211            snapshot,
13212            buffer
13213                .diagnostics_in_range(selection.start..buffer.len())
13214                .filter(|entry| entry.range.start >= selection.start),
13215        );
13216
13217        let mut found: Option<DiagnosticEntry<usize>> = None;
13218        if direction == Direction::Prev {
13219            'outer: for prev_diagnostics in [before.collect::<Vec<_>>(), after.collect::<Vec<_>>()]
13220            {
13221                for diagnostic in prev_diagnostics.into_iter().rev() {
13222                    if diagnostic.range.start != selection.start
13223                        || active_group_id
13224                            .is_some_and(|active| diagnostic.diagnostic.group_id < active)
13225                    {
13226                        found = Some(diagnostic);
13227                        break 'outer;
13228                    }
13229                }
13230            }
13231        } else {
13232            for diagnostic in after.chain(before) {
13233                if diagnostic.range.start != selection.start
13234                    || active_group_id.is_some_and(|active| diagnostic.diagnostic.group_id > active)
13235                {
13236                    found = Some(diagnostic);
13237                    break;
13238                }
13239            }
13240        }
13241        let Some(next_diagnostic) = found else {
13242            return;
13243        };
13244
13245        let Some(buffer_id) = buffer.anchor_after(next_diagnostic.range.start).buffer_id else {
13246            return;
13247        };
13248        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
13249            s.select_ranges(vec![
13250                next_diagnostic.range.start..next_diagnostic.range.start,
13251            ])
13252        });
13253        self.activate_diagnostics(buffer_id, next_diagnostic, window, cx);
13254        self.refresh_inline_completion(false, true, window, cx);
13255    }
13256
13257    fn go_to_next_hunk(&mut self, _: &GoToHunk, window: &mut Window, cx: &mut Context<Self>) {
13258        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
13259        let snapshot = self.snapshot(window, cx);
13260        let selection = self.selections.newest::<Point>(cx);
13261        self.go_to_hunk_before_or_after_position(
13262            &snapshot,
13263            selection.head(),
13264            Direction::Next,
13265            window,
13266            cx,
13267        );
13268    }
13269
13270    pub fn go_to_hunk_before_or_after_position(
13271        &mut self,
13272        snapshot: &EditorSnapshot,
13273        position: Point,
13274        direction: Direction,
13275        window: &mut Window,
13276        cx: &mut Context<Editor>,
13277    ) {
13278        let row = if direction == Direction::Next {
13279            self.hunk_after_position(snapshot, position)
13280                .map(|hunk| hunk.row_range.start)
13281        } else {
13282            self.hunk_before_position(snapshot, position)
13283        };
13284
13285        if let Some(row) = row {
13286            let destination = Point::new(row.0, 0);
13287            let autoscroll = Autoscroll::center();
13288
13289            self.unfold_ranges(&[destination..destination], false, false, cx);
13290            self.change_selections(Some(autoscroll), window, cx, |s| {
13291                s.select_ranges([destination..destination]);
13292            });
13293        }
13294    }
13295
13296    fn hunk_after_position(
13297        &mut self,
13298        snapshot: &EditorSnapshot,
13299        position: Point,
13300    ) -> Option<MultiBufferDiffHunk> {
13301        snapshot
13302            .buffer_snapshot
13303            .diff_hunks_in_range(position..snapshot.buffer_snapshot.max_point())
13304            .find(|hunk| hunk.row_range.start.0 > position.row)
13305            .or_else(|| {
13306                snapshot
13307                    .buffer_snapshot
13308                    .diff_hunks_in_range(Point::zero()..position)
13309                    .find(|hunk| hunk.row_range.end.0 < position.row)
13310            })
13311    }
13312
13313    fn go_to_prev_hunk(
13314        &mut self,
13315        _: &GoToPreviousHunk,
13316        window: &mut Window,
13317        cx: &mut Context<Self>,
13318    ) {
13319        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
13320        let snapshot = self.snapshot(window, cx);
13321        let selection = self.selections.newest::<Point>(cx);
13322        self.go_to_hunk_before_or_after_position(
13323            &snapshot,
13324            selection.head(),
13325            Direction::Prev,
13326            window,
13327            cx,
13328        );
13329    }
13330
13331    fn hunk_before_position(
13332        &mut self,
13333        snapshot: &EditorSnapshot,
13334        position: Point,
13335    ) -> Option<MultiBufferRow> {
13336        snapshot
13337            .buffer_snapshot
13338            .diff_hunk_before(position)
13339            .or_else(|| snapshot.buffer_snapshot.diff_hunk_before(Point::MAX))
13340    }
13341
13342    fn go_to_next_change(
13343        &mut self,
13344        _: &GoToNextChange,
13345        window: &mut Window,
13346        cx: &mut Context<Self>,
13347    ) {
13348        if let Some(selections) = self
13349            .change_list
13350            .next_change(1, Direction::Next)
13351            .map(|s| s.to_vec())
13352        {
13353            self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
13354                let map = s.display_map();
13355                s.select_display_ranges(selections.iter().map(|a| {
13356                    let point = a.to_display_point(&map);
13357                    point..point
13358                }))
13359            })
13360        }
13361    }
13362
13363    fn go_to_previous_change(
13364        &mut self,
13365        _: &GoToPreviousChange,
13366        window: &mut Window,
13367        cx: &mut Context<Self>,
13368    ) {
13369        if let Some(selections) = self
13370            .change_list
13371            .next_change(1, Direction::Prev)
13372            .map(|s| s.to_vec())
13373        {
13374            self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
13375                let map = s.display_map();
13376                s.select_display_ranges(selections.iter().map(|a| {
13377                    let point = a.to_display_point(&map);
13378                    point..point
13379                }))
13380            })
13381        }
13382    }
13383
13384    fn go_to_line<T: 'static>(
13385        &mut self,
13386        position: Anchor,
13387        highlight_color: Option<Hsla>,
13388        window: &mut Window,
13389        cx: &mut Context<Self>,
13390    ) {
13391        let snapshot = self.snapshot(window, cx).display_snapshot;
13392        let position = position.to_point(&snapshot.buffer_snapshot);
13393        let start = snapshot
13394            .buffer_snapshot
13395            .clip_point(Point::new(position.row, 0), Bias::Left);
13396        let end = start + Point::new(1, 0);
13397        let start = snapshot.buffer_snapshot.anchor_before(start);
13398        let end = snapshot.buffer_snapshot.anchor_before(end);
13399
13400        self.highlight_rows::<T>(
13401            start..end,
13402            highlight_color
13403                .unwrap_or_else(|| cx.theme().colors().editor_highlighted_line_background),
13404            false,
13405            cx,
13406        );
13407        self.request_autoscroll(Autoscroll::center().for_anchor(start), cx);
13408    }
13409
13410    pub fn go_to_definition(
13411        &mut self,
13412        _: &GoToDefinition,
13413        window: &mut Window,
13414        cx: &mut Context<Self>,
13415    ) -> Task<Result<Navigated>> {
13416        let definition =
13417            self.go_to_definition_of_kind(GotoDefinitionKind::Symbol, false, window, cx);
13418        let fallback_strategy = EditorSettings::get_global(cx).go_to_definition_fallback;
13419        cx.spawn_in(window, async move |editor, cx| {
13420            if definition.await? == Navigated::Yes {
13421                return Ok(Navigated::Yes);
13422            }
13423            match fallback_strategy {
13424                GoToDefinitionFallback::None => Ok(Navigated::No),
13425                GoToDefinitionFallback::FindAllReferences => {
13426                    match editor.update_in(cx, |editor, window, cx| {
13427                        editor.find_all_references(&FindAllReferences, window, cx)
13428                    })? {
13429                        Some(references) => references.await,
13430                        None => Ok(Navigated::No),
13431                    }
13432                }
13433            }
13434        })
13435    }
13436
13437    pub fn go_to_declaration(
13438        &mut self,
13439        _: &GoToDeclaration,
13440        window: &mut Window,
13441        cx: &mut Context<Self>,
13442    ) -> Task<Result<Navigated>> {
13443        self.go_to_definition_of_kind(GotoDefinitionKind::Declaration, false, window, cx)
13444    }
13445
13446    pub fn go_to_declaration_split(
13447        &mut self,
13448        _: &GoToDeclaration,
13449        window: &mut Window,
13450        cx: &mut Context<Self>,
13451    ) -> Task<Result<Navigated>> {
13452        self.go_to_definition_of_kind(GotoDefinitionKind::Declaration, true, window, cx)
13453    }
13454
13455    pub fn go_to_implementation(
13456        &mut self,
13457        _: &GoToImplementation,
13458        window: &mut Window,
13459        cx: &mut Context<Self>,
13460    ) -> Task<Result<Navigated>> {
13461        self.go_to_definition_of_kind(GotoDefinitionKind::Implementation, false, window, cx)
13462    }
13463
13464    pub fn go_to_implementation_split(
13465        &mut self,
13466        _: &GoToImplementationSplit,
13467        window: &mut Window,
13468        cx: &mut Context<Self>,
13469    ) -> Task<Result<Navigated>> {
13470        self.go_to_definition_of_kind(GotoDefinitionKind::Implementation, true, window, cx)
13471    }
13472
13473    pub fn go_to_type_definition(
13474        &mut self,
13475        _: &GoToTypeDefinition,
13476        window: &mut Window,
13477        cx: &mut Context<Self>,
13478    ) -> Task<Result<Navigated>> {
13479        self.go_to_definition_of_kind(GotoDefinitionKind::Type, false, window, cx)
13480    }
13481
13482    pub fn go_to_definition_split(
13483        &mut self,
13484        _: &GoToDefinitionSplit,
13485        window: &mut Window,
13486        cx: &mut Context<Self>,
13487    ) -> Task<Result<Navigated>> {
13488        self.go_to_definition_of_kind(GotoDefinitionKind::Symbol, true, window, cx)
13489    }
13490
13491    pub fn go_to_type_definition_split(
13492        &mut self,
13493        _: &GoToTypeDefinitionSplit,
13494        window: &mut Window,
13495        cx: &mut Context<Self>,
13496    ) -> Task<Result<Navigated>> {
13497        self.go_to_definition_of_kind(GotoDefinitionKind::Type, true, window, cx)
13498    }
13499
13500    fn go_to_definition_of_kind(
13501        &mut self,
13502        kind: GotoDefinitionKind,
13503        split: bool,
13504        window: &mut Window,
13505        cx: &mut Context<Self>,
13506    ) -> Task<Result<Navigated>> {
13507        let Some(provider) = self.semantics_provider.clone() else {
13508            return Task::ready(Ok(Navigated::No));
13509        };
13510        let head = self.selections.newest::<usize>(cx).head();
13511        let buffer = self.buffer.read(cx);
13512        let (buffer, head) = if let Some(text_anchor) = buffer.text_anchor_for_position(head, cx) {
13513            text_anchor
13514        } else {
13515            return Task::ready(Ok(Navigated::No));
13516        };
13517
13518        let Some(definitions) = provider.definitions(&buffer, head, kind, cx) else {
13519            return Task::ready(Ok(Navigated::No));
13520        };
13521
13522        cx.spawn_in(window, async move |editor, cx| {
13523            let definitions = definitions.await?;
13524            let navigated = editor
13525                .update_in(cx, |editor, window, cx| {
13526                    editor.navigate_to_hover_links(
13527                        Some(kind),
13528                        definitions
13529                            .into_iter()
13530                            .filter(|location| {
13531                                hover_links::exclude_link_to_position(&buffer, &head, location, cx)
13532                            })
13533                            .map(HoverLink::Text)
13534                            .collect::<Vec<_>>(),
13535                        split,
13536                        window,
13537                        cx,
13538                    )
13539                })?
13540                .await?;
13541            anyhow::Ok(navigated)
13542        })
13543    }
13544
13545    pub fn open_url(&mut self, _: &OpenUrl, window: &mut Window, cx: &mut Context<Self>) {
13546        let selection = self.selections.newest_anchor();
13547        let head = selection.head();
13548        let tail = selection.tail();
13549
13550        let Some((buffer, start_position)) =
13551            self.buffer.read(cx).text_anchor_for_position(head, cx)
13552        else {
13553            return;
13554        };
13555
13556        let end_position = if head != tail {
13557            let Some((_, pos)) = self.buffer.read(cx).text_anchor_for_position(tail, cx) else {
13558                return;
13559            };
13560            Some(pos)
13561        } else {
13562            None
13563        };
13564
13565        let url_finder = cx.spawn_in(window, async move |editor, cx| {
13566            let url = if let Some(end_pos) = end_position {
13567                find_url_from_range(&buffer, start_position..end_pos, cx.clone())
13568            } else {
13569                find_url(&buffer, start_position, cx.clone()).map(|(_, url)| url)
13570            };
13571
13572            if let Some(url) = url {
13573                editor.update(cx, |_, cx| {
13574                    cx.open_url(&url);
13575                })
13576            } else {
13577                Ok(())
13578            }
13579        });
13580
13581        url_finder.detach();
13582    }
13583
13584    pub fn open_selected_filename(
13585        &mut self,
13586        _: &OpenSelectedFilename,
13587        window: &mut Window,
13588        cx: &mut Context<Self>,
13589    ) {
13590        let Some(workspace) = self.workspace() else {
13591            return;
13592        };
13593
13594        let position = self.selections.newest_anchor().head();
13595
13596        let Some((buffer, buffer_position)) =
13597            self.buffer.read(cx).text_anchor_for_position(position, cx)
13598        else {
13599            return;
13600        };
13601
13602        let project = self.project.clone();
13603
13604        cx.spawn_in(window, async move |_, cx| {
13605            let result = find_file(&buffer, project, buffer_position, cx).await;
13606
13607            if let Some((_, path)) = result {
13608                workspace
13609                    .update_in(cx, |workspace, window, cx| {
13610                        workspace.open_resolved_path(path, window, cx)
13611                    })?
13612                    .await?;
13613            }
13614            anyhow::Ok(())
13615        })
13616        .detach();
13617    }
13618
13619    pub(crate) fn navigate_to_hover_links(
13620        &mut self,
13621        kind: Option<GotoDefinitionKind>,
13622        mut definitions: Vec<HoverLink>,
13623        split: bool,
13624        window: &mut Window,
13625        cx: &mut Context<Editor>,
13626    ) -> Task<Result<Navigated>> {
13627        // If there is one definition, just open it directly
13628        if definitions.len() == 1 {
13629            let definition = definitions.pop().unwrap();
13630
13631            enum TargetTaskResult {
13632                Location(Option<Location>),
13633                AlreadyNavigated,
13634            }
13635
13636            let target_task = match definition {
13637                HoverLink::Text(link) => {
13638                    Task::ready(anyhow::Ok(TargetTaskResult::Location(Some(link.target))))
13639                }
13640                HoverLink::InlayHint(lsp_location, server_id) => {
13641                    let computation =
13642                        self.compute_target_location(lsp_location, server_id, window, cx);
13643                    cx.background_spawn(async move {
13644                        let location = computation.await?;
13645                        Ok(TargetTaskResult::Location(location))
13646                    })
13647                }
13648                HoverLink::Url(url) => {
13649                    cx.open_url(&url);
13650                    Task::ready(Ok(TargetTaskResult::AlreadyNavigated))
13651                }
13652                HoverLink::File(path) => {
13653                    if let Some(workspace) = self.workspace() {
13654                        cx.spawn_in(window, async move |_, cx| {
13655                            workspace
13656                                .update_in(cx, |workspace, window, cx| {
13657                                    workspace.open_resolved_path(path, window, cx)
13658                                })?
13659                                .await
13660                                .map(|_| TargetTaskResult::AlreadyNavigated)
13661                        })
13662                    } else {
13663                        Task::ready(Ok(TargetTaskResult::Location(None)))
13664                    }
13665                }
13666            };
13667            cx.spawn_in(window, async move |editor, cx| {
13668                let target = match target_task.await.context("target resolution task")? {
13669                    TargetTaskResult::AlreadyNavigated => return Ok(Navigated::Yes),
13670                    TargetTaskResult::Location(None) => return Ok(Navigated::No),
13671                    TargetTaskResult::Location(Some(target)) => target,
13672                };
13673
13674                editor.update_in(cx, |editor, window, cx| {
13675                    let Some(workspace) = editor.workspace() else {
13676                        return Navigated::No;
13677                    };
13678                    let pane = workspace.read(cx).active_pane().clone();
13679
13680                    let range = target.range.to_point(target.buffer.read(cx));
13681                    let range = editor.range_for_match(&range);
13682                    let range = collapse_multiline_range(range);
13683
13684                    if !split
13685                        && Some(&target.buffer) == editor.buffer.read(cx).as_singleton().as_ref()
13686                    {
13687                        editor.go_to_singleton_buffer_range(range.clone(), window, cx);
13688                    } else {
13689                        window.defer(cx, move |window, cx| {
13690                            let target_editor: Entity<Self> =
13691                                workspace.update(cx, |workspace, cx| {
13692                                    let pane = if split {
13693                                        workspace.adjacent_pane(window, cx)
13694                                    } else {
13695                                        workspace.active_pane().clone()
13696                                    };
13697
13698                                    workspace.open_project_item(
13699                                        pane,
13700                                        target.buffer.clone(),
13701                                        true,
13702                                        true,
13703                                        window,
13704                                        cx,
13705                                    )
13706                                });
13707                            target_editor.update(cx, |target_editor, cx| {
13708                                // When selecting a definition in a different buffer, disable the nav history
13709                                // to avoid creating a history entry at the previous cursor location.
13710                                pane.update(cx, |pane, _| pane.disable_history());
13711                                target_editor.go_to_singleton_buffer_range(range, window, cx);
13712                                pane.update(cx, |pane, _| pane.enable_history());
13713                            });
13714                        });
13715                    }
13716                    Navigated::Yes
13717                })
13718            })
13719        } else if !definitions.is_empty() {
13720            cx.spawn_in(window, async move |editor, cx| {
13721                let (title, location_tasks, workspace) = editor
13722                    .update_in(cx, |editor, window, cx| {
13723                        let tab_kind = match kind {
13724                            Some(GotoDefinitionKind::Implementation) => "Implementations",
13725                            _ => "Definitions",
13726                        };
13727                        let title = definitions
13728                            .iter()
13729                            .find_map(|definition| match definition {
13730                                HoverLink::Text(link) => link.origin.as_ref().map(|origin| {
13731                                    let buffer = origin.buffer.read(cx);
13732                                    format!(
13733                                        "{} for {}",
13734                                        tab_kind,
13735                                        buffer
13736                                            .text_for_range(origin.range.clone())
13737                                            .collect::<String>()
13738                                    )
13739                                }),
13740                                HoverLink::InlayHint(_, _) => None,
13741                                HoverLink::Url(_) => None,
13742                                HoverLink::File(_) => None,
13743                            })
13744                            .unwrap_or(tab_kind.to_string());
13745                        let location_tasks = definitions
13746                            .into_iter()
13747                            .map(|definition| match definition {
13748                                HoverLink::Text(link) => Task::ready(Ok(Some(link.target))),
13749                                HoverLink::InlayHint(lsp_location, server_id) => editor
13750                                    .compute_target_location(lsp_location, server_id, window, cx),
13751                                HoverLink::Url(_) => Task::ready(Ok(None)),
13752                                HoverLink::File(_) => Task::ready(Ok(None)),
13753                            })
13754                            .collect::<Vec<_>>();
13755                        (title, location_tasks, editor.workspace().clone())
13756                    })
13757                    .context("location tasks preparation")?;
13758
13759                let locations = future::join_all(location_tasks)
13760                    .await
13761                    .into_iter()
13762                    .filter_map(|location| location.transpose())
13763                    .collect::<Result<_>>()
13764                    .context("location tasks")?;
13765
13766                let Some(workspace) = workspace else {
13767                    return Ok(Navigated::No);
13768                };
13769                let opened = workspace
13770                    .update_in(cx, |workspace, window, cx| {
13771                        Self::open_locations_in_multibuffer(
13772                            workspace,
13773                            locations,
13774                            title,
13775                            split,
13776                            MultibufferSelectionMode::First,
13777                            window,
13778                            cx,
13779                        )
13780                    })
13781                    .ok();
13782
13783                anyhow::Ok(Navigated::from_bool(opened.is_some()))
13784            })
13785        } else {
13786            Task::ready(Ok(Navigated::No))
13787        }
13788    }
13789
13790    fn compute_target_location(
13791        &self,
13792        lsp_location: lsp::Location,
13793        server_id: LanguageServerId,
13794        window: &mut Window,
13795        cx: &mut Context<Self>,
13796    ) -> Task<anyhow::Result<Option<Location>>> {
13797        let Some(project) = self.project.clone() else {
13798            return Task::ready(Ok(None));
13799        };
13800
13801        cx.spawn_in(window, async move |editor, cx| {
13802            let location_task = editor.update(cx, |_, cx| {
13803                project.update(cx, |project, cx| {
13804                    let language_server_name = project
13805                        .language_server_statuses(cx)
13806                        .find(|(id, _)| server_id == *id)
13807                        .map(|(_, status)| LanguageServerName::from(status.name.as_str()));
13808                    language_server_name.map(|language_server_name| {
13809                        project.open_local_buffer_via_lsp(
13810                            lsp_location.uri.clone(),
13811                            server_id,
13812                            language_server_name,
13813                            cx,
13814                        )
13815                    })
13816                })
13817            })?;
13818            let location = match location_task {
13819                Some(task) => Some({
13820                    let target_buffer_handle = task.await.context("open local buffer")?;
13821                    let range = target_buffer_handle.update(cx, |target_buffer, _| {
13822                        let target_start = target_buffer
13823                            .clip_point_utf16(point_from_lsp(lsp_location.range.start), Bias::Left);
13824                        let target_end = target_buffer
13825                            .clip_point_utf16(point_from_lsp(lsp_location.range.end), Bias::Left);
13826                        target_buffer.anchor_after(target_start)
13827                            ..target_buffer.anchor_before(target_end)
13828                    })?;
13829                    Location {
13830                        buffer: target_buffer_handle,
13831                        range,
13832                    }
13833                }),
13834                None => None,
13835            };
13836            Ok(location)
13837        })
13838    }
13839
13840    pub fn find_all_references(
13841        &mut self,
13842        _: &FindAllReferences,
13843        window: &mut Window,
13844        cx: &mut Context<Self>,
13845    ) -> Option<Task<Result<Navigated>>> {
13846        let selection = self.selections.newest::<usize>(cx);
13847        let multi_buffer = self.buffer.read(cx);
13848        let head = selection.head();
13849
13850        let multi_buffer_snapshot = multi_buffer.snapshot(cx);
13851        let head_anchor = multi_buffer_snapshot.anchor_at(
13852            head,
13853            if head < selection.tail() {
13854                Bias::Right
13855            } else {
13856                Bias::Left
13857            },
13858        );
13859
13860        match self
13861            .find_all_references_task_sources
13862            .binary_search_by(|anchor| anchor.cmp(&head_anchor, &multi_buffer_snapshot))
13863        {
13864            Ok(_) => {
13865                log::info!(
13866                    "Ignoring repeated FindAllReferences invocation with the position of already running task"
13867                );
13868                return None;
13869            }
13870            Err(i) => {
13871                self.find_all_references_task_sources.insert(i, head_anchor);
13872            }
13873        }
13874
13875        let (buffer, head) = multi_buffer.text_anchor_for_position(head, cx)?;
13876        let workspace = self.workspace()?;
13877        let project = workspace.read(cx).project().clone();
13878        let references = project.update(cx, |project, cx| project.references(&buffer, head, cx));
13879        Some(cx.spawn_in(window, async move |editor, cx| {
13880            let _cleanup = cx.on_drop(&editor, move |editor, _| {
13881                if let Ok(i) = editor
13882                    .find_all_references_task_sources
13883                    .binary_search_by(|anchor| anchor.cmp(&head_anchor, &multi_buffer_snapshot))
13884                {
13885                    editor.find_all_references_task_sources.remove(i);
13886                }
13887            });
13888
13889            let locations = references.await?;
13890            if locations.is_empty() {
13891                return anyhow::Ok(Navigated::No);
13892            }
13893
13894            workspace.update_in(cx, |workspace, window, cx| {
13895                let title = locations
13896                    .first()
13897                    .as_ref()
13898                    .map(|location| {
13899                        let buffer = location.buffer.read(cx);
13900                        format!(
13901                            "References to `{}`",
13902                            buffer
13903                                .text_for_range(location.range.clone())
13904                                .collect::<String>()
13905                        )
13906                    })
13907                    .unwrap();
13908                Self::open_locations_in_multibuffer(
13909                    workspace,
13910                    locations,
13911                    title,
13912                    false,
13913                    MultibufferSelectionMode::First,
13914                    window,
13915                    cx,
13916                );
13917                Navigated::Yes
13918            })
13919        }))
13920    }
13921
13922    /// Opens a multibuffer with the given project locations in it
13923    pub fn open_locations_in_multibuffer(
13924        workspace: &mut Workspace,
13925        mut locations: Vec<Location>,
13926        title: String,
13927        split: bool,
13928        multibuffer_selection_mode: MultibufferSelectionMode,
13929        window: &mut Window,
13930        cx: &mut Context<Workspace>,
13931    ) {
13932        // If there are multiple definitions, open them in a multibuffer
13933        locations.sort_by_key(|location| location.buffer.read(cx).remote_id());
13934        let mut locations = locations.into_iter().peekable();
13935        let mut ranges: Vec<Range<Anchor>> = Vec::new();
13936        let capability = workspace.project().read(cx).capability();
13937
13938        let excerpt_buffer = cx.new(|cx| {
13939            let mut multibuffer = MultiBuffer::new(capability);
13940            while let Some(location) = locations.next() {
13941                let buffer = location.buffer.read(cx);
13942                let mut ranges_for_buffer = Vec::new();
13943                let range = location.range.to_point(buffer);
13944                ranges_for_buffer.push(range.clone());
13945
13946                while let Some(next_location) = locations.peek() {
13947                    if next_location.buffer == location.buffer {
13948                        ranges_for_buffer.push(next_location.range.to_point(buffer));
13949                        locations.next();
13950                    } else {
13951                        break;
13952                    }
13953                }
13954
13955                ranges_for_buffer.sort_by_key(|range| (range.start, Reverse(range.end)));
13956                let (new_ranges, _) = multibuffer.set_excerpts_for_path(
13957                    PathKey::for_buffer(&location.buffer, cx),
13958                    location.buffer.clone(),
13959                    ranges_for_buffer,
13960                    DEFAULT_MULTIBUFFER_CONTEXT,
13961                    cx,
13962                );
13963                ranges.extend(new_ranges)
13964            }
13965
13966            multibuffer.with_title(title)
13967        });
13968
13969        let editor = cx.new(|cx| {
13970            Editor::for_multibuffer(
13971                excerpt_buffer,
13972                Some(workspace.project().clone()),
13973                window,
13974                cx,
13975            )
13976        });
13977        editor.update(cx, |editor, cx| {
13978            match multibuffer_selection_mode {
13979                MultibufferSelectionMode::First => {
13980                    if let Some(first_range) = ranges.first() {
13981                        editor.change_selections(None, window, cx, |selections| {
13982                            selections.clear_disjoint();
13983                            selections.select_anchor_ranges(std::iter::once(first_range.clone()));
13984                        });
13985                    }
13986                    editor.highlight_background::<Self>(
13987                        &ranges,
13988                        |theme| theme.editor_highlighted_line_background,
13989                        cx,
13990                    );
13991                }
13992                MultibufferSelectionMode::All => {
13993                    editor.change_selections(None, window, cx, |selections| {
13994                        selections.clear_disjoint();
13995                        selections.select_anchor_ranges(ranges);
13996                    });
13997                }
13998            }
13999            editor.register_buffers_with_language_servers(cx);
14000        });
14001
14002        let item = Box::new(editor);
14003        let item_id = item.item_id();
14004
14005        if split {
14006            workspace.split_item(SplitDirection::Right, item.clone(), window, cx);
14007        } else {
14008            if PreviewTabsSettings::get_global(cx).enable_preview_from_code_navigation {
14009                let (preview_item_id, preview_item_idx) =
14010                    workspace.active_pane().update(cx, |pane, _| {
14011                        (pane.preview_item_id(), pane.preview_item_idx())
14012                    });
14013
14014                workspace.add_item_to_active_pane(item.clone(), preview_item_idx, true, window, cx);
14015
14016                if let Some(preview_item_id) = preview_item_id {
14017                    workspace.active_pane().update(cx, |pane, cx| {
14018                        pane.remove_item(preview_item_id, false, false, window, cx);
14019                    });
14020                }
14021            } else {
14022                workspace.add_item_to_active_pane(item.clone(), None, true, window, cx);
14023            }
14024        }
14025        workspace.active_pane().update(cx, |pane, cx| {
14026            pane.set_preview_item_id(Some(item_id), cx);
14027        });
14028    }
14029
14030    pub fn rename(
14031        &mut self,
14032        _: &Rename,
14033        window: &mut Window,
14034        cx: &mut Context<Self>,
14035    ) -> Option<Task<Result<()>>> {
14036        use language::ToOffset as _;
14037
14038        let provider = self.semantics_provider.clone()?;
14039        let selection = self.selections.newest_anchor().clone();
14040        let (cursor_buffer, cursor_buffer_position) = self
14041            .buffer
14042            .read(cx)
14043            .text_anchor_for_position(selection.head(), cx)?;
14044        let (tail_buffer, cursor_buffer_position_end) = self
14045            .buffer
14046            .read(cx)
14047            .text_anchor_for_position(selection.tail(), cx)?;
14048        if tail_buffer != cursor_buffer {
14049            return None;
14050        }
14051
14052        let snapshot = cursor_buffer.read(cx).snapshot();
14053        let cursor_buffer_offset = cursor_buffer_position.to_offset(&snapshot);
14054        let cursor_buffer_offset_end = cursor_buffer_position_end.to_offset(&snapshot);
14055        let prepare_rename = provider
14056            .range_for_rename(&cursor_buffer, cursor_buffer_position, cx)
14057            .unwrap_or_else(|| Task::ready(Ok(None)));
14058        drop(snapshot);
14059
14060        Some(cx.spawn_in(window, async move |this, cx| {
14061            let rename_range = if let Some(range) = prepare_rename.await? {
14062                Some(range)
14063            } else {
14064                this.update(cx, |this, cx| {
14065                    let buffer = this.buffer.read(cx).snapshot(cx);
14066                    let mut buffer_highlights = this
14067                        .document_highlights_for_position(selection.head(), &buffer)
14068                        .filter(|highlight| {
14069                            highlight.start.excerpt_id == selection.head().excerpt_id
14070                                && highlight.end.excerpt_id == selection.head().excerpt_id
14071                        });
14072                    buffer_highlights
14073                        .next()
14074                        .map(|highlight| highlight.start.text_anchor..highlight.end.text_anchor)
14075                })?
14076            };
14077            if let Some(rename_range) = rename_range {
14078                this.update_in(cx, |this, window, cx| {
14079                    let snapshot = cursor_buffer.read(cx).snapshot();
14080                    let rename_buffer_range = rename_range.to_offset(&snapshot);
14081                    let cursor_offset_in_rename_range =
14082                        cursor_buffer_offset.saturating_sub(rename_buffer_range.start);
14083                    let cursor_offset_in_rename_range_end =
14084                        cursor_buffer_offset_end.saturating_sub(rename_buffer_range.start);
14085
14086                    this.take_rename(false, window, cx);
14087                    let buffer = this.buffer.read(cx).read(cx);
14088                    let cursor_offset = selection.head().to_offset(&buffer);
14089                    let rename_start = cursor_offset.saturating_sub(cursor_offset_in_rename_range);
14090                    let rename_end = rename_start + rename_buffer_range.len();
14091                    let range = buffer.anchor_before(rename_start)..buffer.anchor_after(rename_end);
14092                    let mut old_highlight_id = None;
14093                    let old_name: Arc<str> = buffer
14094                        .chunks(rename_start..rename_end, true)
14095                        .map(|chunk| {
14096                            if old_highlight_id.is_none() {
14097                                old_highlight_id = chunk.syntax_highlight_id;
14098                            }
14099                            chunk.text
14100                        })
14101                        .collect::<String>()
14102                        .into();
14103
14104                    drop(buffer);
14105
14106                    // Position the selection in the rename editor so that it matches the current selection.
14107                    this.show_local_selections = false;
14108                    let rename_editor = cx.new(|cx| {
14109                        let mut editor = Editor::single_line(window, cx);
14110                        editor.buffer.update(cx, |buffer, cx| {
14111                            buffer.edit([(0..0, old_name.clone())], None, cx)
14112                        });
14113                        let rename_selection_range = match cursor_offset_in_rename_range
14114                            .cmp(&cursor_offset_in_rename_range_end)
14115                        {
14116                            Ordering::Equal => {
14117                                editor.select_all(&SelectAll, window, cx);
14118                                return editor;
14119                            }
14120                            Ordering::Less => {
14121                                cursor_offset_in_rename_range..cursor_offset_in_rename_range_end
14122                            }
14123                            Ordering::Greater => {
14124                                cursor_offset_in_rename_range_end..cursor_offset_in_rename_range
14125                            }
14126                        };
14127                        if rename_selection_range.end > old_name.len() {
14128                            editor.select_all(&SelectAll, window, cx);
14129                        } else {
14130                            editor.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
14131                                s.select_ranges([rename_selection_range]);
14132                            });
14133                        }
14134                        editor
14135                    });
14136                    cx.subscribe(&rename_editor, |_, _, e: &EditorEvent, cx| {
14137                        if e == &EditorEvent::Focused {
14138                            cx.emit(EditorEvent::FocusedIn)
14139                        }
14140                    })
14141                    .detach();
14142
14143                    let write_highlights =
14144                        this.clear_background_highlights::<DocumentHighlightWrite>(cx);
14145                    let read_highlights =
14146                        this.clear_background_highlights::<DocumentHighlightRead>(cx);
14147                    let ranges = write_highlights
14148                        .iter()
14149                        .flat_map(|(_, ranges)| ranges.iter())
14150                        .chain(read_highlights.iter().flat_map(|(_, ranges)| ranges.iter()))
14151                        .cloned()
14152                        .collect();
14153
14154                    this.highlight_text::<Rename>(
14155                        ranges,
14156                        HighlightStyle {
14157                            fade_out: Some(0.6),
14158                            ..Default::default()
14159                        },
14160                        cx,
14161                    );
14162                    let rename_focus_handle = rename_editor.focus_handle(cx);
14163                    window.focus(&rename_focus_handle);
14164                    let block_id = this.insert_blocks(
14165                        [BlockProperties {
14166                            style: BlockStyle::Flex,
14167                            placement: BlockPlacement::Below(range.start),
14168                            height: Some(1),
14169                            render: Arc::new({
14170                                let rename_editor = rename_editor.clone();
14171                                move |cx: &mut BlockContext| {
14172                                    let mut text_style = cx.editor_style.text.clone();
14173                                    if let Some(highlight_style) = old_highlight_id
14174                                        .and_then(|h| h.style(&cx.editor_style.syntax))
14175                                    {
14176                                        text_style = text_style.highlight(highlight_style);
14177                                    }
14178                                    div()
14179                                        .block_mouse_down()
14180                                        .pl(cx.anchor_x)
14181                                        .child(EditorElement::new(
14182                                            &rename_editor,
14183                                            EditorStyle {
14184                                                background: cx.theme().system().transparent,
14185                                                local_player: cx.editor_style.local_player,
14186                                                text: text_style,
14187                                                scrollbar_width: cx.editor_style.scrollbar_width,
14188                                                syntax: cx.editor_style.syntax.clone(),
14189                                                status: cx.editor_style.status.clone(),
14190                                                inlay_hints_style: HighlightStyle {
14191                                                    font_weight: Some(FontWeight::BOLD),
14192                                                    ..make_inlay_hints_style(cx.app)
14193                                                },
14194                                                inline_completion_styles: make_suggestion_styles(
14195                                                    cx.app,
14196                                                ),
14197                                                ..EditorStyle::default()
14198                                            },
14199                                        ))
14200                                        .into_any_element()
14201                                }
14202                            }),
14203                            priority: 0,
14204                        }],
14205                        Some(Autoscroll::fit()),
14206                        cx,
14207                    )[0];
14208                    this.pending_rename = Some(RenameState {
14209                        range,
14210                        old_name,
14211                        editor: rename_editor,
14212                        block_id,
14213                    });
14214                })?;
14215            }
14216
14217            Ok(())
14218        }))
14219    }
14220
14221    pub fn confirm_rename(
14222        &mut self,
14223        _: &ConfirmRename,
14224        window: &mut Window,
14225        cx: &mut Context<Self>,
14226    ) -> Option<Task<Result<()>>> {
14227        let rename = self.take_rename(false, window, cx)?;
14228        let workspace = self.workspace()?.downgrade();
14229        let (buffer, start) = self
14230            .buffer
14231            .read(cx)
14232            .text_anchor_for_position(rename.range.start, cx)?;
14233        let (end_buffer, _) = self
14234            .buffer
14235            .read(cx)
14236            .text_anchor_for_position(rename.range.end, cx)?;
14237        if buffer != end_buffer {
14238            return None;
14239        }
14240
14241        let old_name = rename.old_name;
14242        let new_name = rename.editor.read(cx).text(cx);
14243
14244        let rename = self.semantics_provider.as_ref()?.perform_rename(
14245            &buffer,
14246            start,
14247            new_name.clone(),
14248            cx,
14249        )?;
14250
14251        Some(cx.spawn_in(window, async move |editor, cx| {
14252            let project_transaction = rename.await?;
14253            Self::open_project_transaction(
14254                &editor,
14255                workspace,
14256                project_transaction,
14257                format!("Rename: {}{}", old_name, new_name),
14258                cx,
14259            )
14260            .await?;
14261
14262            editor.update(cx, |editor, cx| {
14263                editor.refresh_document_highlights(cx);
14264            })?;
14265            Ok(())
14266        }))
14267    }
14268
14269    fn take_rename(
14270        &mut self,
14271        moving_cursor: bool,
14272        window: &mut Window,
14273        cx: &mut Context<Self>,
14274    ) -> Option<RenameState> {
14275        let rename = self.pending_rename.take()?;
14276        if rename.editor.focus_handle(cx).is_focused(window) {
14277            window.focus(&self.focus_handle);
14278        }
14279
14280        self.remove_blocks(
14281            [rename.block_id].into_iter().collect(),
14282            Some(Autoscroll::fit()),
14283            cx,
14284        );
14285        self.clear_highlights::<Rename>(cx);
14286        self.show_local_selections = true;
14287
14288        if moving_cursor {
14289            let cursor_in_rename_editor = rename.editor.update(cx, |editor, cx| {
14290                editor.selections.newest::<usize>(cx).head()
14291            });
14292
14293            // Update the selection to match the position of the selection inside
14294            // the rename editor.
14295            let snapshot = self.buffer.read(cx).read(cx);
14296            let rename_range = rename.range.to_offset(&snapshot);
14297            let cursor_in_editor = snapshot
14298                .clip_offset(rename_range.start + cursor_in_rename_editor, Bias::Left)
14299                .min(rename_range.end);
14300            drop(snapshot);
14301
14302            self.change_selections(None, window, cx, |s| {
14303                s.select_ranges(vec![cursor_in_editor..cursor_in_editor])
14304            });
14305        } else {
14306            self.refresh_document_highlights(cx);
14307        }
14308
14309        Some(rename)
14310    }
14311
14312    pub fn pending_rename(&self) -> Option<&RenameState> {
14313        self.pending_rename.as_ref()
14314    }
14315
14316    fn format(
14317        &mut self,
14318        _: &Format,
14319        window: &mut Window,
14320        cx: &mut Context<Self>,
14321    ) -> Option<Task<Result<()>>> {
14322        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
14323
14324        let project = match &self.project {
14325            Some(project) => project.clone(),
14326            None => return None,
14327        };
14328
14329        Some(self.perform_format(
14330            project,
14331            FormatTrigger::Manual,
14332            FormatTarget::Buffers,
14333            window,
14334            cx,
14335        ))
14336    }
14337
14338    fn format_selections(
14339        &mut self,
14340        _: &FormatSelections,
14341        window: &mut Window,
14342        cx: &mut Context<Self>,
14343    ) -> Option<Task<Result<()>>> {
14344        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
14345
14346        let project = match &self.project {
14347            Some(project) => project.clone(),
14348            None => return None,
14349        };
14350
14351        let ranges = self
14352            .selections
14353            .all_adjusted(cx)
14354            .into_iter()
14355            .map(|selection| selection.range())
14356            .collect_vec();
14357
14358        Some(self.perform_format(
14359            project,
14360            FormatTrigger::Manual,
14361            FormatTarget::Ranges(ranges),
14362            window,
14363            cx,
14364        ))
14365    }
14366
14367    fn perform_format(
14368        &mut self,
14369        project: Entity<Project>,
14370        trigger: FormatTrigger,
14371        target: FormatTarget,
14372        window: &mut Window,
14373        cx: &mut Context<Self>,
14374    ) -> Task<Result<()>> {
14375        let buffer = self.buffer.clone();
14376        let (buffers, target) = match target {
14377            FormatTarget::Buffers => {
14378                let mut buffers = buffer.read(cx).all_buffers();
14379                if trigger == FormatTrigger::Save {
14380                    buffers.retain(|buffer| buffer.read(cx).is_dirty());
14381                }
14382                (buffers, LspFormatTarget::Buffers)
14383            }
14384            FormatTarget::Ranges(selection_ranges) => {
14385                let multi_buffer = buffer.read(cx);
14386                let snapshot = multi_buffer.read(cx);
14387                let mut buffers = HashSet::default();
14388                let mut buffer_id_to_ranges: BTreeMap<BufferId, Vec<Range<text::Anchor>>> =
14389                    BTreeMap::new();
14390                for selection_range in selection_ranges {
14391                    for (buffer, buffer_range, _) in
14392                        snapshot.range_to_buffer_ranges(selection_range)
14393                    {
14394                        let buffer_id = buffer.remote_id();
14395                        let start = buffer.anchor_before(buffer_range.start);
14396                        let end = buffer.anchor_after(buffer_range.end);
14397                        buffers.insert(multi_buffer.buffer(buffer_id).unwrap());
14398                        buffer_id_to_ranges
14399                            .entry(buffer_id)
14400                            .and_modify(|buffer_ranges| buffer_ranges.push(start..end))
14401                            .or_insert_with(|| vec![start..end]);
14402                    }
14403                }
14404                (buffers, LspFormatTarget::Ranges(buffer_id_to_ranges))
14405            }
14406        };
14407
14408        let transaction_id_prev = buffer.read_with(cx, |b, cx| b.last_transaction_id(cx));
14409        let selections_prev = transaction_id_prev
14410            .and_then(|transaction_id_prev| {
14411                // default to selections as they were after the last edit, if we have them,
14412                // instead of how they are now.
14413                // This will make it so that editing, moving somewhere else, formatting, then undoing the format
14414                // will take you back to where you made the last edit, instead of staying where you scrolled
14415                self.selection_history
14416                    .transaction(transaction_id_prev)
14417                    .map(|t| t.0.clone())
14418            })
14419            .unwrap_or_else(|| {
14420                log::info!("Failed to determine selections from before format. Falling back to selections when format was initiated");
14421                self.selections.disjoint_anchors()
14422            });
14423
14424        let mut timeout = cx.background_executor().timer(FORMAT_TIMEOUT).fuse();
14425        let format = project.update(cx, |project, cx| {
14426            project.format(buffers, target, true, trigger, cx)
14427        });
14428
14429        cx.spawn_in(window, async move |editor, cx| {
14430            let transaction = futures::select_biased! {
14431                transaction = format.log_err().fuse() => transaction,
14432                () = timeout => {
14433                    log::warn!("timed out waiting for formatting");
14434                    None
14435                }
14436            };
14437
14438            buffer
14439                .update(cx, |buffer, cx| {
14440                    if let Some(transaction) = transaction {
14441                        if !buffer.is_singleton() {
14442                            buffer.push_transaction(&transaction.0, cx);
14443                        }
14444                    }
14445                    cx.notify();
14446                })
14447                .ok();
14448
14449            if let Some(transaction_id_now) =
14450                buffer.read_with(cx, |b, cx| b.last_transaction_id(cx))?
14451            {
14452                let has_new_transaction = transaction_id_prev != Some(transaction_id_now);
14453                if has_new_transaction {
14454                    _ = editor.update(cx, |editor, _| {
14455                        editor
14456                            .selection_history
14457                            .insert_transaction(transaction_id_now, selections_prev);
14458                    });
14459                }
14460            }
14461
14462            Ok(())
14463        })
14464    }
14465
14466    fn organize_imports(
14467        &mut self,
14468        _: &OrganizeImports,
14469        window: &mut Window,
14470        cx: &mut Context<Self>,
14471    ) -> Option<Task<Result<()>>> {
14472        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
14473        let project = match &self.project {
14474            Some(project) => project.clone(),
14475            None => return None,
14476        };
14477        Some(self.perform_code_action_kind(
14478            project,
14479            CodeActionKind::SOURCE_ORGANIZE_IMPORTS,
14480            window,
14481            cx,
14482        ))
14483    }
14484
14485    fn perform_code_action_kind(
14486        &mut self,
14487        project: Entity<Project>,
14488        kind: CodeActionKind,
14489        window: &mut Window,
14490        cx: &mut Context<Self>,
14491    ) -> Task<Result<()>> {
14492        let buffer = self.buffer.clone();
14493        let buffers = buffer.read(cx).all_buffers();
14494        let mut timeout = cx.background_executor().timer(CODE_ACTION_TIMEOUT).fuse();
14495        let apply_action = project.update(cx, |project, cx| {
14496            project.apply_code_action_kind(buffers, kind, true, cx)
14497        });
14498        cx.spawn_in(window, async move |_, cx| {
14499            let transaction = futures::select_biased! {
14500                () = timeout => {
14501                    log::warn!("timed out waiting for executing code action");
14502                    None
14503                }
14504                transaction = apply_action.log_err().fuse() => transaction,
14505            };
14506            buffer
14507                .update(cx, |buffer, cx| {
14508                    // check if we need this
14509                    if let Some(transaction) = transaction {
14510                        if !buffer.is_singleton() {
14511                            buffer.push_transaction(&transaction.0, cx);
14512                        }
14513                    }
14514                    cx.notify();
14515                })
14516                .ok();
14517            Ok(())
14518        })
14519    }
14520
14521    fn restart_language_server(
14522        &mut self,
14523        _: &RestartLanguageServer,
14524        _: &mut Window,
14525        cx: &mut Context<Self>,
14526    ) {
14527        if let Some(project) = self.project.clone() {
14528            self.buffer.update(cx, |multi_buffer, cx| {
14529                project.update(cx, |project, cx| {
14530                    project.restart_language_servers_for_buffers(
14531                        multi_buffer.all_buffers().into_iter().collect(),
14532                        cx,
14533                    );
14534                });
14535            })
14536        }
14537    }
14538
14539    fn stop_language_server(
14540        &mut self,
14541        _: &StopLanguageServer,
14542        _: &mut Window,
14543        cx: &mut Context<Self>,
14544    ) {
14545        if let Some(project) = self.project.clone() {
14546            self.buffer.update(cx, |multi_buffer, cx| {
14547                project.update(cx, |project, cx| {
14548                    project.stop_language_servers_for_buffers(
14549                        multi_buffer.all_buffers().into_iter().collect(),
14550                        cx,
14551                    );
14552                    cx.emit(project::Event::RefreshInlayHints);
14553                });
14554            });
14555        }
14556    }
14557
14558    fn cancel_language_server_work(
14559        workspace: &mut Workspace,
14560        _: &actions::CancelLanguageServerWork,
14561        _: &mut Window,
14562        cx: &mut Context<Workspace>,
14563    ) {
14564        let project = workspace.project();
14565        let buffers = workspace
14566            .active_item(cx)
14567            .and_then(|item| item.act_as::<Editor>(cx))
14568            .map_or(HashSet::default(), |editor| {
14569                editor.read(cx).buffer.read(cx).all_buffers()
14570            });
14571        project.update(cx, |project, cx| {
14572            project.cancel_language_server_work_for_buffers(buffers, cx);
14573        });
14574    }
14575
14576    fn show_character_palette(
14577        &mut self,
14578        _: &ShowCharacterPalette,
14579        window: &mut Window,
14580        _: &mut Context<Self>,
14581    ) {
14582        window.show_character_palette();
14583    }
14584
14585    fn refresh_active_diagnostics(&mut self, cx: &mut Context<Editor>) {
14586        if let ActiveDiagnostic::Group(active_diagnostics) = &mut self.active_diagnostics {
14587            let buffer = self.buffer.read(cx).snapshot(cx);
14588            let primary_range_start = active_diagnostics.active_range.start.to_offset(&buffer);
14589            let primary_range_end = active_diagnostics.active_range.end.to_offset(&buffer);
14590            let is_valid = buffer
14591                .diagnostics_in_range::<usize>(primary_range_start..primary_range_end)
14592                .any(|entry| {
14593                    entry.diagnostic.is_primary
14594                        && !entry.range.is_empty()
14595                        && entry.range.start == primary_range_start
14596                        && entry.diagnostic.message == active_diagnostics.active_message
14597                });
14598
14599            if !is_valid {
14600                self.dismiss_diagnostics(cx);
14601            }
14602        }
14603    }
14604
14605    pub fn active_diagnostic_group(&self) -> Option<&ActiveDiagnosticGroup> {
14606        match &self.active_diagnostics {
14607            ActiveDiagnostic::Group(group) => Some(group),
14608            _ => None,
14609        }
14610    }
14611
14612    pub fn set_all_diagnostics_active(&mut self, cx: &mut Context<Self>) {
14613        self.dismiss_diagnostics(cx);
14614        self.active_diagnostics = ActiveDiagnostic::All;
14615    }
14616
14617    fn activate_diagnostics(
14618        &mut self,
14619        buffer_id: BufferId,
14620        diagnostic: DiagnosticEntry<usize>,
14621        window: &mut Window,
14622        cx: &mut Context<Self>,
14623    ) {
14624        if matches!(self.active_diagnostics, ActiveDiagnostic::All) {
14625            return;
14626        }
14627        self.dismiss_diagnostics(cx);
14628        let snapshot = self.snapshot(window, cx);
14629        let Some(diagnostic_renderer) = cx
14630            .try_global::<GlobalDiagnosticRenderer>()
14631            .map(|g| g.0.clone())
14632        else {
14633            return;
14634        };
14635        let buffer = self.buffer.read(cx).snapshot(cx);
14636
14637        let diagnostic_group = buffer
14638            .diagnostic_group(buffer_id, diagnostic.diagnostic.group_id)
14639            .collect::<Vec<_>>();
14640
14641        let blocks = diagnostic_renderer.render_group(
14642            diagnostic_group,
14643            buffer_id,
14644            snapshot,
14645            cx.weak_entity(),
14646            cx,
14647        );
14648
14649        let blocks = self.display_map.update(cx, |display_map, cx| {
14650            display_map.insert_blocks(blocks, cx).into_iter().collect()
14651        });
14652        self.active_diagnostics = ActiveDiagnostic::Group(ActiveDiagnosticGroup {
14653            active_range: buffer.anchor_before(diagnostic.range.start)
14654                ..buffer.anchor_after(diagnostic.range.end),
14655            active_message: diagnostic.diagnostic.message.clone(),
14656            group_id: diagnostic.diagnostic.group_id,
14657            blocks,
14658        });
14659        cx.notify();
14660    }
14661
14662    fn dismiss_diagnostics(&mut self, cx: &mut Context<Self>) {
14663        if matches!(self.active_diagnostics, ActiveDiagnostic::All) {
14664            return;
14665        };
14666
14667        let prev = mem::replace(&mut self.active_diagnostics, ActiveDiagnostic::None);
14668        if let ActiveDiagnostic::Group(group) = prev {
14669            self.display_map.update(cx, |display_map, cx| {
14670                display_map.remove_blocks(group.blocks, cx);
14671            });
14672            cx.notify();
14673        }
14674    }
14675
14676    /// Disable inline diagnostics rendering for this editor.
14677    pub fn disable_inline_diagnostics(&mut self) {
14678        self.inline_diagnostics_enabled = false;
14679        self.inline_diagnostics_update = Task::ready(());
14680        self.inline_diagnostics.clear();
14681    }
14682
14683    pub fn inline_diagnostics_enabled(&self) -> bool {
14684        self.inline_diagnostics_enabled
14685    }
14686
14687    pub fn show_inline_diagnostics(&self) -> bool {
14688        self.show_inline_diagnostics
14689    }
14690
14691    pub fn toggle_inline_diagnostics(
14692        &mut self,
14693        _: &ToggleInlineDiagnostics,
14694        window: &mut Window,
14695        cx: &mut Context<Editor>,
14696    ) {
14697        self.show_inline_diagnostics = !self.show_inline_diagnostics;
14698        self.refresh_inline_diagnostics(false, window, cx);
14699    }
14700
14701    fn refresh_inline_diagnostics(
14702        &mut self,
14703        debounce: bool,
14704        window: &mut Window,
14705        cx: &mut Context<Self>,
14706    ) {
14707        if !self.inline_diagnostics_enabled || !self.show_inline_diagnostics {
14708            self.inline_diagnostics_update = Task::ready(());
14709            self.inline_diagnostics.clear();
14710            return;
14711        }
14712
14713        let debounce_ms = ProjectSettings::get_global(cx)
14714            .diagnostics
14715            .inline
14716            .update_debounce_ms;
14717        let debounce = if debounce && debounce_ms > 0 {
14718            Some(Duration::from_millis(debounce_ms))
14719        } else {
14720            None
14721        };
14722        self.inline_diagnostics_update = cx.spawn_in(window, async move |editor, cx| {
14723            let editor = editor.upgrade().unwrap();
14724
14725            if let Some(debounce) = debounce {
14726                cx.background_executor().timer(debounce).await;
14727            }
14728            let Some(snapshot) = editor
14729                .update(cx, |editor, cx| editor.buffer().read(cx).snapshot(cx))
14730                .ok()
14731            else {
14732                return;
14733            };
14734
14735            let new_inline_diagnostics = cx
14736                .background_spawn(async move {
14737                    let mut inline_diagnostics = Vec::<(Anchor, InlineDiagnostic)>::new();
14738                    for diagnostic_entry in snapshot.diagnostics_in_range(0..snapshot.len()) {
14739                        let message = diagnostic_entry
14740                            .diagnostic
14741                            .message
14742                            .split_once('\n')
14743                            .map(|(line, _)| line)
14744                            .map(SharedString::new)
14745                            .unwrap_or_else(|| {
14746                                SharedString::from(diagnostic_entry.diagnostic.message)
14747                            });
14748                        let start_anchor = snapshot.anchor_before(diagnostic_entry.range.start);
14749                        let (Ok(i) | Err(i)) = inline_diagnostics
14750                            .binary_search_by(|(probe, _)| probe.cmp(&start_anchor, &snapshot));
14751                        inline_diagnostics.insert(
14752                            i,
14753                            (
14754                                start_anchor,
14755                                InlineDiagnostic {
14756                                    message,
14757                                    group_id: diagnostic_entry.diagnostic.group_id,
14758                                    start: diagnostic_entry.range.start.to_point(&snapshot),
14759                                    is_primary: diagnostic_entry.diagnostic.is_primary,
14760                                    severity: diagnostic_entry.diagnostic.severity,
14761                                },
14762                            ),
14763                        );
14764                    }
14765                    inline_diagnostics
14766                })
14767                .await;
14768
14769            editor
14770                .update(cx, |editor, cx| {
14771                    editor.inline_diagnostics = new_inline_diagnostics;
14772                    cx.notify();
14773                })
14774                .ok();
14775        });
14776    }
14777
14778    pub fn set_selections_from_remote(
14779        &mut self,
14780        selections: Vec<Selection<Anchor>>,
14781        pending_selection: Option<Selection<Anchor>>,
14782        window: &mut Window,
14783        cx: &mut Context<Self>,
14784    ) {
14785        let old_cursor_position = self.selections.newest_anchor().head();
14786        self.selections.change_with(cx, |s| {
14787            s.select_anchors(selections);
14788            if let Some(pending_selection) = pending_selection {
14789                s.set_pending(pending_selection, SelectMode::Character);
14790            } else {
14791                s.clear_pending();
14792            }
14793        });
14794        self.selections_did_change(false, &old_cursor_position, true, window, cx);
14795    }
14796
14797    fn push_to_selection_history(&mut self) {
14798        self.selection_history.push(SelectionHistoryEntry {
14799            selections: self.selections.disjoint_anchors(),
14800            select_next_state: self.select_next_state.clone(),
14801            select_prev_state: self.select_prev_state.clone(),
14802            add_selections_state: self.add_selections_state.clone(),
14803        });
14804    }
14805
14806    pub fn transact(
14807        &mut self,
14808        window: &mut Window,
14809        cx: &mut Context<Self>,
14810        update: impl FnOnce(&mut Self, &mut Window, &mut Context<Self>),
14811    ) -> Option<TransactionId> {
14812        self.start_transaction_at(Instant::now(), window, cx);
14813        update(self, window, cx);
14814        self.end_transaction_at(Instant::now(), cx)
14815    }
14816
14817    pub fn start_transaction_at(
14818        &mut self,
14819        now: Instant,
14820        window: &mut Window,
14821        cx: &mut Context<Self>,
14822    ) {
14823        self.end_selection(window, cx);
14824        if let Some(tx_id) = self
14825            .buffer
14826            .update(cx, |buffer, cx| buffer.start_transaction_at(now, cx))
14827        {
14828            self.selection_history
14829                .insert_transaction(tx_id, self.selections.disjoint_anchors());
14830            cx.emit(EditorEvent::TransactionBegun {
14831                transaction_id: tx_id,
14832            })
14833        }
14834    }
14835
14836    pub fn end_transaction_at(
14837        &mut self,
14838        now: Instant,
14839        cx: &mut Context<Self>,
14840    ) -> Option<TransactionId> {
14841        if let Some(transaction_id) = self
14842            .buffer
14843            .update(cx, |buffer, cx| buffer.end_transaction_at(now, cx))
14844        {
14845            if let Some((_, end_selections)) =
14846                self.selection_history.transaction_mut(transaction_id)
14847            {
14848                *end_selections = Some(self.selections.disjoint_anchors());
14849            } else {
14850                log::error!("unexpectedly ended a transaction that wasn't started by this editor");
14851            }
14852
14853            cx.emit(EditorEvent::Edited { transaction_id });
14854            Some(transaction_id)
14855        } else {
14856            None
14857        }
14858    }
14859
14860    pub fn set_mark(&mut self, _: &actions::SetMark, window: &mut Window, cx: &mut Context<Self>) {
14861        if self.selection_mark_mode {
14862            self.change_selections(None, window, cx, |s| {
14863                s.move_with(|_, sel| {
14864                    sel.collapse_to(sel.head(), SelectionGoal::None);
14865                });
14866            })
14867        }
14868        self.selection_mark_mode = true;
14869        cx.notify();
14870    }
14871
14872    pub fn swap_selection_ends(
14873        &mut self,
14874        _: &actions::SwapSelectionEnds,
14875        window: &mut Window,
14876        cx: &mut Context<Self>,
14877    ) {
14878        self.change_selections(None, window, cx, |s| {
14879            s.move_with(|_, sel| {
14880                if sel.start != sel.end {
14881                    sel.reversed = !sel.reversed
14882                }
14883            });
14884        });
14885        self.request_autoscroll(Autoscroll::newest(), cx);
14886        cx.notify();
14887    }
14888
14889    pub fn toggle_fold(
14890        &mut self,
14891        _: &actions::ToggleFold,
14892        window: &mut Window,
14893        cx: &mut Context<Self>,
14894    ) {
14895        if self.is_singleton(cx) {
14896            let selection = self.selections.newest::<Point>(cx);
14897
14898            let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
14899            let range = if selection.is_empty() {
14900                let point = selection.head().to_display_point(&display_map);
14901                let start = DisplayPoint::new(point.row(), 0).to_point(&display_map);
14902                let end = DisplayPoint::new(point.row(), display_map.line_len(point.row()))
14903                    .to_point(&display_map);
14904                start..end
14905            } else {
14906                selection.range()
14907            };
14908            if display_map.folds_in_range(range).next().is_some() {
14909                self.unfold_lines(&Default::default(), window, cx)
14910            } else {
14911                self.fold(&Default::default(), window, cx)
14912            }
14913        } else {
14914            let multi_buffer_snapshot = self.buffer.read(cx).snapshot(cx);
14915            let buffer_ids: HashSet<_> = self
14916                .selections
14917                .disjoint_anchor_ranges()
14918                .flat_map(|range| multi_buffer_snapshot.buffer_ids_for_range(range))
14919                .collect();
14920
14921            let should_unfold = buffer_ids
14922                .iter()
14923                .any(|buffer_id| self.is_buffer_folded(*buffer_id, cx));
14924
14925            for buffer_id in buffer_ids {
14926                if should_unfold {
14927                    self.unfold_buffer(buffer_id, cx);
14928                } else {
14929                    self.fold_buffer(buffer_id, cx);
14930                }
14931            }
14932        }
14933    }
14934
14935    pub fn toggle_fold_recursive(
14936        &mut self,
14937        _: &actions::ToggleFoldRecursive,
14938        window: &mut Window,
14939        cx: &mut Context<Self>,
14940    ) {
14941        let selection = self.selections.newest::<Point>(cx);
14942
14943        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
14944        let range = if selection.is_empty() {
14945            let point = selection.head().to_display_point(&display_map);
14946            let start = DisplayPoint::new(point.row(), 0).to_point(&display_map);
14947            let end = DisplayPoint::new(point.row(), display_map.line_len(point.row()))
14948                .to_point(&display_map);
14949            start..end
14950        } else {
14951            selection.range()
14952        };
14953        if display_map.folds_in_range(range).next().is_some() {
14954            self.unfold_recursive(&Default::default(), window, cx)
14955        } else {
14956            self.fold_recursive(&Default::default(), window, cx)
14957        }
14958    }
14959
14960    pub fn fold(&mut self, _: &actions::Fold, window: &mut Window, cx: &mut Context<Self>) {
14961        if self.is_singleton(cx) {
14962            let mut to_fold = Vec::new();
14963            let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
14964            let selections = self.selections.all_adjusted(cx);
14965
14966            for selection in selections {
14967                let range = selection.range().sorted();
14968                let buffer_start_row = range.start.row;
14969
14970                if range.start.row != range.end.row {
14971                    let mut found = false;
14972                    let mut row = range.start.row;
14973                    while row <= range.end.row {
14974                        if let Some(crease) = display_map.crease_for_buffer_row(MultiBufferRow(row))
14975                        {
14976                            found = true;
14977                            row = crease.range().end.row + 1;
14978                            to_fold.push(crease);
14979                        } else {
14980                            row += 1
14981                        }
14982                    }
14983                    if found {
14984                        continue;
14985                    }
14986                }
14987
14988                for row in (0..=range.start.row).rev() {
14989                    if let Some(crease) = display_map.crease_for_buffer_row(MultiBufferRow(row)) {
14990                        if crease.range().end.row >= buffer_start_row {
14991                            to_fold.push(crease);
14992                            if row <= range.start.row {
14993                                break;
14994                            }
14995                        }
14996                    }
14997                }
14998            }
14999
15000            self.fold_creases(to_fold, true, window, cx);
15001        } else {
15002            let multi_buffer_snapshot = self.buffer.read(cx).snapshot(cx);
15003            let buffer_ids = self
15004                .selections
15005                .disjoint_anchor_ranges()
15006                .flat_map(|range| multi_buffer_snapshot.buffer_ids_for_range(range))
15007                .collect::<HashSet<_>>();
15008            for buffer_id in buffer_ids {
15009                self.fold_buffer(buffer_id, cx);
15010            }
15011        }
15012    }
15013
15014    fn fold_at_level(
15015        &mut self,
15016        fold_at: &FoldAtLevel,
15017        window: &mut Window,
15018        cx: &mut Context<Self>,
15019    ) {
15020        if !self.buffer.read(cx).is_singleton() {
15021            return;
15022        }
15023
15024        let fold_at_level = fold_at.0;
15025        let snapshot = self.buffer.read(cx).snapshot(cx);
15026        let mut to_fold = Vec::new();
15027        let mut stack = vec![(0, snapshot.max_row().0, 1)];
15028
15029        while let Some((mut start_row, end_row, current_level)) = stack.pop() {
15030            while start_row < end_row {
15031                match self
15032                    .snapshot(window, cx)
15033                    .crease_for_buffer_row(MultiBufferRow(start_row))
15034                {
15035                    Some(crease) => {
15036                        let nested_start_row = crease.range().start.row + 1;
15037                        let nested_end_row = crease.range().end.row;
15038
15039                        if current_level < fold_at_level {
15040                            stack.push((nested_start_row, nested_end_row, current_level + 1));
15041                        } else if current_level == fold_at_level {
15042                            to_fold.push(crease);
15043                        }
15044
15045                        start_row = nested_end_row + 1;
15046                    }
15047                    None => start_row += 1,
15048                }
15049            }
15050        }
15051
15052        self.fold_creases(to_fold, true, window, cx);
15053    }
15054
15055    pub fn fold_all(&mut self, _: &actions::FoldAll, window: &mut Window, cx: &mut Context<Self>) {
15056        if self.buffer.read(cx).is_singleton() {
15057            let mut fold_ranges = Vec::new();
15058            let snapshot = self.buffer.read(cx).snapshot(cx);
15059
15060            for row in 0..snapshot.max_row().0 {
15061                if let Some(foldable_range) = self
15062                    .snapshot(window, cx)
15063                    .crease_for_buffer_row(MultiBufferRow(row))
15064                {
15065                    fold_ranges.push(foldable_range);
15066                }
15067            }
15068
15069            self.fold_creases(fold_ranges, true, window, cx);
15070        } else {
15071            self.toggle_fold_multiple_buffers = cx.spawn_in(window, async move |editor, cx| {
15072                editor
15073                    .update_in(cx, |editor, _, cx| {
15074                        for buffer_id in editor.buffer.read(cx).excerpt_buffer_ids() {
15075                            editor.fold_buffer(buffer_id, cx);
15076                        }
15077                    })
15078                    .ok();
15079            });
15080        }
15081    }
15082
15083    pub fn fold_function_bodies(
15084        &mut self,
15085        _: &actions::FoldFunctionBodies,
15086        window: &mut Window,
15087        cx: &mut Context<Self>,
15088    ) {
15089        let snapshot = self.buffer.read(cx).snapshot(cx);
15090
15091        let ranges = snapshot
15092            .text_object_ranges(0..snapshot.len(), TreeSitterOptions::default())
15093            .filter_map(|(range, obj)| (obj == TextObject::InsideFunction).then_some(range))
15094            .collect::<Vec<_>>();
15095
15096        let creases = ranges
15097            .into_iter()
15098            .map(|range| Crease::simple(range, self.display_map.read(cx).fold_placeholder.clone()))
15099            .collect();
15100
15101        self.fold_creases(creases, true, window, cx);
15102    }
15103
15104    pub fn fold_recursive(
15105        &mut self,
15106        _: &actions::FoldRecursive,
15107        window: &mut Window,
15108        cx: &mut Context<Self>,
15109    ) {
15110        let mut to_fold = Vec::new();
15111        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
15112        let selections = self.selections.all_adjusted(cx);
15113
15114        for selection in selections {
15115            let range = selection.range().sorted();
15116            let buffer_start_row = range.start.row;
15117
15118            if range.start.row != range.end.row {
15119                let mut found = false;
15120                for row in range.start.row..=range.end.row {
15121                    if let Some(crease) = display_map.crease_for_buffer_row(MultiBufferRow(row)) {
15122                        found = true;
15123                        to_fold.push(crease);
15124                    }
15125                }
15126                if found {
15127                    continue;
15128                }
15129            }
15130
15131            for row in (0..=range.start.row).rev() {
15132                if let Some(crease) = display_map.crease_for_buffer_row(MultiBufferRow(row)) {
15133                    if crease.range().end.row >= buffer_start_row {
15134                        to_fold.push(crease);
15135                    } else {
15136                        break;
15137                    }
15138                }
15139            }
15140        }
15141
15142        self.fold_creases(to_fold, true, window, cx);
15143    }
15144
15145    pub fn fold_at(
15146        &mut self,
15147        buffer_row: MultiBufferRow,
15148        window: &mut Window,
15149        cx: &mut Context<Self>,
15150    ) {
15151        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
15152
15153        if let Some(crease) = display_map.crease_for_buffer_row(buffer_row) {
15154            let autoscroll = self
15155                .selections
15156                .all::<Point>(cx)
15157                .iter()
15158                .any(|selection| crease.range().overlaps(&selection.range()));
15159
15160            self.fold_creases(vec![crease], autoscroll, window, cx);
15161        }
15162    }
15163
15164    pub fn unfold_lines(&mut self, _: &UnfoldLines, _window: &mut Window, cx: &mut Context<Self>) {
15165        if self.is_singleton(cx) {
15166            let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
15167            let buffer = &display_map.buffer_snapshot;
15168            let selections = self.selections.all::<Point>(cx);
15169            let ranges = selections
15170                .iter()
15171                .map(|s| {
15172                    let range = s.display_range(&display_map).sorted();
15173                    let mut start = range.start.to_point(&display_map);
15174                    let mut end = range.end.to_point(&display_map);
15175                    start.column = 0;
15176                    end.column = buffer.line_len(MultiBufferRow(end.row));
15177                    start..end
15178                })
15179                .collect::<Vec<_>>();
15180
15181            self.unfold_ranges(&ranges, true, true, cx);
15182        } else {
15183            let multi_buffer_snapshot = self.buffer.read(cx).snapshot(cx);
15184            let buffer_ids = self
15185                .selections
15186                .disjoint_anchor_ranges()
15187                .flat_map(|range| multi_buffer_snapshot.buffer_ids_for_range(range))
15188                .collect::<HashSet<_>>();
15189            for buffer_id in buffer_ids {
15190                self.unfold_buffer(buffer_id, cx);
15191            }
15192        }
15193    }
15194
15195    pub fn unfold_recursive(
15196        &mut self,
15197        _: &UnfoldRecursive,
15198        _window: &mut Window,
15199        cx: &mut Context<Self>,
15200    ) {
15201        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
15202        let selections = self.selections.all::<Point>(cx);
15203        let ranges = selections
15204            .iter()
15205            .map(|s| {
15206                let mut range = s.display_range(&display_map).sorted();
15207                *range.start.column_mut() = 0;
15208                *range.end.column_mut() = display_map.line_len(range.end.row());
15209                let start = range.start.to_point(&display_map);
15210                let end = range.end.to_point(&display_map);
15211                start..end
15212            })
15213            .collect::<Vec<_>>();
15214
15215        self.unfold_ranges(&ranges, true, true, cx);
15216    }
15217
15218    pub fn unfold_at(
15219        &mut self,
15220        buffer_row: MultiBufferRow,
15221        _window: &mut Window,
15222        cx: &mut Context<Self>,
15223    ) {
15224        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
15225
15226        let intersection_range = Point::new(buffer_row.0, 0)
15227            ..Point::new(
15228                buffer_row.0,
15229                display_map.buffer_snapshot.line_len(buffer_row),
15230            );
15231
15232        let autoscroll = self
15233            .selections
15234            .all::<Point>(cx)
15235            .iter()
15236            .any(|selection| RangeExt::overlaps(&selection.range(), &intersection_range));
15237
15238        self.unfold_ranges(&[intersection_range], true, autoscroll, cx);
15239    }
15240
15241    pub fn unfold_all(
15242        &mut self,
15243        _: &actions::UnfoldAll,
15244        _window: &mut Window,
15245        cx: &mut Context<Self>,
15246    ) {
15247        if self.buffer.read(cx).is_singleton() {
15248            let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
15249            self.unfold_ranges(&[0..display_map.buffer_snapshot.len()], true, true, cx);
15250        } else {
15251            self.toggle_fold_multiple_buffers = cx.spawn(async move |editor, cx| {
15252                editor
15253                    .update(cx, |editor, cx| {
15254                        for buffer_id in editor.buffer.read(cx).excerpt_buffer_ids() {
15255                            editor.unfold_buffer(buffer_id, cx);
15256                        }
15257                    })
15258                    .ok();
15259            });
15260        }
15261    }
15262
15263    pub fn fold_selected_ranges(
15264        &mut self,
15265        _: &FoldSelectedRanges,
15266        window: &mut Window,
15267        cx: &mut Context<Self>,
15268    ) {
15269        let selections = self.selections.all_adjusted(cx);
15270        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
15271        let ranges = selections
15272            .into_iter()
15273            .map(|s| Crease::simple(s.range(), display_map.fold_placeholder.clone()))
15274            .collect::<Vec<_>>();
15275        self.fold_creases(ranges, true, window, cx);
15276    }
15277
15278    pub fn fold_ranges<T: ToOffset + Clone>(
15279        &mut self,
15280        ranges: Vec<Range<T>>,
15281        auto_scroll: bool,
15282        window: &mut Window,
15283        cx: &mut Context<Self>,
15284    ) {
15285        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
15286        let ranges = ranges
15287            .into_iter()
15288            .map(|r| Crease::simple(r, display_map.fold_placeholder.clone()))
15289            .collect::<Vec<_>>();
15290        self.fold_creases(ranges, auto_scroll, window, cx);
15291    }
15292
15293    pub fn fold_creases<T: ToOffset + Clone>(
15294        &mut self,
15295        creases: Vec<Crease<T>>,
15296        auto_scroll: bool,
15297        _window: &mut Window,
15298        cx: &mut Context<Self>,
15299    ) {
15300        if creases.is_empty() {
15301            return;
15302        }
15303
15304        let mut buffers_affected = HashSet::default();
15305        let multi_buffer = self.buffer().read(cx);
15306        for crease in &creases {
15307            if let Some((_, buffer, _)) =
15308                multi_buffer.excerpt_containing(crease.range().start.clone(), cx)
15309            {
15310                buffers_affected.insert(buffer.read(cx).remote_id());
15311            };
15312        }
15313
15314        self.display_map.update(cx, |map, cx| map.fold(creases, cx));
15315
15316        if auto_scroll {
15317            self.request_autoscroll(Autoscroll::fit(), cx);
15318        }
15319
15320        cx.notify();
15321
15322        self.scrollbar_marker_state.dirty = true;
15323        self.folds_did_change(cx);
15324    }
15325
15326    /// Removes any folds whose ranges intersect any of the given ranges.
15327    pub fn unfold_ranges<T: ToOffset + Clone>(
15328        &mut self,
15329        ranges: &[Range<T>],
15330        inclusive: bool,
15331        auto_scroll: bool,
15332        cx: &mut Context<Self>,
15333    ) {
15334        self.remove_folds_with(ranges, auto_scroll, cx, |map, cx| {
15335            map.unfold_intersecting(ranges.iter().cloned(), inclusive, cx)
15336        });
15337        self.folds_did_change(cx);
15338    }
15339
15340    pub fn fold_buffer(&mut self, buffer_id: BufferId, cx: &mut Context<Self>) {
15341        if self.buffer().read(cx).is_singleton() || self.is_buffer_folded(buffer_id, cx) {
15342            return;
15343        }
15344        let folded_excerpts = self.buffer().read(cx).excerpts_for_buffer(buffer_id, cx);
15345        self.display_map.update(cx, |display_map, cx| {
15346            display_map.fold_buffers([buffer_id], cx)
15347        });
15348        cx.emit(EditorEvent::BufferFoldToggled {
15349            ids: folded_excerpts.iter().map(|&(id, _)| id).collect(),
15350            folded: true,
15351        });
15352        cx.notify();
15353    }
15354
15355    pub fn unfold_buffer(&mut self, buffer_id: BufferId, cx: &mut Context<Self>) {
15356        if self.buffer().read(cx).is_singleton() || !self.is_buffer_folded(buffer_id, cx) {
15357            return;
15358        }
15359        let unfolded_excerpts = self.buffer().read(cx).excerpts_for_buffer(buffer_id, cx);
15360        self.display_map.update(cx, |display_map, cx| {
15361            display_map.unfold_buffers([buffer_id], cx);
15362        });
15363        cx.emit(EditorEvent::BufferFoldToggled {
15364            ids: unfolded_excerpts.iter().map(|&(id, _)| id).collect(),
15365            folded: false,
15366        });
15367        cx.notify();
15368    }
15369
15370    pub fn is_buffer_folded(&self, buffer: BufferId, cx: &App) -> bool {
15371        self.display_map.read(cx).is_buffer_folded(buffer)
15372    }
15373
15374    pub fn folded_buffers<'a>(&self, cx: &'a App) -> &'a HashSet<BufferId> {
15375        self.display_map.read(cx).folded_buffers()
15376    }
15377
15378    pub fn disable_header_for_buffer(&mut self, buffer_id: BufferId, cx: &mut Context<Self>) {
15379        self.display_map.update(cx, |display_map, cx| {
15380            display_map.disable_header_for_buffer(buffer_id, cx);
15381        });
15382        cx.notify();
15383    }
15384
15385    /// Removes any folds with the given ranges.
15386    pub fn remove_folds_with_type<T: ToOffset + Clone>(
15387        &mut self,
15388        ranges: &[Range<T>],
15389        type_id: TypeId,
15390        auto_scroll: bool,
15391        cx: &mut Context<Self>,
15392    ) {
15393        self.remove_folds_with(ranges, auto_scroll, cx, |map, cx| {
15394            map.remove_folds_with_type(ranges.iter().cloned(), type_id, cx)
15395        });
15396        self.folds_did_change(cx);
15397    }
15398
15399    fn remove_folds_with<T: ToOffset + Clone>(
15400        &mut self,
15401        ranges: &[Range<T>],
15402        auto_scroll: bool,
15403        cx: &mut Context<Self>,
15404        update: impl FnOnce(&mut DisplayMap, &mut Context<DisplayMap>),
15405    ) {
15406        if ranges.is_empty() {
15407            return;
15408        }
15409
15410        let mut buffers_affected = HashSet::default();
15411        let multi_buffer = self.buffer().read(cx);
15412        for range in ranges {
15413            if let Some((_, buffer, _)) = multi_buffer.excerpt_containing(range.start.clone(), cx) {
15414                buffers_affected.insert(buffer.read(cx).remote_id());
15415            };
15416        }
15417
15418        self.display_map.update(cx, update);
15419
15420        if auto_scroll {
15421            self.request_autoscroll(Autoscroll::fit(), cx);
15422        }
15423
15424        cx.notify();
15425        self.scrollbar_marker_state.dirty = true;
15426        self.active_indent_guides_state.dirty = true;
15427    }
15428
15429    pub fn update_fold_widths(
15430        &mut self,
15431        widths: impl IntoIterator<Item = (FoldId, Pixels)>,
15432        cx: &mut Context<Self>,
15433    ) -> bool {
15434        self.display_map
15435            .update(cx, |map, cx| map.update_fold_widths(widths, cx))
15436    }
15437
15438    pub fn default_fold_placeholder(&self, cx: &App) -> FoldPlaceholder {
15439        self.display_map.read(cx).fold_placeholder.clone()
15440    }
15441
15442    pub fn set_expand_all_diff_hunks(&mut self, cx: &mut App) {
15443        self.buffer.update(cx, |buffer, cx| {
15444            buffer.set_all_diff_hunks_expanded(cx);
15445        });
15446    }
15447
15448    pub fn expand_all_diff_hunks(
15449        &mut self,
15450        _: &ExpandAllDiffHunks,
15451        _window: &mut Window,
15452        cx: &mut Context<Self>,
15453    ) {
15454        self.buffer.update(cx, |buffer, cx| {
15455            buffer.expand_diff_hunks(vec![Anchor::min()..Anchor::max()], cx)
15456        });
15457    }
15458
15459    pub fn toggle_selected_diff_hunks(
15460        &mut self,
15461        _: &ToggleSelectedDiffHunks,
15462        _window: &mut Window,
15463        cx: &mut Context<Self>,
15464    ) {
15465        let ranges: Vec<_> = self.selections.disjoint.iter().map(|s| s.range()).collect();
15466        self.toggle_diff_hunks_in_ranges(ranges, cx);
15467    }
15468
15469    pub fn diff_hunks_in_ranges<'a>(
15470        &'a self,
15471        ranges: &'a [Range<Anchor>],
15472        buffer: &'a MultiBufferSnapshot,
15473    ) -> impl 'a + Iterator<Item = MultiBufferDiffHunk> {
15474        ranges.iter().flat_map(move |range| {
15475            let end_excerpt_id = range.end.excerpt_id;
15476            let range = range.to_point(buffer);
15477            let mut peek_end = range.end;
15478            if range.end.row < buffer.max_row().0 {
15479                peek_end = Point::new(range.end.row + 1, 0);
15480            }
15481            buffer
15482                .diff_hunks_in_range(range.start..peek_end)
15483                .filter(move |hunk| hunk.excerpt_id.cmp(&end_excerpt_id, buffer).is_le())
15484        })
15485    }
15486
15487    pub fn has_stageable_diff_hunks_in_ranges(
15488        &self,
15489        ranges: &[Range<Anchor>],
15490        snapshot: &MultiBufferSnapshot,
15491    ) -> bool {
15492        let mut hunks = self.diff_hunks_in_ranges(ranges, &snapshot);
15493        hunks.any(|hunk| hunk.status().has_secondary_hunk())
15494    }
15495
15496    pub fn toggle_staged_selected_diff_hunks(
15497        &mut self,
15498        _: &::git::ToggleStaged,
15499        _: &mut Window,
15500        cx: &mut Context<Self>,
15501    ) {
15502        let snapshot = self.buffer.read(cx).snapshot(cx);
15503        let ranges: Vec<_> = self.selections.disjoint.iter().map(|s| s.range()).collect();
15504        let stage = self.has_stageable_diff_hunks_in_ranges(&ranges, &snapshot);
15505        self.stage_or_unstage_diff_hunks(stage, ranges, cx);
15506    }
15507
15508    pub fn set_render_diff_hunk_controls(
15509        &mut self,
15510        render_diff_hunk_controls: RenderDiffHunkControlsFn,
15511        cx: &mut Context<Self>,
15512    ) {
15513        self.render_diff_hunk_controls = render_diff_hunk_controls;
15514        cx.notify();
15515    }
15516
15517    pub fn stage_and_next(
15518        &mut self,
15519        _: &::git::StageAndNext,
15520        window: &mut Window,
15521        cx: &mut Context<Self>,
15522    ) {
15523        self.do_stage_or_unstage_and_next(true, window, cx);
15524    }
15525
15526    pub fn unstage_and_next(
15527        &mut self,
15528        _: &::git::UnstageAndNext,
15529        window: &mut Window,
15530        cx: &mut Context<Self>,
15531    ) {
15532        self.do_stage_or_unstage_and_next(false, window, cx);
15533    }
15534
15535    pub fn stage_or_unstage_diff_hunks(
15536        &mut self,
15537        stage: bool,
15538        ranges: Vec<Range<Anchor>>,
15539        cx: &mut Context<Self>,
15540    ) {
15541        let task = self.save_buffers_for_ranges_if_needed(&ranges, cx);
15542        cx.spawn(async move |this, cx| {
15543            task.await?;
15544            this.update(cx, |this, cx| {
15545                let snapshot = this.buffer.read(cx).snapshot(cx);
15546                let chunk_by = this
15547                    .diff_hunks_in_ranges(&ranges, &snapshot)
15548                    .chunk_by(|hunk| hunk.buffer_id);
15549                for (buffer_id, hunks) in &chunk_by {
15550                    this.do_stage_or_unstage(stage, buffer_id, hunks, cx);
15551                }
15552            })
15553        })
15554        .detach_and_log_err(cx);
15555    }
15556
15557    fn save_buffers_for_ranges_if_needed(
15558        &mut self,
15559        ranges: &[Range<Anchor>],
15560        cx: &mut Context<Editor>,
15561    ) -> Task<Result<()>> {
15562        let multibuffer = self.buffer.read(cx);
15563        let snapshot = multibuffer.read(cx);
15564        let buffer_ids: HashSet<_> = ranges
15565            .iter()
15566            .flat_map(|range| snapshot.buffer_ids_for_range(range.clone()))
15567            .collect();
15568        drop(snapshot);
15569
15570        let mut buffers = HashSet::default();
15571        for buffer_id in buffer_ids {
15572            if let Some(buffer_entity) = multibuffer.buffer(buffer_id) {
15573                let buffer = buffer_entity.read(cx);
15574                if buffer.file().is_some_and(|file| file.disk_state().exists()) && buffer.is_dirty()
15575                {
15576                    buffers.insert(buffer_entity);
15577                }
15578            }
15579        }
15580
15581        if let Some(project) = &self.project {
15582            project.update(cx, |project, cx| project.save_buffers(buffers, cx))
15583        } else {
15584            Task::ready(Ok(()))
15585        }
15586    }
15587
15588    fn do_stage_or_unstage_and_next(
15589        &mut self,
15590        stage: bool,
15591        window: &mut Window,
15592        cx: &mut Context<Self>,
15593    ) {
15594        let ranges = self.selections.disjoint_anchor_ranges().collect::<Vec<_>>();
15595
15596        if ranges.iter().any(|range| range.start != range.end) {
15597            self.stage_or_unstage_diff_hunks(stage, ranges, cx);
15598            return;
15599        }
15600
15601        self.stage_or_unstage_diff_hunks(stage, ranges, cx);
15602        let snapshot = self.snapshot(window, cx);
15603        let position = self.selections.newest::<Point>(cx).head();
15604        let mut row = snapshot
15605            .buffer_snapshot
15606            .diff_hunks_in_range(position..snapshot.buffer_snapshot.max_point())
15607            .find(|hunk| hunk.row_range.start.0 > position.row)
15608            .map(|hunk| hunk.row_range.start);
15609
15610        let all_diff_hunks_expanded = self.buffer().read(cx).all_diff_hunks_expanded();
15611        // Outside of the project diff editor, wrap around to the beginning.
15612        if !all_diff_hunks_expanded {
15613            row = row.or_else(|| {
15614                snapshot
15615                    .buffer_snapshot
15616                    .diff_hunks_in_range(Point::zero()..position)
15617                    .find(|hunk| hunk.row_range.end.0 < position.row)
15618                    .map(|hunk| hunk.row_range.start)
15619            });
15620        }
15621
15622        if let Some(row) = row {
15623            let destination = Point::new(row.0, 0);
15624            let autoscroll = Autoscroll::center();
15625
15626            self.unfold_ranges(&[destination..destination], false, false, cx);
15627            self.change_selections(Some(autoscroll), window, cx, |s| {
15628                s.select_ranges([destination..destination]);
15629            });
15630        }
15631    }
15632
15633    fn do_stage_or_unstage(
15634        &self,
15635        stage: bool,
15636        buffer_id: BufferId,
15637        hunks: impl Iterator<Item = MultiBufferDiffHunk>,
15638        cx: &mut App,
15639    ) -> Option<()> {
15640        let project = self.project.as_ref()?;
15641        let buffer = project.read(cx).buffer_for_id(buffer_id, cx)?;
15642        let diff = self.buffer.read(cx).diff_for(buffer_id)?;
15643        let buffer_snapshot = buffer.read(cx).snapshot();
15644        let file_exists = buffer_snapshot
15645            .file()
15646            .is_some_and(|file| file.disk_state().exists());
15647        diff.update(cx, |diff, cx| {
15648            diff.stage_or_unstage_hunks(
15649                stage,
15650                &hunks
15651                    .map(|hunk| buffer_diff::DiffHunk {
15652                        buffer_range: hunk.buffer_range,
15653                        diff_base_byte_range: hunk.diff_base_byte_range,
15654                        secondary_status: hunk.secondary_status,
15655                        range: Point::zero()..Point::zero(), // unused
15656                    })
15657                    .collect::<Vec<_>>(),
15658                &buffer_snapshot,
15659                file_exists,
15660                cx,
15661            )
15662        });
15663        None
15664    }
15665
15666    pub fn expand_selected_diff_hunks(&mut self, cx: &mut Context<Self>) {
15667        let ranges: Vec<_> = self.selections.disjoint.iter().map(|s| s.range()).collect();
15668        self.buffer
15669            .update(cx, |buffer, cx| buffer.expand_diff_hunks(ranges, cx))
15670    }
15671
15672    pub fn clear_expanded_diff_hunks(&mut self, cx: &mut Context<Self>) -> bool {
15673        self.buffer.update(cx, |buffer, cx| {
15674            let ranges = vec![Anchor::min()..Anchor::max()];
15675            if !buffer.all_diff_hunks_expanded()
15676                && buffer.has_expanded_diff_hunks_in_ranges(&ranges, cx)
15677            {
15678                buffer.collapse_diff_hunks(ranges, cx);
15679                true
15680            } else {
15681                false
15682            }
15683        })
15684    }
15685
15686    fn toggle_diff_hunks_in_ranges(
15687        &mut self,
15688        ranges: Vec<Range<Anchor>>,
15689        cx: &mut Context<Editor>,
15690    ) {
15691        self.buffer.update(cx, |buffer, cx| {
15692            let expand = !buffer.has_expanded_diff_hunks_in_ranges(&ranges, cx);
15693            buffer.expand_or_collapse_diff_hunks(ranges, expand, cx);
15694        })
15695    }
15696
15697    fn toggle_single_diff_hunk(&mut self, range: Range<Anchor>, cx: &mut Context<Self>) {
15698        self.buffer.update(cx, |buffer, cx| {
15699            let snapshot = buffer.snapshot(cx);
15700            let excerpt_id = range.end.excerpt_id;
15701            let point_range = range.to_point(&snapshot);
15702            let expand = !buffer.single_hunk_is_expanded(range, cx);
15703            buffer.expand_or_collapse_diff_hunks_inner([(point_range, excerpt_id)], expand, cx);
15704        })
15705    }
15706
15707    pub(crate) fn apply_all_diff_hunks(
15708        &mut self,
15709        _: &ApplyAllDiffHunks,
15710        window: &mut Window,
15711        cx: &mut Context<Self>,
15712    ) {
15713        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
15714
15715        let buffers = self.buffer.read(cx).all_buffers();
15716        for branch_buffer in buffers {
15717            branch_buffer.update(cx, |branch_buffer, cx| {
15718                branch_buffer.merge_into_base(Vec::new(), cx);
15719            });
15720        }
15721
15722        if let Some(project) = self.project.clone() {
15723            self.save(true, project, window, cx).detach_and_log_err(cx);
15724        }
15725    }
15726
15727    pub(crate) fn apply_selected_diff_hunks(
15728        &mut self,
15729        _: &ApplyDiffHunk,
15730        window: &mut Window,
15731        cx: &mut Context<Self>,
15732    ) {
15733        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
15734        let snapshot = self.snapshot(window, cx);
15735        let hunks = snapshot.hunks_for_ranges(self.selections.ranges(cx));
15736        let mut ranges_by_buffer = HashMap::default();
15737        self.transact(window, cx, |editor, _window, cx| {
15738            for hunk in hunks {
15739                if let Some(buffer) = editor.buffer.read(cx).buffer(hunk.buffer_id) {
15740                    ranges_by_buffer
15741                        .entry(buffer.clone())
15742                        .or_insert_with(Vec::new)
15743                        .push(hunk.buffer_range.to_offset(buffer.read(cx)));
15744                }
15745            }
15746
15747            for (buffer, ranges) in ranges_by_buffer {
15748                buffer.update(cx, |buffer, cx| {
15749                    buffer.merge_into_base(ranges, cx);
15750                });
15751            }
15752        });
15753
15754        if let Some(project) = self.project.clone() {
15755            self.save(true, project, window, cx).detach_and_log_err(cx);
15756        }
15757    }
15758
15759    pub fn set_gutter_hovered(&mut self, hovered: bool, cx: &mut Context<Self>) {
15760        if hovered != self.gutter_hovered {
15761            self.gutter_hovered = hovered;
15762            cx.notify();
15763        }
15764    }
15765
15766    pub fn insert_blocks(
15767        &mut self,
15768        blocks: impl IntoIterator<Item = BlockProperties<Anchor>>,
15769        autoscroll: Option<Autoscroll>,
15770        cx: &mut Context<Self>,
15771    ) -> Vec<CustomBlockId> {
15772        let blocks = self
15773            .display_map
15774            .update(cx, |display_map, cx| display_map.insert_blocks(blocks, cx));
15775        if let Some(autoscroll) = autoscroll {
15776            self.request_autoscroll(autoscroll, cx);
15777        }
15778        cx.notify();
15779        blocks
15780    }
15781
15782    pub fn resize_blocks(
15783        &mut self,
15784        heights: HashMap<CustomBlockId, u32>,
15785        autoscroll: Option<Autoscroll>,
15786        cx: &mut Context<Self>,
15787    ) {
15788        self.display_map
15789            .update(cx, |display_map, cx| display_map.resize_blocks(heights, cx));
15790        if let Some(autoscroll) = autoscroll {
15791            self.request_autoscroll(autoscroll, cx);
15792        }
15793        cx.notify();
15794    }
15795
15796    pub fn replace_blocks(
15797        &mut self,
15798        renderers: HashMap<CustomBlockId, RenderBlock>,
15799        autoscroll: Option<Autoscroll>,
15800        cx: &mut Context<Self>,
15801    ) {
15802        self.display_map
15803            .update(cx, |display_map, _cx| display_map.replace_blocks(renderers));
15804        if let Some(autoscroll) = autoscroll {
15805            self.request_autoscroll(autoscroll, cx);
15806        }
15807        cx.notify();
15808    }
15809
15810    pub fn remove_blocks(
15811        &mut self,
15812        block_ids: HashSet<CustomBlockId>,
15813        autoscroll: Option<Autoscroll>,
15814        cx: &mut Context<Self>,
15815    ) {
15816        self.display_map.update(cx, |display_map, cx| {
15817            display_map.remove_blocks(block_ids, cx)
15818        });
15819        if let Some(autoscroll) = autoscroll {
15820            self.request_autoscroll(autoscroll, cx);
15821        }
15822        cx.notify();
15823    }
15824
15825    pub fn row_for_block(
15826        &self,
15827        block_id: CustomBlockId,
15828        cx: &mut Context<Self>,
15829    ) -> Option<DisplayRow> {
15830        self.display_map
15831            .update(cx, |map, cx| map.row_for_block(block_id, cx))
15832    }
15833
15834    pub(crate) fn set_focused_block(&mut self, focused_block: FocusedBlock) {
15835        self.focused_block = Some(focused_block);
15836    }
15837
15838    pub(crate) fn take_focused_block(&mut self) -> Option<FocusedBlock> {
15839        self.focused_block.take()
15840    }
15841
15842    pub fn insert_creases(
15843        &mut self,
15844        creases: impl IntoIterator<Item = Crease<Anchor>>,
15845        cx: &mut Context<Self>,
15846    ) -> Vec<CreaseId> {
15847        self.display_map
15848            .update(cx, |map, cx| map.insert_creases(creases, cx))
15849    }
15850
15851    pub fn remove_creases(
15852        &mut self,
15853        ids: impl IntoIterator<Item = CreaseId>,
15854        cx: &mut Context<Self>,
15855    ) {
15856        self.display_map
15857            .update(cx, |map, cx| map.remove_creases(ids, cx));
15858    }
15859
15860    pub fn longest_row(&self, cx: &mut App) -> DisplayRow {
15861        self.display_map
15862            .update(cx, |map, cx| map.snapshot(cx))
15863            .longest_row()
15864    }
15865
15866    pub fn max_point(&self, cx: &mut App) -> DisplayPoint {
15867        self.display_map
15868            .update(cx, |map, cx| map.snapshot(cx))
15869            .max_point()
15870    }
15871
15872    pub fn text(&self, cx: &App) -> String {
15873        self.buffer.read(cx).read(cx).text()
15874    }
15875
15876    pub fn is_empty(&self, cx: &App) -> bool {
15877        self.buffer.read(cx).read(cx).is_empty()
15878    }
15879
15880    pub fn text_option(&self, cx: &App) -> Option<String> {
15881        let text = self.text(cx);
15882        let text = text.trim();
15883
15884        if text.is_empty() {
15885            return None;
15886        }
15887
15888        Some(text.to_string())
15889    }
15890
15891    pub fn set_text(
15892        &mut self,
15893        text: impl Into<Arc<str>>,
15894        window: &mut Window,
15895        cx: &mut Context<Self>,
15896    ) {
15897        self.transact(window, cx, |this, _, cx| {
15898            this.buffer
15899                .read(cx)
15900                .as_singleton()
15901                .expect("you can only call set_text on editors for singleton buffers")
15902                .update(cx, |buffer, cx| buffer.set_text(text, cx));
15903        });
15904    }
15905
15906    pub fn display_text(&self, cx: &mut App) -> String {
15907        self.display_map
15908            .update(cx, |map, cx| map.snapshot(cx))
15909            .text()
15910    }
15911
15912    pub fn wrap_guides(&self, cx: &App) -> SmallVec<[(usize, bool); 2]> {
15913        let mut wrap_guides = smallvec::smallvec![];
15914
15915        if self.show_wrap_guides == Some(false) {
15916            return wrap_guides;
15917        }
15918
15919        let settings = self.buffer.read(cx).language_settings(cx);
15920        if settings.show_wrap_guides {
15921            match self.soft_wrap_mode(cx) {
15922                SoftWrap::Column(soft_wrap) => {
15923                    wrap_guides.push((soft_wrap as usize, true));
15924                }
15925                SoftWrap::Bounded(soft_wrap) => {
15926                    wrap_guides.push((soft_wrap as usize, true));
15927                }
15928                SoftWrap::GitDiff | SoftWrap::None | SoftWrap::EditorWidth => {}
15929            }
15930            wrap_guides.extend(settings.wrap_guides.iter().map(|guide| (*guide, false)))
15931        }
15932
15933        wrap_guides
15934    }
15935
15936    pub fn soft_wrap_mode(&self, cx: &App) -> SoftWrap {
15937        let settings = self.buffer.read(cx).language_settings(cx);
15938        let mode = self.soft_wrap_mode_override.unwrap_or(settings.soft_wrap);
15939        match mode {
15940            language_settings::SoftWrap::PreferLine | language_settings::SoftWrap::None => {
15941                SoftWrap::None
15942            }
15943            language_settings::SoftWrap::EditorWidth => SoftWrap::EditorWidth,
15944            language_settings::SoftWrap::PreferredLineLength => {
15945                SoftWrap::Column(settings.preferred_line_length)
15946            }
15947            language_settings::SoftWrap::Bounded => {
15948                SoftWrap::Bounded(settings.preferred_line_length)
15949            }
15950        }
15951    }
15952
15953    pub fn set_soft_wrap_mode(
15954        &mut self,
15955        mode: language_settings::SoftWrap,
15956
15957        cx: &mut Context<Self>,
15958    ) {
15959        self.soft_wrap_mode_override = Some(mode);
15960        cx.notify();
15961    }
15962
15963    pub fn set_hard_wrap(&mut self, hard_wrap: Option<usize>, cx: &mut Context<Self>) {
15964        self.hard_wrap = hard_wrap;
15965        cx.notify();
15966    }
15967
15968    pub fn set_text_style_refinement(&mut self, style: TextStyleRefinement) {
15969        self.text_style_refinement = Some(style);
15970    }
15971
15972    /// called by the Element so we know what style we were most recently rendered with.
15973    pub(crate) fn set_style(
15974        &mut self,
15975        style: EditorStyle,
15976        window: &mut Window,
15977        cx: &mut Context<Self>,
15978    ) {
15979        let rem_size = window.rem_size();
15980        self.display_map.update(cx, |map, cx| {
15981            map.set_font(
15982                style.text.font(),
15983                style.text.font_size.to_pixels(rem_size),
15984                cx,
15985            )
15986        });
15987        self.style = Some(style);
15988    }
15989
15990    pub fn style(&self) -> Option<&EditorStyle> {
15991        self.style.as_ref()
15992    }
15993
15994    // Called by the element. This method is not designed to be called outside of the editor
15995    // element's layout code because it does not notify when rewrapping is computed synchronously.
15996    pub(crate) fn set_wrap_width(&self, width: Option<Pixels>, cx: &mut App) -> bool {
15997        self.display_map
15998            .update(cx, |map, cx| map.set_wrap_width(width, cx))
15999    }
16000
16001    pub fn set_soft_wrap(&mut self) {
16002        self.soft_wrap_mode_override = Some(language_settings::SoftWrap::EditorWidth)
16003    }
16004
16005    pub fn toggle_soft_wrap(&mut self, _: &ToggleSoftWrap, _: &mut Window, cx: &mut Context<Self>) {
16006        if self.soft_wrap_mode_override.is_some() {
16007            self.soft_wrap_mode_override.take();
16008        } else {
16009            let soft_wrap = match self.soft_wrap_mode(cx) {
16010                SoftWrap::GitDiff => return,
16011                SoftWrap::None => language_settings::SoftWrap::EditorWidth,
16012                SoftWrap::EditorWidth | SoftWrap::Column(_) | SoftWrap::Bounded(_) => {
16013                    language_settings::SoftWrap::None
16014                }
16015            };
16016            self.soft_wrap_mode_override = Some(soft_wrap);
16017        }
16018        cx.notify();
16019    }
16020
16021    pub fn toggle_tab_bar(&mut self, _: &ToggleTabBar, _: &mut Window, cx: &mut Context<Self>) {
16022        let Some(workspace) = self.workspace() else {
16023            return;
16024        };
16025        let fs = workspace.read(cx).app_state().fs.clone();
16026        let current_show = TabBarSettings::get_global(cx).show;
16027        update_settings_file::<TabBarSettings>(fs, cx, move |setting, _| {
16028            setting.show = Some(!current_show);
16029        });
16030    }
16031
16032    pub fn toggle_indent_guides(
16033        &mut self,
16034        _: &ToggleIndentGuides,
16035        _: &mut Window,
16036        cx: &mut Context<Self>,
16037    ) {
16038        let currently_enabled = self.should_show_indent_guides().unwrap_or_else(|| {
16039            self.buffer
16040                .read(cx)
16041                .language_settings(cx)
16042                .indent_guides
16043                .enabled
16044        });
16045        self.show_indent_guides = Some(!currently_enabled);
16046        cx.notify();
16047    }
16048
16049    fn should_show_indent_guides(&self) -> Option<bool> {
16050        self.show_indent_guides
16051    }
16052
16053    pub fn toggle_line_numbers(
16054        &mut self,
16055        _: &ToggleLineNumbers,
16056        _: &mut Window,
16057        cx: &mut Context<Self>,
16058    ) {
16059        let mut editor_settings = EditorSettings::get_global(cx).clone();
16060        editor_settings.gutter.line_numbers = !editor_settings.gutter.line_numbers;
16061        EditorSettings::override_global(editor_settings, cx);
16062    }
16063
16064    pub fn line_numbers_enabled(&self, cx: &App) -> bool {
16065        if let Some(show_line_numbers) = self.show_line_numbers {
16066            return show_line_numbers;
16067        }
16068        EditorSettings::get_global(cx).gutter.line_numbers
16069    }
16070
16071    pub fn should_use_relative_line_numbers(&self, cx: &mut App) -> bool {
16072        self.use_relative_line_numbers
16073            .unwrap_or(EditorSettings::get_global(cx).relative_line_numbers)
16074    }
16075
16076    pub fn toggle_relative_line_numbers(
16077        &mut self,
16078        _: &ToggleRelativeLineNumbers,
16079        _: &mut Window,
16080        cx: &mut Context<Self>,
16081    ) {
16082        let is_relative = self.should_use_relative_line_numbers(cx);
16083        self.set_relative_line_number(Some(!is_relative), cx)
16084    }
16085
16086    pub fn set_relative_line_number(&mut self, is_relative: Option<bool>, cx: &mut Context<Self>) {
16087        self.use_relative_line_numbers = is_relative;
16088        cx.notify();
16089    }
16090
16091    pub fn set_show_gutter(&mut self, show_gutter: bool, cx: &mut Context<Self>) {
16092        self.show_gutter = show_gutter;
16093        cx.notify();
16094    }
16095
16096    pub fn set_show_scrollbars(&mut self, show_scrollbars: bool, cx: &mut Context<Self>) {
16097        self.show_scrollbars = show_scrollbars;
16098        cx.notify();
16099    }
16100
16101    pub fn set_show_line_numbers(&mut self, show_line_numbers: bool, cx: &mut Context<Self>) {
16102        self.show_line_numbers = Some(show_line_numbers);
16103        cx.notify();
16104    }
16105
16106    pub fn set_show_git_diff_gutter(&mut self, show_git_diff_gutter: bool, cx: &mut Context<Self>) {
16107        self.show_git_diff_gutter = Some(show_git_diff_gutter);
16108        cx.notify();
16109    }
16110
16111    pub fn set_show_code_actions(&mut self, show_code_actions: bool, cx: &mut Context<Self>) {
16112        self.show_code_actions = Some(show_code_actions);
16113        cx.notify();
16114    }
16115
16116    pub fn set_show_runnables(&mut self, show_runnables: bool, cx: &mut Context<Self>) {
16117        self.show_runnables = Some(show_runnables);
16118        cx.notify();
16119    }
16120
16121    pub fn set_show_breakpoints(&mut self, show_breakpoints: bool, cx: &mut Context<Self>) {
16122        self.show_breakpoints = Some(show_breakpoints);
16123        cx.notify();
16124    }
16125
16126    pub fn set_masked(&mut self, masked: bool, cx: &mut Context<Self>) {
16127        if self.display_map.read(cx).masked != masked {
16128            self.display_map.update(cx, |map, _| map.masked = masked);
16129        }
16130        cx.notify()
16131    }
16132
16133    pub fn set_show_wrap_guides(&mut self, show_wrap_guides: bool, cx: &mut Context<Self>) {
16134        self.show_wrap_guides = Some(show_wrap_guides);
16135        cx.notify();
16136    }
16137
16138    pub fn set_show_indent_guides(&mut self, show_indent_guides: bool, cx: &mut Context<Self>) {
16139        self.show_indent_guides = Some(show_indent_guides);
16140        cx.notify();
16141    }
16142
16143    pub fn working_directory(&self, cx: &App) -> Option<PathBuf> {
16144        if let Some(buffer) = self.buffer().read(cx).as_singleton() {
16145            if let Some(file) = buffer.read(cx).file().and_then(|f| f.as_local()) {
16146                if let Some(dir) = file.abs_path(cx).parent() {
16147                    return Some(dir.to_owned());
16148                }
16149            }
16150
16151            if let Some(project_path) = buffer.read(cx).project_path(cx) {
16152                return Some(project_path.path.to_path_buf());
16153            }
16154        }
16155
16156        None
16157    }
16158
16159    fn target_file<'a>(&self, cx: &'a App) -> Option<&'a dyn language::LocalFile> {
16160        self.active_excerpt(cx)?
16161            .1
16162            .read(cx)
16163            .file()
16164            .and_then(|f| f.as_local())
16165    }
16166
16167    pub fn target_file_abs_path(&self, cx: &mut Context<Self>) -> Option<PathBuf> {
16168        self.active_excerpt(cx).and_then(|(_, buffer, _)| {
16169            let buffer = buffer.read(cx);
16170            if let Some(project_path) = buffer.project_path(cx) {
16171                let project = self.project.as_ref()?.read(cx);
16172                project.absolute_path(&project_path, cx)
16173            } else {
16174                buffer
16175                    .file()
16176                    .and_then(|file| file.as_local().map(|file| file.abs_path(cx)))
16177            }
16178        })
16179    }
16180
16181    fn target_file_path(&self, cx: &mut Context<Self>) -> Option<PathBuf> {
16182        self.active_excerpt(cx).and_then(|(_, buffer, _)| {
16183            let project_path = buffer.read(cx).project_path(cx)?;
16184            let project = self.project.as_ref()?.read(cx);
16185            let entry = project.entry_for_path(&project_path, cx)?;
16186            let path = entry.path.to_path_buf();
16187            Some(path)
16188        })
16189    }
16190
16191    pub fn reveal_in_finder(
16192        &mut self,
16193        _: &RevealInFileManager,
16194        _window: &mut Window,
16195        cx: &mut Context<Self>,
16196    ) {
16197        if let Some(target) = self.target_file(cx) {
16198            cx.reveal_path(&target.abs_path(cx));
16199        }
16200    }
16201
16202    pub fn copy_path(
16203        &mut self,
16204        _: &zed_actions::workspace::CopyPath,
16205        _window: &mut Window,
16206        cx: &mut Context<Self>,
16207    ) {
16208        if let Some(path) = self.target_file_abs_path(cx) {
16209            if let Some(path) = path.to_str() {
16210                cx.write_to_clipboard(ClipboardItem::new_string(path.to_string()));
16211            }
16212        }
16213    }
16214
16215    pub fn copy_relative_path(
16216        &mut self,
16217        _: &zed_actions::workspace::CopyRelativePath,
16218        _window: &mut Window,
16219        cx: &mut Context<Self>,
16220    ) {
16221        if let Some(path) = self.target_file_path(cx) {
16222            if let Some(path) = path.to_str() {
16223                cx.write_to_clipboard(ClipboardItem::new_string(path.to_string()));
16224            }
16225        }
16226    }
16227
16228    pub fn project_path(&self, cx: &App) -> Option<ProjectPath> {
16229        if let Some(buffer) = self.buffer.read(cx).as_singleton() {
16230            buffer.read(cx).project_path(cx)
16231        } else {
16232            None
16233        }
16234    }
16235
16236    // Returns true if the editor handled a go-to-line request
16237    pub fn go_to_active_debug_line(&mut self, window: &mut Window, cx: &mut Context<Self>) -> bool {
16238        maybe!({
16239            let breakpoint_store = self.breakpoint_store.as_ref()?;
16240
16241            let Some((_, _, active_position)) =
16242                breakpoint_store.read(cx).active_position().cloned()
16243            else {
16244                self.clear_row_highlights::<DebugCurrentRowHighlight>();
16245                return None;
16246            };
16247
16248            let snapshot = self
16249                .project
16250                .as_ref()?
16251                .read(cx)
16252                .buffer_for_id(active_position.buffer_id?, cx)?
16253                .read(cx)
16254                .snapshot();
16255
16256            let mut handled = false;
16257            for (id, ExcerptRange { context, .. }) in self
16258                .buffer
16259                .read(cx)
16260                .excerpts_for_buffer(active_position.buffer_id?, cx)
16261            {
16262                if context.start.cmp(&active_position, &snapshot).is_ge()
16263                    || context.end.cmp(&active_position, &snapshot).is_lt()
16264                {
16265                    continue;
16266                }
16267                let snapshot = self.buffer.read(cx).snapshot(cx);
16268                let multibuffer_anchor = snapshot.anchor_in_excerpt(id, active_position)?;
16269
16270                handled = true;
16271                self.clear_row_highlights::<DebugCurrentRowHighlight>();
16272                self.go_to_line::<DebugCurrentRowHighlight>(
16273                    multibuffer_anchor,
16274                    Some(cx.theme().colors().editor_debugger_active_line_background),
16275                    window,
16276                    cx,
16277                );
16278
16279                cx.notify();
16280            }
16281            handled.then_some(())
16282        })
16283        .is_some()
16284    }
16285
16286    pub fn copy_file_name_without_extension(
16287        &mut self,
16288        _: &CopyFileNameWithoutExtension,
16289        _: &mut Window,
16290        cx: &mut Context<Self>,
16291    ) {
16292        if let Some(file) = self.target_file(cx) {
16293            if let Some(file_stem) = file.path().file_stem() {
16294                if let Some(name) = file_stem.to_str() {
16295                    cx.write_to_clipboard(ClipboardItem::new_string(name.to_string()));
16296                }
16297            }
16298        }
16299    }
16300
16301    pub fn copy_file_name(&mut self, _: &CopyFileName, _: &mut Window, cx: &mut Context<Self>) {
16302        if let Some(file) = self.target_file(cx) {
16303            if let Some(file_name) = file.path().file_name() {
16304                if let Some(name) = file_name.to_str() {
16305                    cx.write_to_clipboard(ClipboardItem::new_string(name.to_string()));
16306                }
16307            }
16308        }
16309    }
16310
16311    pub fn toggle_git_blame(
16312        &mut self,
16313        _: &::git::Blame,
16314        window: &mut Window,
16315        cx: &mut Context<Self>,
16316    ) {
16317        self.show_git_blame_gutter = !self.show_git_blame_gutter;
16318
16319        if self.show_git_blame_gutter && !self.has_blame_entries(cx) {
16320            self.start_git_blame(true, window, cx);
16321        }
16322
16323        cx.notify();
16324    }
16325
16326    pub fn toggle_git_blame_inline(
16327        &mut self,
16328        _: &ToggleGitBlameInline,
16329        window: &mut Window,
16330        cx: &mut Context<Self>,
16331    ) {
16332        self.toggle_git_blame_inline_internal(true, window, cx);
16333        cx.notify();
16334    }
16335
16336    pub fn open_git_blame_commit(
16337        &mut self,
16338        _: &OpenGitBlameCommit,
16339        window: &mut Window,
16340        cx: &mut Context<Self>,
16341    ) {
16342        self.open_git_blame_commit_internal(window, cx);
16343    }
16344
16345    fn open_git_blame_commit_internal(
16346        &mut self,
16347        window: &mut Window,
16348        cx: &mut Context<Self>,
16349    ) -> Option<()> {
16350        let blame = self.blame.as_ref()?;
16351        let snapshot = self.snapshot(window, cx);
16352        let cursor = self.selections.newest::<Point>(cx).head();
16353        let (buffer, point, _) = snapshot.buffer_snapshot.point_to_buffer_point(cursor)?;
16354        let blame_entry = blame
16355            .update(cx, |blame, cx| {
16356                blame
16357                    .blame_for_rows(
16358                        &[RowInfo {
16359                            buffer_id: Some(buffer.remote_id()),
16360                            buffer_row: Some(point.row),
16361                            ..Default::default()
16362                        }],
16363                        cx,
16364                    )
16365                    .next()
16366            })
16367            .flatten()?;
16368        let renderer = cx.global::<GlobalBlameRenderer>().0.clone();
16369        let repo = blame.read(cx).repository(cx)?;
16370        let workspace = self.workspace()?.downgrade();
16371        renderer.open_blame_commit(blame_entry, repo, workspace, window, cx);
16372        None
16373    }
16374
16375    pub fn git_blame_inline_enabled(&self) -> bool {
16376        self.git_blame_inline_enabled
16377    }
16378
16379    pub fn toggle_selection_menu(
16380        &mut self,
16381        _: &ToggleSelectionMenu,
16382        _: &mut Window,
16383        cx: &mut Context<Self>,
16384    ) {
16385        self.show_selection_menu = self
16386            .show_selection_menu
16387            .map(|show_selections_menu| !show_selections_menu)
16388            .or_else(|| Some(!EditorSettings::get_global(cx).toolbar.selections_menu));
16389
16390        cx.notify();
16391    }
16392
16393    pub fn selection_menu_enabled(&self, cx: &App) -> bool {
16394        self.show_selection_menu
16395            .unwrap_or_else(|| EditorSettings::get_global(cx).toolbar.selections_menu)
16396    }
16397
16398    fn start_git_blame(
16399        &mut self,
16400        user_triggered: bool,
16401        window: &mut Window,
16402        cx: &mut Context<Self>,
16403    ) {
16404        if let Some(project) = self.project.as_ref() {
16405            let Some(buffer) = self.buffer().read(cx).as_singleton() else {
16406                return;
16407            };
16408
16409            if buffer.read(cx).file().is_none() {
16410                return;
16411            }
16412
16413            let focused = self.focus_handle(cx).contains_focused(window, cx);
16414
16415            let project = project.clone();
16416            let blame = cx.new(|cx| GitBlame::new(buffer, project, user_triggered, focused, cx));
16417            self.blame_subscription =
16418                Some(cx.observe_in(&blame, window, |_, _, _, cx| cx.notify()));
16419            self.blame = Some(blame);
16420        }
16421    }
16422
16423    fn toggle_git_blame_inline_internal(
16424        &mut self,
16425        user_triggered: bool,
16426        window: &mut Window,
16427        cx: &mut Context<Self>,
16428    ) {
16429        if self.git_blame_inline_enabled {
16430            self.git_blame_inline_enabled = false;
16431            self.show_git_blame_inline = false;
16432            self.show_git_blame_inline_delay_task.take();
16433        } else {
16434            self.git_blame_inline_enabled = true;
16435            self.start_git_blame_inline(user_triggered, window, cx);
16436        }
16437
16438        cx.notify();
16439    }
16440
16441    fn start_git_blame_inline(
16442        &mut self,
16443        user_triggered: bool,
16444        window: &mut Window,
16445        cx: &mut Context<Self>,
16446    ) {
16447        self.start_git_blame(user_triggered, window, cx);
16448
16449        if ProjectSettings::get_global(cx)
16450            .git
16451            .inline_blame_delay()
16452            .is_some()
16453        {
16454            self.start_inline_blame_timer(window, cx);
16455        } else {
16456            self.show_git_blame_inline = true
16457        }
16458    }
16459
16460    pub fn blame(&self) -> Option<&Entity<GitBlame>> {
16461        self.blame.as_ref()
16462    }
16463
16464    pub fn show_git_blame_gutter(&self) -> bool {
16465        self.show_git_blame_gutter
16466    }
16467
16468    pub fn render_git_blame_gutter(&self, cx: &App) -> bool {
16469        self.show_git_blame_gutter && self.has_blame_entries(cx)
16470    }
16471
16472    pub fn render_git_blame_inline(&self, window: &Window, cx: &App) -> bool {
16473        self.show_git_blame_inline
16474            && (self.focus_handle.is_focused(window)
16475                || self
16476                    .git_blame_inline_tooltip
16477                    .as_ref()
16478                    .and_then(|t| t.upgrade())
16479                    .is_some())
16480            && !self.newest_selection_head_on_empty_line(cx)
16481            && self.has_blame_entries(cx)
16482    }
16483
16484    fn has_blame_entries(&self, cx: &App) -> bool {
16485        self.blame()
16486            .map_or(false, |blame| blame.read(cx).has_generated_entries())
16487    }
16488
16489    fn newest_selection_head_on_empty_line(&self, cx: &App) -> bool {
16490        let cursor_anchor = self.selections.newest_anchor().head();
16491
16492        let snapshot = self.buffer.read(cx).snapshot(cx);
16493        let buffer_row = MultiBufferRow(cursor_anchor.to_point(&snapshot).row);
16494
16495        snapshot.line_len(buffer_row) == 0
16496    }
16497
16498    fn get_permalink_to_line(&self, cx: &mut Context<Self>) -> Task<Result<url::Url>> {
16499        let buffer_and_selection = maybe!({
16500            let selection = self.selections.newest::<Point>(cx);
16501            let selection_range = selection.range();
16502
16503            let multi_buffer = self.buffer().read(cx);
16504            let multi_buffer_snapshot = multi_buffer.snapshot(cx);
16505            let buffer_ranges = multi_buffer_snapshot.range_to_buffer_ranges(selection_range);
16506
16507            let (buffer, range, _) = if selection.reversed {
16508                buffer_ranges.first()
16509            } else {
16510                buffer_ranges.last()
16511            }?;
16512
16513            let selection = text::ToPoint::to_point(&range.start, &buffer).row
16514                ..text::ToPoint::to_point(&range.end, &buffer).row;
16515            Some((
16516                multi_buffer.buffer(buffer.remote_id()).unwrap().clone(),
16517                selection,
16518            ))
16519        });
16520
16521        let Some((buffer, selection)) = buffer_and_selection else {
16522            return Task::ready(Err(anyhow!("failed to determine buffer and selection")));
16523        };
16524
16525        let Some(project) = self.project.as_ref() else {
16526            return Task::ready(Err(anyhow!("editor does not have project")));
16527        };
16528
16529        project.update(cx, |project, cx| {
16530            project.get_permalink_to_line(&buffer, selection, cx)
16531        })
16532    }
16533
16534    pub fn copy_permalink_to_line(
16535        &mut self,
16536        _: &CopyPermalinkToLine,
16537        window: &mut Window,
16538        cx: &mut Context<Self>,
16539    ) {
16540        let permalink_task = self.get_permalink_to_line(cx);
16541        let workspace = self.workspace();
16542
16543        cx.spawn_in(window, async move |_, cx| match permalink_task.await {
16544            Ok(permalink) => {
16545                cx.update(|_, cx| {
16546                    cx.write_to_clipboard(ClipboardItem::new_string(permalink.to_string()));
16547                })
16548                .ok();
16549            }
16550            Err(err) => {
16551                let message = format!("Failed to copy permalink: {err}");
16552
16553                Err::<(), anyhow::Error>(err).log_err();
16554
16555                if let Some(workspace) = workspace {
16556                    workspace
16557                        .update_in(cx, |workspace, _, cx| {
16558                            struct CopyPermalinkToLine;
16559
16560                            workspace.show_toast(
16561                                Toast::new(
16562                                    NotificationId::unique::<CopyPermalinkToLine>(),
16563                                    message,
16564                                ),
16565                                cx,
16566                            )
16567                        })
16568                        .ok();
16569                }
16570            }
16571        })
16572        .detach();
16573    }
16574
16575    pub fn copy_file_location(
16576        &mut self,
16577        _: &CopyFileLocation,
16578        _: &mut Window,
16579        cx: &mut Context<Self>,
16580    ) {
16581        let selection = self.selections.newest::<Point>(cx).start.row + 1;
16582        if let Some(file) = self.target_file(cx) {
16583            if let Some(path) = file.path().to_str() {
16584                cx.write_to_clipboard(ClipboardItem::new_string(format!("{path}:{selection}")));
16585            }
16586        }
16587    }
16588
16589    pub fn open_permalink_to_line(
16590        &mut self,
16591        _: &OpenPermalinkToLine,
16592        window: &mut Window,
16593        cx: &mut Context<Self>,
16594    ) {
16595        let permalink_task = self.get_permalink_to_line(cx);
16596        let workspace = self.workspace();
16597
16598        cx.spawn_in(window, async move |_, cx| match permalink_task.await {
16599            Ok(permalink) => {
16600                cx.update(|_, cx| {
16601                    cx.open_url(permalink.as_ref());
16602                })
16603                .ok();
16604            }
16605            Err(err) => {
16606                let message = format!("Failed to open permalink: {err}");
16607
16608                Err::<(), anyhow::Error>(err).log_err();
16609
16610                if let Some(workspace) = workspace {
16611                    workspace
16612                        .update(cx, |workspace, cx| {
16613                            struct OpenPermalinkToLine;
16614
16615                            workspace.show_toast(
16616                                Toast::new(
16617                                    NotificationId::unique::<OpenPermalinkToLine>(),
16618                                    message,
16619                                ),
16620                                cx,
16621                            )
16622                        })
16623                        .ok();
16624                }
16625            }
16626        })
16627        .detach();
16628    }
16629
16630    pub fn insert_uuid_v4(
16631        &mut self,
16632        _: &InsertUuidV4,
16633        window: &mut Window,
16634        cx: &mut Context<Self>,
16635    ) {
16636        self.insert_uuid(UuidVersion::V4, window, cx);
16637    }
16638
16639    pub fn insert_uuid_v7(
16640        &mut self,
16641        _: &InsertUuidV7,
16642        window: &mut Window,
16643        cx: &mut Context<Self>,
16644    ) {
16645        self.insert_uuid(UuidVersion::V7, window, cx);
16646    }
16647
16648    fn insert_uuid(&mut self, version: UuidVersion, window: &mut Window, cx: &mut Context<Self>) {
16649        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
16650        self.transact(window, cx, |this, window, cx| {
16651            let edits = this
16652                .selections
16653                .all::<Point>(cx)
16654                .into_iter()
16655                .map(|selection| {
16656                    let uuid = match version {
16657                        UuidVersion::V4 => uuid::Uuid::new_v4(),
16658                        UuidVersion::V7 => uuid::Uuid::now_v7(),
16659                    };
16660
16661                    (selection.range(), uuid.to_string())
16662                });
16663            this.edit(edits, cx);
16664            this.refresh_inline_completion(true, false, window, cx);
16665        });
16666    }
16667
16668    pub fn open_selections_in_multibuffer(
16669        &mut self,
16670        _: &OpenSelectionsInMultibuffer,
16671        window: &mut Window,
16672        cx: &mut Context<Self>,
16673    ) {
16674        let multibuffer = self.buffer.read(cx);
16675
16676        let Some(buffer) = multibuffer.as_singleton() else {
16677            return;
16678        };
16679
16680        let Some(workspace) = self.workspace() else {
16681            return;
16682        };
16683
16684        let locations = self
16685            .selections
16686            .disjoint_anchors()
16687            .iter()
16688            .map(|range| Location {
16689                buffer: buffer.clone(),
16690                range: range.start.text_anchor..range.end.text_anchor,
16691            })
16692            .collect::<Vec<_>>();
16693
16694        let title = multibuffer.title(cx).to_string();
16695
16696        cx.spawn_in(window, async move |_, cx| {
16697            workspace.update_in(cx, |workspace, window, cx| {
16698                Self::open_locations_in_multibuffer(
16699                    workspace,
16700                    locations,
16701                    format!("Selections for '{title}'"),
16702                    false,
16703                    MultibufferSelectionMode::All,
16704                    window,
16705                    cx,
16706                );
16707            })
16708        })
16709        .detach();
16710    }
16711
16712    /// Adds a row highlight for the given range. If a row has multiple highlights, the
16713    /// last highlight added will be used.
16714    ///
16715    /// If the range ends at the beginning of a line, then that line will not be highlighted.
16716    pub fn highlight_rows<T: 'static>(
16717        &mut self,
16718        range: Range<Anchor>,
16719        color: Hsla,
16720        should_autoscroll: bool,
16721        cx: &mut Context<Self>,
16722    ) {
16723        let snapshot = self.buffer().read(cx).snapshot(cx);
16724        let row_highlights = self.highlighted_rows.entry(TypeId::of::<T>()).or_default();
16725        let ix = row_highlights.binary_search_by(|highlight| {
16726            Ordering::Equal
16727                .then_with(|| highlight.range.start.cmp(&range.start, &snapshot))
16728                .then_with(|| highlight.range.end.cmp(&range.end, &snapshot))
16729        });
16730
16731        if let Err(mut ix) = ix {
16732            let index = post_inc(&mut self.highlight_order);
16733
16734            // If this range intersects with the preceding highlight, then merge it with
16735            // the preceding highlight. Otherwise insert a new highlight.
16736            let mut merged = false;
16737            if ix > 0 {
16738                let prev_highlight = &mut row_highlights[ix - 1];
16739                if prev_highlight
16740                    .range
16741                    .end
16742                    .cmp(&range.start, &snapshot)
16743                    .is_ge()
16744                {
16745                    ix -= 1;
16746                    if prev_highlight.range.end.cmp(&range.end, &snapshot).is_lt() {
16747                        prev_highlight.range.end = range.end;
16748                    }
16749                    merged = true;
16750                    prev_highlight.index = index;
16751                    prev_highlight.color = color;
16752                    prev_highlight.should_autoscroll = should_autoscroll;
16753                }
16754            }
16755
16756            if !merged {
16757                row_highlights.insert(
16758                    ix,
16759                    RowHighlight {
16760                        range: range.clone(),
16761                        index,
16762                        color,
16763                        should_autoscroll,
16764                    },
16765                );
16766            }
16767
16768            // If any of the following highlights intersect with this one, merge them.
16769            while let Some(next_highlight) = row_highlights.get(ix + 1) {
16770                let highlight = &row_highlights[ix];
16771                if next_highlight
16772                    .range
16773                    .start
16774                    .cmp(&highlight.range.end, &snapshot)
16775                    .is_le()
16776                {
16777                    if next_highlight
16778                        .range
16779                        .end
16780                        .cmp(&highlight.range.end, &snapshot)
16781                        .is_gt()
16782                    {
16783                        row_highlights[ix].range.end = next_highlight.range.end;
16784                    }
16785                    row_highlights.remove(ix + 1);
16786                } else {
16787                    break;
16788                }
16789            }
16790        }
16791    }
16792
16793    /// Remove any highlighted row ranges of the given type that intersect the
16794    /// given ranges.
16795    pub fn remove_highlighted_rows<T: 'static>(
16796        &mut self,
16797        ranges_to_remove: Vec<Range<Anchor>>,
16798        cx: &mut Context<Self>,
16799    ) {
16800        let snapshot = self.buffer().read(cx).snapshot(cx);
16801        let row_highlights = self.highlighted_rows.entry(TypeId::of::<T>()).or_default();
16802        let mut ranges_to_remove = ranges_to_remove.iter().peekable();
16803        row_highlights.retain(|highlight| {
16804            while let Some(range_to_remove) = ranges_to_remove.peek() {
16805                match range_to_remove.end.cmp(&highlight.range.start, &snapshot) {
16806                    Ordering::Less | Ordering::Equal => {
16807                        ranges_to_remove.next();
16808                    }
16809                    Ordering::Greater => {
16810                        match range_to_remove.start.cmp(&highlight.range.end, &snapshot) {
16811                            Ordering::Less | Ordering::Equal => {
16812                                return false;
16813                            }
16814                            Ordering::Greater => break,
16815                        }
16816                    }
16817                }
16818            }
16819
16820            true
16821        })
16822    }
16823
16824    /// Clear all anchor ranges for a certain highlight context type, so no corresponding rows will be highlighted.
16825    pub fn clear_row_highlights<T: 'static>(&mut self) {
16826        self.highlighted_rows.remove(&TypeId::of::<T>());
16827    }
16828
16829    /// For a highlight given context type, gets all anchor ranges that will be used for row highlighting.
16830    pub fn highlighted_rows<T: 'static>(&self) -> impl '_ + Iterator<Item = (Range<Anchor>, Hsla)> {
16831        self.highlighted_rows
16832            .get(&TypeId::of::<T>())
16833            .map_or(&[] as &[_], |vec| vec.as_slice())
16834            .iter()
16835            .map(|highlight| (highlight.range.clone(), highlight.color))
16836    }
16837
16838    /// Merges all anchor ranges for all context types ever set, picking the last highlight added in case of a row conflict.
16839    /// Returns a map of display rows that are highlighted and their corresponding highlight color.
16840    /// Allows to ignore certain kinds of highlights.
16841    pub fn highlighted_display_rows(
16842        &self,
16843        window: &mut Window,
16844        cx: &mut App,
16845    ) -> BTreeMap<DisplayRow, LineHighlight> {
16846        let snapshot = self.snapshot(window, cx);
16847        let mut used_highlight_orders = HashMap::default();
16848        self.highlighted_rows
16849            .iter()
16850            .flat_map(|(_, highlighted_rows)| highlighted_rows.iter())
16851            .fold(
16852                BTreeMap::<DisplayRow, LineHighlight>::new(),
16853                |mut unique_rows, highlight| {
16854                    let start = highlight.range.start.to_display_point(&snapshot);
16855                    let end = highlight.range.end.to_display_point(&snapshot);
16856                    let start_row = start.row().0;
16857                    let end_row = if highlight.range.end.text_anchor != text::Anchor::MAX
16858                        && end.column() == 0
16859                    {
16860                        end.row().0.saturating_sub(1)
16861                    } else {
16862                        end.row().0
16863                    };
16864                    for row in start_row..=end_row {
16865                        let used_index =
16866                            used_highlight_orders.entry(row).or_insert(highlight.index);
16867                        if highlight.index >= *used_index {
16868                            *used_index = highlight.index;
16869                            unique_rows.insert(DisplayRow(row), highlight.color.into());
16870                        }
16871                    }
16872                    unique_rows
16873                },
16874            )
16875    }
16876
16877    pub fn highlighted_display_row_for_autoscroll(
16878        &self,
16879        snapshot: &DisplaySnapshot,
16880    ) -> Option<DisplayRow> {
16881        self.highlighted_rows
16882            .values()
16883            .flat_map(|highlighted_rows| highlighted_rows.iter())
16884            .filter_map(|highlight| {
16885                if highlight.should_autoscroll {
16886                    Some(highlight.range.start.to_display_point(snapshot).row())
16887                } else {
16888                    None
16889                }
16890            })
16891            .min()
16892    }
16893
16894    pub fn set_search_within_ranges(&mut self, ranges: &[Range<Anchor>], cx: &mut Context<Self>) {
16895        self.highlight_background::<SearchWithinRange>(
16896            ranges,
16897            |colors| colors.editor_document_highlight_read_background,
16898            cx,
16899        )
16900    }
16901
16902    pub fn set_breadcrumb_header(&mut self, new_header: String) {
16903        self.breadcrumb_header = Some(new_header);
16904    }
16905
16906    pub fn clear_search_within_ranges(&mut self, cx: &mut Context<Self>) {
16907        self.clear_background_highlights::<SearchWithinRange>(cx);
16908    }
16909
16910    pub fn highlight_background<T: 'static>(
16911        &mut self,
16912        ranges: &[Range<Anchor>],
16913        color_fetcher: fn(&ThemeColors) -> Hsla,
16914        cx: &mut Context<Self>,
16915    ) {
16916        self.background_highlights
16917            .insert(TypeId::of::<T>(), (color_fetcher, Arc::from(ranges)));
16918        self.scrollbar_marker_state.dirty = true;
16919        cx.notify();
16920    }
16921
16922    pub fn clear_background_highlights<T: 'static>(
16923        &mut self,
16924        cx: &mut Context<Self>,
16925    ) -> Option<BackgroundHighlight> {
16926        let text_highlights = self.background_highlights.remove(&TypeId::of::<T>())?;
16927        if !text_highlights.1.is_empty() {
16928            self.scrollbar_marker_state.dirty = true;
16929            cx.notify();
16930        }
16931        Some(text_highlights)
16932    }
16933
16934    pub fn highlight_gutter<T: 'static>(
16935        &mut self,
16936        ranges: &[Range<Anchor>],
16937        color_fetcher: fn(&App) -> Hsla,
16938        cx: &mut Context<Self>,
16939    ) {
16940        self.gutter_highlights
16941            .insert(TypeId::of::<T>(), (color_fetcher, Arc::from(ranges)));
16942        cx.notify();
16943    }
16944
16945    pub fn clear_gutter_highlights<T: 'static>(
16946        &mut self,
16947        cx: &mut Context<Self>,
16948    ) -> Option<GutterHighlight> {
16949        cx.notify();
16950        self.gutter_highlights.remove(&TypeId::of::<T>())
16951    }
16952
16953    #[cfg(feature = "test-support")]
16954    pub fn all_text_background_highlights(
16955        &self,
16956        window: &mut Window,
16957        cx: &mut Context<Self>,
16958    ) -> Vec<(Range<DisplayPoint>, Hsla)> {
16959        let snapshot = self.snapshot(window, cx);
16960        let buffer = &snapshot.buffer_snapshot;
16961        let start = buffer.anchor_before(0);
16962        let end = buffer.anchor_after(buffer.len());
16963        let theme = cx.theme().colors();
16964        self.background_highlights_in_range(start..end, &snapshot, theme)
16965    }
16966
16967    #[cfg(feature = "test-support")]
16968    pub fn search_background_highlights(&mut self, cx: &mut Context<Self>) -> Vec<Range<Point>> {
16969        let snapshot = self.buffer().read(cx).snapshot(cx);
16970
16971        let highlights = self
16972            .background_highlights
16973            .get(&TypeId::of::<items::BufferSearchHighlights>());
16974
16975        if let Some((_color, ranges)) = highlights {
16976            ranges
16977                .iter()
16978                .map(|range| range.start.to_point(&snapshot)..range.end.to_point(&snapshot))
16979                .collect_vec()
16980        } else {
16981            vec![]
16982        }
16983    }
16984
16985    fn document_highlights_for_position<'a>(
16986        &'a self,
16987        position: Anchor,
16988        buffer: &'a MultiBufferSnapshot,
16989    ) -> impl 'a + Iterator<Item = &'a Range<Anchor>> {
16990        let read_highlights = self
16991            .background_highlights
16992            .get(&TypeId::of::<DocumentHighlightRead>())
16993            .map(|h| &h.1);
16994        let write_highlights = self
16995            .background_highlights
16996            .get(&TypeId::of::<DocumentHighlightWrite>())
16997            .map(|h| &h.1);
16998        let left_position = position.bias_left(buffer);
16999        let right_position = position.bias_right(buffer);
17000        read_highlights
17001            .into_iter()
17002            .chain(write_highlights)
17003            .flat_map(move |ranges| {
17004                let start_ix = match ranges.binary_search_by(|probe| {
17005                    let cmp = probe.end.cmp(&left_position, buffer);
17006                    if cmp.is_ge() {
17007                        Ordering::Greater
17008                    } else {
17009                        Ordering::Less
17010                    }
17011                }) {
17012                    Ok(i) | Err(i) => i,
17013                };
17014
17015                ranges[start_ix..]
17016                    .iter()
17017                    .take_while(move |range| range.start.cmp(&right_position, buffer).is_le())
17018            })
17019    }
17020
17021    pub fn has_background_highlights<T: 'static>(&self) -> bool {
17022        self.background_highlights
17023            .get(&TypeId::of::<T>())
17024            .map_or(false, |(_, highlights)| !highlights.is_empty())
17025    }
17026
17027    pub fn background_highlights_in_range(
17028        &self,
17029        search_range: Range<Anchor>,
17030        display_snapshot: &DisplaySnapshot,
17031        theme: &ThemeColors,
17032    ) -> Vec<(Range<DisplayPoint>, Hsla)> {
17033        let mut results = Vec::new();
17034        for (color_fetcher, ranges) in self.background_highlights.values() {
17035            let color = color_fetcher(theme);
17036            let start_ix = match ranges.binary_search_by(|probe| {
17037                let cmp = probe
17038                    .end
17039                    .cmp(&search_range.start, &display_snapshot.buffer_snapshot);
17040                if cmp.is_gt() {
17041                    Ordering::Greater
17042                } else {
17043                    Ordering::Less
17044                }
17045            }) {
17046                Ok(i) | Err(i) => i,
17047            };
17048            for range in &ranges[start_ix..] {
17049                if range
17050                    .start
17051                    .cmp(&search_range.end, &display_snapshot.buffer_snapshot)
17052                    .is_ge()
17053                {
17054                    break;
17055                }
17056
17057                let start = range.start.to_display_point(display_snapshot);
17058                let end = range.end.to_display_point(display_snapshot);
17059                results.push((start..end, color))
17060            }
17061        }
17062        results
17063    }
17064
17065    pub fn background_highlight_row_ranges<T: 'static>(
17066        &self,
17067        search_range: Range<Anchor>,
17068        display_snapshot: &DisplaySnapshot,
17069        count: usize,
17070    ) -> Vec<RangeInclusive<DisplayPoint>> {
17071        let mut results = Vec::new();
17072        let Some((_, ranges)) = self.background_highlights.get(&TypeId::of::<T>()) else {
17073            return vec![];
17074        };
17075
17076        let start_ix = match ranges.binary_search_by(|probe| {
17077            let cmp = probe
17078                .end
17079                .cmp(&search_range.start, &display_snapshot.buffer_snapshot);
17080            if cmp.is_gt() {
17081                Ordering::Greater
17082            } else {
17083                Ordering::Less
17084            }
17085        }) {
17086            Ok(i) | Err(i) => i,
17087        };
17088        let mut push_region = |start: Option<Point>, end: Option<Point>| {
17089            if let (Some(start_display), Some(end_display)) = (start, end) {
17090                results.push(
17091                    start_display.to_display_point(display_snapshot)
17092                        ..=end_display.to_display_point(display_snapshot),
17093                );
17094            }
17095        };
17096        let mut start_row: Option<Point> = None;
17097        let mut end_row: Option<Point> = None;
17098        if ranges.len() > count {
17099            return Vec::new();
17100        }
17101        for range in &ranges[start_ix..] {
17102            if range
17103                .start
17104                .cmp(&search_range.end, &display_snapshot.buffer_snapshot)
17105                .is_ge()
17106            {
17107                break;
17108            }
17109            let end = range.end.to_point(&display_snapshot.buffer_snapshot);
17110            if let Some(current_row) = &end_row {
17111                if end.row == current_row.row {
17112                    continue;
17113                }
17114            }
17115            let start = range.start.to_point(&display_snapshot.buffer_snapshot);
17116            if start_row.is_none() {
17117                assert_eq!(end_row, None);
17118                start_row = Some(start);
17119                end_row = Some(end);
17120                continue;
17121            }
17122            if let Some(current_end) = end_row.as_mut() {
17123                if start.row > current_end.row + 1 {
17124                    push_region(start_row, end_row);
17125                    start_row = Some(start);
17126                    end_row = Some(end);
17127                } else {
17128                    // Merge two hunks.
17129                    *current_end = end;
17130                }
17131            } else {
17132                unreachable!();
17133            }
17134        }
17135        // We might still have a hunk that was not rendered (if there was a search hit on the last line)
17136        push_region(start_row, end_row);
17137        results
17138    }
17139
17140    pub fn gutter_highlights_in_range(
17141        &self,
17142        search_range: Range<Anchor>,
17143        display_snapshot: &DisplaySnapshot,
17144        cx: &App,
17145    ) -> Vec<(Range<DisplayPoint>, Hsla)> {
17146        let mut results = Vec::new();
17147        for (color_fetcher, ranges) in self.gutter_highlights.values() {
17148            let color = color_fetcher(cx);
17149            let start_ix = match ranges.binary_search_by(|probe| {
17150                let cmp = probe
17151                    .end
17152                    .cmp(&search_range.start, &display_snapshot.buffer_snapshot);
17153                if cmp.is_gt() {
17154                    Ordering::Greater
17155                } else {
17156                    Ordering::Less
17157                }
17158            }) {
17159                Ok(i) | Err(i) => i,
17160            };
17161            for range in &ranges[start_ix..] {
17162                if range
17163                    .start
17164                    .cmp(&search_range.end, &display_snapshot.buffer_snapshot)
17165                    .is_ge()
17166                {
17167                    break;
17168                }
17169
17170                let start = range.start.to_display_point(display_snapshot);
17171                let end = range.end.to_display_point(display_snapshot);
17172                results.push((start..end, color))
17173            }
17174        }
17175        results
17176    }
17177
17178    /// Get the text ranges corresponding to the redaction query
17179    pub fn redacted_ranges(
17180        &self,
17181        search_range: Range<Anchor>,
17182        display_snapshot: &DisplaySnapshot,
17183        cx: &App,
17184    ) -> Vec<Range<DisplayPoint>> {
17185        display_snapshot
17186            .buffer_snapshot
17187            .redacted_ranges(search_range, |file| {
17188                if let Some(file) = file {
17189                    file.is_private()
17190                        && EditorSettings::get(
17191                            Some(SettingsLocation {
17192                                worktree_id: file.worktree_id(cx),
17193                                path: file.path().as_ref(),
17194                            }),
17195                            cx,
17196                        )
17197                        .redact_private_values
17198                } else {
17199                    false
17200                }
17201            })
17202            .map(|range| {
17203                range.start.to_display_point(display_snapshot)
17204                    ..range.end.to_display_point(display_snapshot)
17205            })
17206            .collect()
17207    }
17208
17209    pub fn highlight_text<T: 'static>(
17210        &mut self,
17211        ranges: Vec<Range<Anchor>>,
17212        style: HighlightStyle,
17213        cx: &mut Context<Self>,
17214    ) {
17215        self.display_map.update(cx, |map, _| {
17216            map.highlight_text(TypeId::of::<T>(), ranges, style)
17217        });
17218        cx.notify();
17219    }
17220
17221    pub(crate) fn highlight_inlays<T: 'static>(
17222        &mut self,
17223        highlights: Vec<InlayHighlight>,
17224        style: HighlightStyle,
17225        cx: &mut Context<Self>,
17226    ) {
17227        self.display_map.update(cx, |map, _| {
17228            map.highlight_inlays(TypeId::of::<T>(), highlights, style)
17229        });
17230        cx.notify();
17231    }
17232
17233    pub fn text_highlights<'a, T: 'static>(
17234        &'a self,
17235        cx: &'a App,
17236    ) -> Option<(HighlightStyle, &'a [Range<Anchor>])> {
17237        self.display_map.read(cx).text_highlights(TypeId::of::<T>())
17238    }
17239
17240    pub fn clear_highlights<T: 'static>(&mut self, cx: &mut Context<Self>) {
17241        let cleared = self
17242            .display_map
17243            .update(cx, |map, _| map.clear_highlights(TypeId::of::<T>()));
17244        if cleared {
17245            cx.notify();
17246        }
17247    }
17248
17249    pub fn show_local_cursors(&self, window: &mut Window, cx: &mut App) -> bool {
17250        (self.read_only(cx) || self.blink_manager.read(cx).visible())
17251            && self.focus_handle.is_focused(window)
17252    }
17253
17254    pub fn set_show_cursor_when_unfocused(&mut self, is_enabled: bool, cx: &mut Context<Self>) {
17255        self.show_cursor_when_unfocused = is_enabled;
17256        cx.notify();
17257    }
17258
17259    fn on_buffer_changed(&mut self, _: Entity<MultiBuffer>, cx: &mut Context<Self>) {
17260        cx.notify();
17261    }
17262
17263    fn on_buffer_event(
17264        &mut self,
17265        multibuffer: &Entity<MultiBuffer>,
17266        event: &multi_buffer::Event,
17267        window: &mut Window,
17268        cx: &mut Context<Self>,
17269    ) {
17270        match event {
17271            multi_buffer::Event::Edited {
17272                singleton_buffer_edited,
17273                edited_buffer: buffer_edited,
17274            } => {
17275                self.scrollbar_marker_state.dirty = true;
17276                self.active_indent_guides_state.dirty = true;
17277                self.refresh_active_diagnostics(cx);
17278                self.refresh_code_actions(window, cx);
17279                if self.has_active_inline_completion() {
17280                    self.update_visible_inline_completion(window, cx);
17281                }
17282                if let Some(buffer) = buffer_edited {
17283                    let buffer_id = buffer.read(cx).remote_id();
17284                    if !self.registered_buffers.contains_key(&buffer_id) {
17285                        if let Some(project) = self.project.as_ref() {
17286                            project.update(cx, |project, cx| {
17287                                self.registered_buffers.insert(
17288                                    buffer_id,
17289                                    project.register_buffer_with_language_servers(&buffer, cx),
17290                                );
17291                            })
17292                        }
17293                    }
17294                }
17295                cx.emit(EditorEvent::BufferEdited);
17296                cx.emit(SearchEvent::MatchesInvalidated);
17297                if *singleton_buffer_edited {
17298                    if let Some(project) = &self.project {
17299                        #[allow(clippy::mutable_key_type)]
17300                        let languages_affected = multibuffer.update(cx, |multibuffer, cx| {
17301                            multibuffer
17302                                .all_buffers()
17303                                .into_iter()
17304                                .filter_map(|buffer| {
17305                                    buffer.update(cx, |buffer, cx| {
17306                                        let language = buffer.language()?;
17307                                        let should_discard = project.update(cx, |project, cx| {
17308                                            project.is_local()
17309                                                && !project.has_language_servers_for(buffer, cx)
17310                                        });
17311                                        should_discard.not().then_some(language.clone())
17312                                    })
17313                                })
17314                                .collect::<HashSet<_>>()
17315                        });
17316                        if !languages_affected.is_empty() {
17317                            self.refresh_inlay_hints(
17318                                InlayHintRefreshReason::BufferEdited(languages_affected),
17319                                cx,
17320                            );
17321                        }
17322                    }
17323                }
17324
17325                let Some(project) = &self.project else { return };
17326                let (telemetry, is_via_ssh) = {
17327                    let project = project.read(cx);
17328                    let telemetry = project.client().telemetry().clone();
17329                    let is_via_ssh = project.is_via_ssh();
17330                    (telemetry, is_via_ssh)
17331                };
17332                refresh_linked_ranges(self, window, cx);
17333                telemetry.log_edit_event("editor", is_via_ssh);
17334            }
17335            multi_buffer::Event::ExcerptsAdded {
17336                buffer,
17337                predecessor,
17338                excerpts,
17339            } => {
17340                self.tasks_update_task = Some(self.refresh_runnables(window, cx));
17341                let buffer_id = buffer.read(cx).remote_id();
17342                if self.buffer.read(cx).diff_for(buffer_id).is_none() {
17343                    if let Some(project) = &self.project {
17344                        get_uncommitted_diff_for_buffer(
17345                            project,
17346                            [buffer.clone()],
17347                            self.buffer.clone(),
17348                            cx,
17349                        )
17350                        .detach();
17351                    }
17352                }
17353                cx.emit(EditorEvent::ExcerptsAdded {
17354                    buffer: buffer.clone(),
17355                    predecessor: *predecessor,
17356                    excerpts: excerpts.clone(),
17357                });
17358                self.refresh_inlay_hints(InlayHintRefreshReason::NewLinesShown, cx);
17359            }
17360            multi_buffer::Event::ExcerptsRemoved { ids } => {
17361                self.refresh_inlay_hints(InlayHintRefreshReason::ExcerptsRemoved(ids.clone()), cx);
17362                let buffer = self.buffer.read(cx);
17363                self.registered_buffers
17364                    .retain(|buffer_id, _| buffer.buffer(*buffer_id).is_some());
17365                jsx_tag_auto_close::refresh_enabled_in_any_buffer(self, multibuffer, cx);
17366                cx.emit(EditorEvent::ExcerptsRemoved { ids: ids.clone() })
17367            }
17368            multi_buffer::Event::ExcerptsEdited {
17369                excerpt_ids,
17370                buffer_ids,
17371            } => {
17372                self.display_map.update(cx, |map, cx| {
17373                    map.unfold_buffers(buffer_ids.iter().copied(), cx)
17374                });
17375                cx.emit(EditorEvent::ExcerptsEdited {
17376                    ids: excerpt_ids.clone(),
17377                })
17378            }
17379            multi_buffer::Event::ExcerptsExpanded { ids } => {
17380                self.refresh_inlay_hints(InlayHintRefreshReason::NewLinesShown, cx);
17381                cx.emit(EditorEvent::ExcerptsExpanded { ids: ids.clone() })
17382            }
17383            multi_buffer::Event::Reparsed(buffer_id) => {
17384                self.tasks_update_task = Some(self.refresh_runnables(window, cx));
17385                jsx_tag_auto_close::refresh_enabled_in_any_buffer(self, multibuffer, cx);
17386
17387                cx.emit(EditorEvent::Reparsed(*buffer_id));
17388            }
17389            multi_buffer::Event::DiffHunksToggled => {
17390                self.tasks_update_task = Some(self.refresh_runnables(window, cx));
17391            }
17392            multi_buffer::Event::LanguageChanged(buffer_id) => {
17393                linked_editing_ranges::refresh_linked_ranges(self, window, cx);
17394                jsx_tag_auto_close::refresh_enabled_in_any_buffer(self, multibuffer, cx);
17395                cx.emit(EditorEvent::Reparsed(*buffer_id));
17396                cx.notify();
17397            }
17398            multi_buffer::Event::DirtyChanged => cx.emit(EditorEvent::DirtyChanged),
17399            multi_buffer::Event::Saved => cx.emit(EditorEvent::Saved),
17400            multi_buffer::Event::FileHandleChanged
17401            | multi_buffer::Event::Reloaded
17402            | multi_buffer::Event::BufferDiffChanged => cx.emit(EditorEvent::TitleChanged),
17403            multi_buffer::Event::Closed => cx.emit(EditorEvent::Closed),
17404            multi_buffer::Event::DiagnosticsUpdated => {
17405                self.refresh_active_diagnostics(cx);
17406                self.refresh_inline_diagnostics(true, window, cx);
17407                self.scrollbar_marker_state.dirty = true;
17408                cx.notify();
17409            }
17410            _ => {}
17411        };
17412    }
17413
17414    fn on_display_map_changed(
17415        &mut self,
17416        _: Entity<DisplayMap>,
17417        _: &mut Window,
17418        cx: &mut Context<Self>,
17419    ) {
17420        cx.notify();
17421    }
17422
17423    fn settings_changed(&mut self, window: &mut Window, cx: &mut Context<Self>) {
17424        self.tasks_update_task = Some(self.refresh_runnables(window, cx));
17425        self.update_edit_prediction_settings(cx);
17426        self.refresh_inline_completion(true, false, window, cx);
17427        self.refresh_inlay_hints(
17428            InlayHintRefreshReason::SettingsChange(inlay_hint_settings(
17429                self.selections.newest_anchor().head(),
17430                &self.buffer.read(cx).snapshot(cx),
17431                cx,
17432            )),
17433            cx,
17434        );
17435
17436        let old_cursor_shape = self.cursor_shape;
17437
17438        {
17439            let editor_settings = EditorSettings::get_global(cx);
17440            self.scroll_manager.vertical_scroll_margin = editor_settings.vertical_scroll_margin;
17441            self.show_breadcrumbs = editor_settings.toolbar.breadcrumbs;
17442            self.cursor_shape = editor_settings.cursor_shape.unwrap_or_default();
17443            self.hide_mouse_mode = editor_settings.hide_mouse.unwrap_or_default();
17444        }
17445
17446        if old_cursor_shape != self.cursor_shape {
17447            cx.emit(EditorEvent::CursorShapeChanged);
17448        }
17449
17450        let project_settings = ProjectSettings::get_global(cx);
17451        self.serialize_dirty_buffers = project_settings.session.restore_unsaved_buffers;
17452
17453        if self.mode.is_full() {
17454            let show_inline_diagnostics = project_settings.diagnostics.inline.enabled;
17455            let inline_blame_enabled = project_settings.git.inline_blame_enabled();
17456            if self.show_inline_diagnostics != show_inline_diagnostics {
17457                self.show_inline_diagnostics = show_inline_diagnostics;
17458                self.refresh_inline_diagnostics(false, window, cx);
17459            }
17460
17461            if self.git_blame_inline_enabled != inline_blame_enabled {
17462                self.toggle_git_blame_inline_internal(false, window, cx);
17463            }
17464        }
17465
17466        cx.notify();
17467    }
17468
17469    pub fn set_searchable(&mut self, searchable: bool) {
17470        self.searchable = searchable;
17471    }
17472
17473    pub fn searchable(&self) -> bool {
17474        self.searchable
17475    }
17476
17477    fn open_proposed_changes_editor(
17478        &mut self,
17479        _: &OpenProposedChangesEditor,
17480        window: &mut Window,
17481        cx: &mut Context<Self>,
17482    ) {
17483        let Some(workspace) = self.workspace() else {
17484            cx.propagate();
17485            return;
17486        };
17487
17488        let selections = self.selections.all::<usize>(cx);
17489        let multi_buffer = self.buffer.read(cx);
17490        let multi_buffer_snapshot = multi_buffer.snapshot(cx);
17491        let mut new_selections_by_buffer = HashMap::default();
17492        for selection in selections {
17493            for (buffer, range, _) in
17494                multi_buffer_snapshot.range_to_buffer_ranges(selection.start..selection.end)
17495            {
17496                let mut range = range.to_point(buffer);
17497                range.start.column = 0;
17498                range.end.column = buffer.line_len(range.end.row);
17499                new_selections_by_buffer
17500                    .entry(multi_buffer.buffer(buffer.remote_id()).unwrap())
17501                    .or_insert(Vec::new())
17502                    .push(range)
17503            }
17504        }
17505
17506        let proposed_changes_buffers = new_selections_by_buffer
17507            .into_iter()
17508            .map(|(buffer, ranges)| ProposedChangeLocation { buffer, ranges })
17509            .collect::<Vec<_>>();
17510        let proposed_changes_editor = cx.new(|cx| {
17511            ProposedChangesEditor::new(
17512                "Proposed changes",
17513                proposed_changes_buffers,
17514                self.project.clone(),
17515                window,
17516                cx,
17517            )
17518        });
17519
17520        window.defer(cx, move |window, cx| {
17521            workspace.update(cx, |workspace, cx| {
17522                workspace.active_pane().update(cx, |pane, cx| {
17523                    pane.add_item(
17524                        Box::new(proposed_changes_editor),
17525                        true,
17526                        true,
17527                        None,
17528                        window,
17529                        cx,
17530                    );
17531                });
17532            });
17533        });
17534    }
17535
17536    pub fn open_excerpts_in_split(
17537        &mut self,
17538        _: &OpenExcerptsSplit,
17539        window: &mut Window,
17540        cx: &mut Context<Self>,
17541    ) {
17542        self.open_excerpts_common(None, true, window, cx)
17543    }
17544
17545    pub fn open_excerpts(&mut self, _: &OpenExcerpts, window: &mut Window, cx: &mut Context<Self>) {
17546        self.open_excerpts_common(None, false, window, cx)
17547    }
17548
17549    fn open_excerpts_common(
17550        &mut self,
17551        jump_data: Option<JumpData>,
17552        split: bool,
17553        window: &mut Window,
17554        cx: &mut Context<Self>,
17555    ) {
17556        let Some(workspace) = self.workspace() else {
17557            cx.propagate();
17558            return;
17559        };
17560
17561        if self.buffer.read(cx).is_singleton() {
17562            cx.propagate();
17563            return;
17564        }
17565
17566        let mut new_selections_by_buffer = HashMap::default();
17567        match &jump_data {
17568            Some(JumpData::MultiBufferPoint {
17569                excerpt_id,
17570                position,
17571                anchor,
17572                line_offset_from_top,
17573            }) => {
17574                let multi_buffer_snapshot = self.buffer.read(cx).snapshot(cx);
17575                if let Some(buffer) = multi_buffer_snapshot
17576                    .buffer_id_for_excerpt(*excerpt_id)
17577                    .and_then(|buffer_id| self.buffer.read(cx).buffer(buffer_id))
17578                {
17579                    let buffer_snapshot = buffer.read(cx).snapshot();
17580                    let jump_to_point = if buffer_snapshot.can_resolve(anchor) {
17581                        language::ToPoint::to_point(anchor, &buffer_snapshot)
17582                    } else {
17583                        buffer_snapshot.clip_point(*position, Bias::Left)
17584                    };
17585                    let jump_to_offset = buffer_snapshot.point_to_offset(jump_to_point);
17586                    new_selections_by_buffer.insert(
17587                        buffer,
17588                        (
17589                            vec![jump_to_offset..jump_to_offset],
17590                            Some(*line_offset_from_top),
17591                        ),
17592                    );
17593                }
17594            }
17595            Some(JumpData::MultiBufferRow {
17596                row,
17597                line_offset_from_top,
17598            }) => {
17599                let point = MultiBufferPoint::new(row.0, 0);
17600                if let Some((buffer, buffer_point, _)) =
17601                    self.buffer.read(cx).point_to_buffer_point(point, cx)
17602                {
17603                    let buffer_offset = buffer.read(cx).point_to_offset(buffer_point);
17604                    new_selections_by_buffer
17605                        .entry(buffer)
17606                        .or_insert((Vec::new(), Some(*line_offset_from_top)))
17607                        .0
17608                        .push(buffer_offset..buffer_offset)
17609                }
17610            }
17611            None => {
17612                let selections = self.selections.all::<usize>(cx);
17613                let multi_buffer = self.buffer.read(cx);
17614                for selection in selections {
17615                    for (snapshot, range, _, anchor) in multi_buffer
17616                        .snapshot(cx)
17617                        .range_to_buffer_ranges_with_deleted_hunks(selection.range())
17618                    {
17619                        if let Some(anchor) = anchor {
17620                            // selection is in a deleted hunk
17621                            let Some(buffer_id) = anchor.buffer_id else {
17622                                continue;
17623                            };
17624                            let Some(buffer_handle) = multi_buffer.buffer(buffer_id) else {
17625                                continue;
17626                            };
17627                            let offset = text::ToOffset::to_offset(
17628                                &anchor.text_anchor,
17629                                &buffer_handle.read(cx).snapshot(),
17630                            );
17631                            let range = offset..offset;
17632                            new_selections_by_buffer
17633                                .entry(buffer_handle)
17634                                .or_insert((Vec::new(), None))
17635                                .0
17636                                .push(range)
17637                        } else {
17638                            let Some(buffer_handle) = multi_buffer.buffer(snapshot.remote_id())
17639                            else {
17640                                continue;
17641                            };
17642                            new_selections_by_buffer
17643                                .entry(buffer_handle)
17644                                .or_insert((Vec::new(), None))
17645                                .0
17646                                .push(range)
17647                        }
17648                    }
17649                }
17650            }
17651        }
17652
17653        new_selections_by_buffer
17654            .retain(|buffer, _| Self::can_open_excerpts_in_file(buffer.read(cx).file()));
17655
17656        if new_selections_by_buffer.is_empty() {
17657            return;
17658        }
17659
17660        // We defer the pane interaction because we ourselves are a workspace item
17661        // and activating a new item causes the pane to call a method on us reentrantly,
17662        // which panics if we're on the stack.
17663        window.defer(cx, move |window, cx| {
17664            workspace.update(cx, |workspace, cx| {
17665                let pane = if split {
17666                    workspace.adjacent_pane(window, cx)
17667                } else {
17668                    workspace.active_pane().clone()
17669                };
17670
17671                for (buffer, (ranges, scroll_offset)) in new_selections_by_buffer {
17672                    let editor = buffer
17673                        .read(cx)
17674                        .file()
17675                        .is_none()
17676                        .then(|| {
17677                            // Handle file-less buffers separately: those are not really the project items, so won't have a project path or entity id,
17678                            // so `workspace.open_project_item` will never find them, always opening a new editor.
17679                            // Instead, we try to activate the existing editor in the pane first.
17680                            let (editor, pane_item_index) =
17681                                pane.read(cx).items().enumerate().find_map(|(i, item)| {
17682                                    let editor = item.downcast::<Editor>()?;
17683                                    let singleton_buffer =
17684                                        editor.read(cx).buffer().read(cx).as_singleton()?;
17685                                    if singleton_buffer == buffer {
17686                                        Some((editor, i))
17687                                    } else {
17688                                        None
17689                                    }
17690                                })?;
17691                            pane.update(cx, |pane, cx| {
17692                                pane.activate_item(pane_item_index, true, true, window, cx)
17693                            });
17694                            Some(editor)
17695                        })
17696                        .flatten()
17697                        .unwrap_or_else(|| {
17698                            workspace.open_project_item::<Self>(
17699                                pane.clone(),
17700                                buffer,
17701                                true,
17702                                true,
17703                                window,
17704                                cx,
17705                            )
17706                        });
17707
17708                    editor.update(cx, |editor, cx| {
17709                        let autoscroll = match scroll_offset {
17710                            Some(scroll_offset) => Autoscroll::top_relative(scroll_offset as usize),
17711                            None => Autoscroll::newest(),
17712                        };
17713                        let nav_history = editor.nav_history.take();
17714                        editor.change_selections(Some(autoscroll), window, cx, |s| {
17715                            s.select_ranges(ranges);
17716                        });
17717                        editor.nav_history = nav_history;
17718                    });
17719                }
17720            })
17721        });
17722    }
17723
17724    // For now, don't allow opening excerpts in buffers that aren't backed by
17725    // regular project files.
17726    fn can_open_excerpts_in_file(file: Option<&Arc<dyn language::File>>) -> bool {
17727        file.map_or(true, |file| project::File::from_dyn(Some(file)).is_some())
17728    }
17729
17730    fn marked_text_ranges(&self, cx: &App) -> Option<Vec<Range<OffsetUtf16>>> {
17731        let snapshot = self.buffer.read(cx).read(cx);
17732        let (_, ranges) = self.text_highlights::<InputComposition>(cx)?;
17733        Some(
17734            ranges
17735                .iter()
17736                .map(move |range| {
17737                    range.start.to_offset_utf16(&snapshot)..range.end.to_offset_utf16(&snapshot)
17738                })
17739                .collect(),
17740        )
17741    }
17742
17743    fn selection_replacement_ranges(
17744        &self,
17745        range: Range<OffsetUtf16>,
17746        cx: &mut App,
17747    ) -> Vec<Range<OffsetUtf16>> {
17748        let selections = self.selections.all::<OffsetUtf16>(cx);
17749        let newest_selection = selections
17750            .iter()
17751            .max_by_key(|selection| selection.id)
17752            .unwrap();
17753        let start_delta = range.start.0 as isize - newest_selection.start.0 as isize;
17754        let end_delta = range.end.0 as isize - newest_selection.end.0 as isize;
17755        let snapshot = self.buffer.read(cx).read(cx);
17756        selections
17757            .into_iter()
17758            .map(|mut selection| {
17759                selection.start.0 =
17760                    (selection.start.0 as isize).saturating_add(start_delta) as usize;
17761                selection.end.0 = (selection.end.0 as isize).saturating_add(end_delta) as usize;
17762                snapshot.clip_offset_utf16(selection.start, Bias::Left)
17763                    ..snapshot.clip_offset_utf16(selection.end, Bias::Right)
17764            })
17765            .collect()
17766    }
17767
17768    fn report_editor_event(
17769        &self,
17770        event_type: &'static str,
17771        file_extension: Option<String>,
17772        cx: &App,
17773    ) {
17774        if cfg!(any(test, feature = "test-support")) {
17775            return;
17776        }
17777
17778        let Some(project) = &self.project else { return };
17779
17780        // If None, we are in a file without an extension
17781        let file = self
17782            .buffer
17783            .read(cx)
17784            .as_singleton()
17785            .and_then(|b| b.read(cx).file());
17786        let file_extension = file_extension.or(file
17787            .as_ref()
17788            .and_then(|file| Path::new(file.file_name(cx)).extension())
17789            .and_then(|e| e.to_str())
17790            .map(|a| a.to_string()));
17791
17792        let vim_mode = vim_enabled(cx);
17793
17794        let edit_predictions_provider = all_language_settings(file, cx).edit_predictions.provider;
17795        let copilot_enabled = edit_predictions_provider
17796            == language::language_settings::EditPredictionProvider::Copilot;
17797        let copilot_enabled_for_language = self
17798            .buffer
17799            .read(cx)
17800            .language_settings(cx)
17801            .show_edit_predictions;
17802
17803        let project = project.read(cx);
17804        telemetry::event!(
17805            event_type,
17806            file_extension,
17807            vim_mode,
17808            copilot_enabled,
17809            copilot_enabled_for_language,
17810            edit_predictions_provider,
17811            is_via_ssh = project.is_via_ssh(),
17812        );
17813    }
17814
17815    /// Copy the highlighted chunks to the clipboard as JSON. The format is an array of lines,
17816    /// with each line being an array of {text, highlight} objects.
17817    fn copy_highlight_json(
17818        &mut self,
17819        _: &CopyHighlightJson,
17820        window: &mut Window,
17821        cx: &mut Context<Self>,
17822    ) {
17823        #[derive(Serialize)]
17824        struct Chunk<'a> {
17825            text: String,
17826            highlight: Option<&'a str>,
17827        }
17828
17829        let snapshot = self.buffer.read(cx).snapshot(cx);
17830        let range = self
17831            .selected_text_range(false, window, cx)
17832            .and_then(|selection| {
17833                if selection.range.is_empty() {
17834                    None
17835                } else {
17836                    Some(selection.range)
17837                }
17838            })
17839            .unwrap_or_else(|| 0..snapshot.len());
17840
17841        let chunks = snapshot.chunks(range, true);
17842        let mut lines = Vec::new();
17843        let mut line: VecDeque<Chunk> = VecDeque::new();
17844
17845        let Some(style) = self.style.as_ref() else {
17846            return;
17847        };
17848
17849        for chunk in chunks {
17850            let highlight = chunk
17851                .syntax_highlight_id
17852                .and_then(|id| id.name(&style.syntax));
17853            let mut chunk_lines = chunk.text.split('\n').peekable();
17854            while let Some(text) = chunk_lines.next() {
17855                let mut merged_with_last_token = false;
17856                if let Some(last_token) = line.back_mut() {
17857                    if last_token.highlight == highlight {
17858                        last_token.text.push_str(text);
17859                        merged_with_last_token = true;
17860                    }
17861                }
17862
17863                if !merged_with_last_token {
17864                    line.push_back(Chunk {
17865                        text: text.into(),
17866                        highlight,
17867                    });
17868                }
17869
17870                if chunk_lines.peek().is_some() {
17871                    if line.len() > 1 && line.front().unwrap().text.is_empty() {
17872                        line.pop_front();
17873                    }
17874                    if line.len() > 1 && line.back().unwrap().text.is_empty() {
17875                        line.pop_back();
17876                    }
17877
17878                    lines.push(mem::take(&mut line));
17879                }
17880            }
17881        }
17882
17883        let Some(lines) = serde_json::to_string_pretty(&lines).log_err() else {
17884            return;
17885        };
17886        cx.write_to_clipboard(ClipboardItem::new_string(lines));
17887    }
17888
17889    pub fn open_context_menu(
17890        &mut self,
17891        _: &OpenContextMenu,
17892        window: &mut Window,
17893        cx: &mut Context<Self>,
17894    ) {
17895        self.request_autoscroll(Autoscroll::newest(), cx);
17896        let position = self.selections.newest_display(cx).start;
17897        mouse_context_menu::deploy_context_menu(self, None, position, window, cx);
17898    }
17899
17900    pub fn inlay_hint_cache(&self) -> &InlayHintCache {
17901        &self.inlay_hint_cache
17902    }
17903
17904    pub fn replay_insert_event(
17905        &mut self,
17906        text: &str,
17907        relative_utf16_range: Option<Range<isize>>,
17908        window: &mut Window,
17909        cx: &mut Context<Self>,
17910    ) {
17911        if !self.input_enabled {
17912            cx.emit(EditorEvent::InputIgnored { text: text.into() });
17913            return;
17914        }
17915        if let Some(relative_utf16_range) = relative_utf16_range {
17916            let selections = self.selections.all::<OffsetUtf16>(cx);
17917            self.change_selections(None, window, cx, |s| {
17918                let new_ranges = selections.into_iter().map(|range| {
17919                    let start = OffsetUtf16(
17920                        range
17921                            .head()
17922                            .0
17923                            .saturating_add_signed(relative_utf16_range.start),
17924                    );
17925                    let end = OffsetUtf16(
17926                        range
17927                            .head()
17928                            .0
17929                            .saturating_add_signed(relative_utf16_range.end),
17930                    );
17931                    start..end
17932                });
17933                s.select_ranges(new_ranges);
17934            });
17935        }
17936
17937        self.handle_input(text, window, cx);
17938    }
17939
17940    pub fn supports_inlay_hints(&self, cx: &mut App) -> bool {
17941        let Some(provider) = self.semantics_provider.as_ref() else {
17942            return false;
17943        };
17944
17945        let mut supports = false;
17946        self.buffer().update(cx, |this, cx| {
17947            this.for_each_buffer(|buffer| {
17948                supports |= provider.supports_inlay_hints(buffer, cx);
17949            });
17950        });
17951
17952        supports
17953    }
17954
17955    pub fn is_focused(&self, window: &Window) -> bool {
17956        self.focus_handle.is_focused(window)
17957    }
17958
17959    fn handle_focus(&mut self, window: &mut Window, cx: &mut Context<Self>) {
17960        cx.emit(EditorEvent::Focused);
17961
17962        if let Some(descendant) = self
17963            .last_focused_descendant
17964            .take()
17965            .and_then(|descendant| descendant.upgrade())
17966        {
17967            window.focus(&descendant);
17968        } else {
17969            if let Some(blame) = self.blame.as_ref() {
17970                blame.update(cx, GitBlame::focus)
17971            }
17972
17973            self.blink_manager.update(cx, BlinkManager::enable);
17974            self.show_cursor_names(window, cx);
17975            self.buffer.update(cx, |buffer, cx| {
17976                buffer.finalize_last_transaction(cx);
17977                if self.leader_peer_id.is_none() {
17978                    buffer.set_active_selections(
17979                        &self.selections.disjoint_anchors(),
17980                        self.selections.line_mode,
17981                        self.cursor_shape,
17982                        cx,
17983                    );
17984                }
17985            });
17986        }
17987    }
17988
17989    fn handle_focus_in(&mut self, _: &mut Window, cx: &mut Context<Self>) {
17990        cx.emit(EditorEvent::FocusedIn)
17991    }
17992
17993    fn handle_focus_out(
17994        &mut self,
17995        event: FocusOutEvent,
17996        _window: &mut Window,
17997        cx: &mut Context<Self>,
17998    ) {
17999        if event.blurred != self.focus_handle {
18000            self.last_focused_descendant = Some(event.blurred);
18001        }
18002        self.refresh_inlay_hints(InlayHintRefreshReason::ModifiersChanged(false), cx);
18003    }
18004
18005    pub fn handle_blur(&mut self, window: &mut Window, cx: &mut Context<Self>) {
18006        self.blink_manager.update(cx, BlinkManager::disable);
18007        self.buffer
18008            .update(cx, |buffer, cx| buffer.remove_active_selections(cx));
18009
18010        if let Some(blame) = self.blame.as_ref() {
18011            blame.update(cx, GitBlame::blur)
18012        }
18013        if !self.hover_state.focused(window, cx) {
18014            hide_hover(self, cx);
18015        }
18016        if !self
18017            .context_menu
18018            .borrow()
18019            .as_ref()
18020            .is_some_and(|context_menu| context_menu.focused(window, cx))
18021        {
18022            self.hide_context_menu(window, cx);
18023        }
18024        self.discard_inline_completion(false, cx);
18025        cx.emit(EditorEvent::Blurred);
18026        cx.notify();
18027    }
18028
18029    pub fn register_action<A: Action>(
18030        &mut self,
18031        listener: impl Fn(&A, &mut Window, &mut App) + 'static,
18032    ) -> Subscription {
18033        let id = self.next_editor_action_id.post_inc();
18034        let listener = Arc::new(listener);
18035        self.editor_actions.borrow_mut().insert(
18036            id,
18037            Box::new(move |window, _| {
18038                let listener = listener.clone();
18039                window.on_action(TypeId::of::<A>(), move |action, phase, window, cx| {
18040                    let action = action.downcast_ref().unwrap();
18041                    if phase == DispatchPhase::Bubble {
18042                        listener(action, window, cx)
18043                    }
18044                })
18045            }),
18046        );
18047
18048        let editor_actions = self.editor_actions.clone();
18049        Subscription::new(move || {
18050            editor_actions.borrow_mut().remove(&id);
18051        })
18052    }
18053
18054    pub fn file_header_size(&self) -> u32 {
18055        FILE_HEADER_HEIGHT
18056    }
18057
18058    pub fn restore(
18059        &mut self,
18060        revert_changes: HashMap<BufferId, Vec<(Range<text::Anchor>, Rope)>>,
18061        window: &mut Window,
18062        cx: &mut Context<Self>,
18063    ) {
18064        let workspace = self.workspace();
18065        let project = self.project.as_ref();
18066        let save_tasks = self.buffer().update(cx, |multi_buffer, cx| {
18067            let mut tasks = Vec::new();
18068            for (buffer_id, changes) in revert_changes {
18069                if let Some(buffer) = multi_buffer.buffer(buffer_id) {
18070                    buffer.update(cx, |buffer, cx| {
18071                        buffer.edit(
18072                            changes
18073                                .into_iter()
18074                                .map(|(range, text)| (range, text.to_string())),
18075                            None,
18076                            cx,
18077                        );
18078                    });
18079
18080                    if let Some(project) =
18081                        project.filter(|_| multi_buffer.all_diff_hunks_expanded())
18082                    {
18083                        project.update(cx, |project, cx| {
18084                            tasks.push((buffer.clone(), project.save_buffer(buffer, cx)));
18085                        })
18086                    }
18087                }
18088            }
18089            tasks
18090        });
18091        cx.spawn_in(window, async move |_, cx| {
18092            for (buffer, task) in save_tasks {
18093                let result = task.await;
18094                if result.is_err() {
18095                    let Some(path) = buffer
18096                        .read_with(cx, |buffer, cx| buffer.project_path(cx))
18097                        .ok()
18098                    else {
18099                        continue;
18100                    };
18101                    if let Some((workspace, path)) = workspace.as_ref().zip(path) {
18102                        let Some(task) = cx
18103                            .update_window_entity(&workspace, |workspace, window, cx| {
18104                                workspace
18105                                    .open_path_preview(path, None, false, false, false, window, cx)
18106                            })
18107                            .ok()
18108                        else {
18109                            continue;
18110                        };
18111                        task.await.log_err();
18112                    }
18113                }
18114            }
18115        })
18116        .detach();
18117        self.change_selections(None, window, cx, |selections| selections.refresh());
18118    }
18119
18120    pub fn to_pixel_point(
18121        &self,
18122        source: multi_buffer::Anchor,
18123        editor_snapshot: &EditorSnapshot,
18124        window: &mut Window,
18125    ) -> Option<gpui::Point<Pixels>> {
18126        let source_point = source.to_display_point(editor_snapshot);
18127        self.display_to_pixel_point(source_point, editor_snapshot, window)
18128    }
18129
18130    pub fn display_to_pixel_point(
18131        &self,
18132        source: DisplayPoint,
18133        editor_snapshot: &EditorSnapshot,
18134        window: &mut Window,
18135    ) -> Option<gpui::Point<Pixels>> {
18136        let line_height = self.style()?.text.line_height_in_pixels(window.rem_size());
18137        let text_layout_details = self.text_layout_details(window);
18138        let scroll_top = text_layout_details
18139            .scroll_anchor
18140            .scroll_position(editor_snapshot)
18141            .y;
18142
18143        if source.row().as_f32() < scroll_top.floor() {
18144            return None;
18145        }
18146        let source_x = editor_snapshot.x_for_display_point(source, &text_layout_details);
18147        let source_y = line_height * (source.row().as_f32() - scroll_top);
18148        Some(gpui::Point::new(source_x, source_y))
18149    }
18150
18151    pub fn has_visible_completions_menu(&self) -> bool {
18152        !self.edit_prediction_preview_is_active()
18153            && self.context_menu.borrow().as_ref().map_or(false, |menu| {
18154                menu.visible() && matches!(menu, CodeContextMenu::Completions(_))
18155            })
18156    }
18157
18158    pub fn register_addon<T: Addon>(&mut self, instance: T) {
18159        self.addons
18160            .insert(std::any::TypeId::of::<T>(), Box::new(instance));
18161    }
18162
18163    pub fn unregister_addon<T: Addon>(&mut self) {
18164        self.addons.remove(&std::any::TypeId::of::<T>());
18165    }
18166
18167    pub fn addon<T: Addon>(&self) -> Option<&T> {
18168        let type_id = std::any::TypeId::of::<T>();
18169        self.addons
18170            .get(&type_id)
18171            .and_then(|item| item.to_any().downcast_ref::<T>())
18172    }
18173
18174    fn character_size(&self, window: &mut Window) -> gpui::Size<Pixels> {
18175        let text_layout_details = self.text_layout_details(window);
18176        let style = &text_layout_details.editor_style;
18177        let font_id = window.text_system().resolve_font(&style.text.font());
18178        let font_size = style.text.font_size.to_pixels(window.rem_size());
18179        let line_height = style.text.line_height_in_pixels(window.rem_size());
18180        let em_width = window.text_system().em_width(font_id, font_size).unwrap();
18181
18182        gpui::Size::new(em_width, line_height)
18183    }
18184
18185    pub fn wait_for_diff_to_load(&self) -> Option<Shared<Task<()>>> {
18186        self.load_diff_task.clone()
18187    }
18188
18189    fn read_metadata_from_db(
18190        &mut self,
18191        item_id: u64,
18192        workspace_id: WorkspaceId,
18193        window: &mut Window,
18194        cx: &mut Context<Editor>,
18195    ) {
18196        if self.is_singleton(cx)
18197            && WorkspaceSettings::get(None, cx).restore_on_startup != RestoreOnStartupBehavior::None
18198        {
18199            let buffer_snapshot = OnceCell::new();
18200
18201            if let Some(folds) = DB.get_editor_folds(item_id, workspace_id).log_err() {
18202                if !folds.is_empty() {
18203                    let snapshot =
18204                        buffer_snapshot.get_or_init(|| self.buffer.read(cx).snapshot(cx));
18205                    self.fold_ranges(
18206                        folds
18207                            .into_iter()
18208                            .map(|(start, end)| {
18209                                snapshot.clip_offset(start, Bias::Left)
18210                                    ..snapshot.clip_offset(end, Bias::Right)
18211                            })
18212                            .collect(),
18213                        false,
18214                        window,
18215                        cx,
18216                    );
18217                }
18218            }
18219
18220            if let Some(selections) = DB.get_editor_selections(item_id, workspace_id).log_err() {
18221                if !selections.is_empty() {
18222                    let snapshot =
18223                        buffer_snapshot.get_or_init(|| self.buffer.read(cx).snapshot(cx));
18224                    self.change_selections(None, window, cx, |s| {
18225                        s.select_ranges(selections.into_iter().map(|(start, end)| {
18226                            snapshot.clip_offset(start, Bias::Left)
18227                                ..snapshot.clip_offset(end, Bias::Right)
18228                        }));
18229                    });
18230                }
18231            };
18232        }
18233
18234        self.read_scroll_position_from_db(item_id, workspace_id, window, cx);
18235    }
18236}
18237
18238fn vim_enabled(cx: &App) -> bool {
18239    cx.global::<SettingsStore>()
18240        .raw_user_settings()
18241        .get("vim_mode")
18242        == Some(&serde_json::Value::Bool(true))
18243}
18244
18245// Consider user intent and default settings
18246fn choose_completion_range(
18247    completion: &Completion,
18248    intent: CompletionIntent,
18249    buffer: &Entity<Buffer>,
18250    cx: &mut Context<Editor>,
18251) -> Range<usize> {
18252    fn should_replace(
18253        completion: &Completion,
18254        insert_range: &Range<text::Anchor>,
18255        intent: CompletionIntent,
18256        completion_mode_setting: LspInsertMode,
18257        buffer: &Buffer,
18258    ) -> bool {
18259        // specific actions take precedence over settings
18260        match intent {
18261            CompletionIntent::CompleteWithInsert => return false,
18262            CompletionIntent::CompleteWithReplace => return true,
18263            CompletionIntent::Complete | CompletionIntent::Compose => {}
18264        }
18265
18266        match completion_mode_setting {
18267            LspInsertMode::Insert => false,
18268            LspInsertMode::Replace => true,
18269            LspInsertMode::ReplaceSubsequence => {
18270                let mut text_to_replace = buffer.chars_for_range(
18271                    buffer.anchor_before(completion.replace_range.start)
18272                        ..buffer.anchor_after(completion.replace_range.end),
18273                );
18274                let mut completion_text = completion.new_text.chars();
18275
18276                // is `text_to_replace` a subsequence of `completion_text`
18277                text_to_replace
18278                    .all(|needle_ch| completion_text.any(|haystack_ch| haystack_ch == needle_ch))
18279            }
18280            LspInsertMode::ReplaceSuffix => {
18281                let range_after_cursor = insert_range.end..completion.replace_range.end;
18282
18283                let text_after_cursor = buffer
18284                    .text_for_range(
18285                        buffer.anchor_before(range_after_cursor.start)
18286                            ..buffer.anchor_after(range_after_cursor.end),
18287                    )
18288                    .collect::<String>();
18289                completion.new_text.ends_with(&text_after_cursor)
18290            }
18291        }
18292    }
18293
18294    let buffer = buffer.read(cx);
18295
18296    if let CompletionSource::Lsp {
18297        insert_range: Some(insert_range),
18298        ..
18299    } = &completion.source
18300    {
18301        let completion_mode_setting =
18302            language_settings(buffer.language().map(|l| l.name()), buffer.file(), cx)
18303                .completions
18304                .lsp_insert_mode;
18305
18306        if !should_replace(
18307            completion,
18308            &insert_range,
18309            intent,
18310            completion_mode_setting,
18311            buffer,
18312        ) {
18313            return insert_range.to_offset(buffer);
18314        }
18315    }
18316
18317    completion.replace_range.to_offset(buffer)
18318}
18319
18320fn insert_extra_newline_brackets(
18321    buffer: &MultiBufferSnapshot,
18322    range: Range<usize>,
18323    language: &language::LanguageScope,
18324) -> bool {
18325    let leading_whitespace_len = buffer
18326        .reversed_chars_at(range.start)
18327        .take_while(|c| c.is_whitespace() && *c != '\n')
18328        .map(|c| c.len_utf8())
18329        .sum::<usize>();
18330    let trailing_whitespace_len = buffer
18331        .chars_at(range.end)
18332        .take_while(|c| c.is_whitespace() && *c != '\n')
18333        .map(|c| c.len_utf8())
18334        .sum::<usize>();
18335    let range = range.start - leading_whitespace_len..range.end + trailing_whitespace_len;
18336
18337    language.brackets().any(|(pair, enabled)| {
18338        let pair_start = pair.start.trim_end();
18339        let pair_end = pair.end.trim_start();
18340
18341        enabled
18342            && pair.newline
18343            && buffer.contains_str_at(range.end, pair_end)
18344            && buffer.contains_str_at(range.start.saturating_sub(pair_start.len()), pair_start)
18345    })
18346}
18347
18348fn insert_extra_newline_tree_sitter(buffer: &MultiBufferSnapshot, range: Range<usize>) -> bool {
18349    let (buffer, range) = match buffer.range_to_buffer_ranges(range).as_slice() {
18350        [(buffer, range, _)] => (*buffer, range.clone()),
18351        _ => return false,
18352    };
18353    let pair = {
18354        let mut result: Option<BracketMatch> = None;
18355
18356        for pair in buffer
18357            .all_bracket_ranges(range.clone())
18358            .filter(move |pair| {
18359                pair.open_range.start <= range.start && pair.close_range.end >= range.end
18360            })
18361        {
18362            let len = pair.close_range.end - pair.open_range.start;
18363
18364            if let Some(existing) = &result {
18365                let existing_len = existing.close_range.end - existing.open_range.start;
18366                if len > existing_len {
18367                    continue;
18368                }
18369            }
18370
18371            result = Some(pair);
18372        }
18373
18374        result
18375    };
18376    let Some(pair) = pair else {
18377        return false;
18378    };
18379    pair.newline_only
18380        && buffer
18381            .chars_for_range(pair.open_range.end..range.start)
18382            .chain(buffer.chars_for_range(range.end..pair.close_range.start))
18383            .all(|c| c.is_whitespace() && c != '\n')
18384}
18385
18386fn get_uncommitted_diff_for_buffer(
18387    project: &Entity<Project>,
18388    buffers: impl IntoIterator<Item = Entity<Buffer>>,
18389    buffer: Entity<MultiBuffer>,
18390    cx: &mut App,
18391) -> Task<()> {
18392    let mut tasks = Vec::new();
18393    project.update(cx, |project, cx| {
18394        for buffer in buffers {
18395            if project::File::from_dyn(buffer.read(cx).file()).is_some() {
18396                tasks.push(project.open_uncommitted_diff(buffer.clone(), cx))
18397            }
18398        }
18399    });
18400    cx.spawn(async move |cx| {
18401        let diffs = future::join_all(tasks).await;
18402        buffer
18403            .update(cx, |buffer, cx| {
18404                for diff in diffs.into_iter().flatten() {
18405                    buffer.add_diff(diff, cx);
18406                }
18407            })
18408            .ok();
18409    })
18410}
18411
18412fn char_len_with_expanded_tabs(offset: usize, text: &str, tab_size: NonZeroU32) -> usize {
18413    let tab_size = tab_size.get() as usize;
18414    let mut width = offset;
18415
18416    for ch in text.chars() {
18417        width += if ch == '\t' {
18418            tab_size - (width % tab_size)
18419        } else {
18420            1
18421        };
18422    }
18423
18424    width - offset
18425}
18426
18427#[cfg(test)]
18428mod tests {
18429    use super::*;
18430
18431    #[test]
18432    fn test_string_size_with_expanded_tabs() {
18433        let nz = |val| NonZeroU32::new(val).unwrap();
18434        assert_eq!(char_len_with_expanded_tabs(0, "", nz(4)), 0);
18435        assert_eq!(char_len_with_expanded_tabs(0, "hello", nz(4)), 5);
18436        assert_eq!(char_len_with_expanded_tabs(0, "\thello", nz(4)), 9);
18437        assert_eq!(char_len_with_expanded_tabs(0, "abc\tab", nz(4)), 6);
18438        assert_eq!(char_len_with_expanded_tabs(0, "hello\t", nz(4)), 8);
18439        assert_eq!(char_len_with_expanded_tabs(0, "\t\t", nz(8)), 16);
18440        assert_eq!(char_len_with_expanded_tabs(0, "x\t", nz(8)), 8);
18441        assert_eq!(char_len_with_expanded_tabs(7, "x\t", nz(8)), 9);
18442    }
18443}
18444
18445/// Tokenizes a string into runs of text that should stick together, or that is whitespace.
18446struct WordBreakingTokenizer<'a> {
18447    input: &'a str,
18448}
18449
18450impl<'a> WordBreakingTokenizer<'a> {
18451    fn new(input: &'a str) -> Self {
18452        Self { input }
18453    }
18454}
18455
18456fn is_char_ideographic(ch: char) -> bool {
18457    use unicode_script::Script::*;
18458    use unicode_script::UnicodeScript;
18459    matches!(ch.script(), Han | Tangut | Yi)
18460}
18461
18462fn is_grapheme_ideographic(text: &str) -> bool {
18463    text.chars().any(is_char_ideographic)
18464}
18465
18466fn is_grapheme_whitespace(text: &str) -> bool {
18467    text.chars().any(|x| x.is_whitespace())
18468}
18469
18470fn should_stay_with_preceding_ideograph(text: &str) -> bool {
18471    text.chars().next().map_or(false, |ch| {
18472        matches!(ch, '。' | '、' | ',' | '?' | '!' | ':' | ';' | '…')
18473    })
18474}
18475
18476#[derive(PartialEq, Eq, Debug, Clone, Copy)]
18477enum WordBreakToken<'a> {
18478    Word { token: &'a str, grapheme_len: usize },
18479    InlineWhitespace { token: &'a str, grapheme_len: usize },
18480    Newline,
18481}
18482
18483impl<'a> Iterator for WordBreakingTokenizer<'a> {
18484    /// Yields a span, the count of graphemes in the token, and whether it was
18485    /// whitespace. Note that it also breaks at word boundaries.
18486    type Item = WordBreakToken<'a>;
18487
18488    fn next(&mut self) -> Option<Self::Item> {
18489        use unicode_segmentation::UnicodeSegmentation;
18490        if self.input.is_empty() {
18491            return None;
18492        }
18493
18494        let mut iter = self.input.graphemes(true).peekable();
18495        let mut offset = 0;
18496        let mut grapheme_len = 0;
18497        if let Some(first_grapheme) = iter.next() {
18498            let is_newline = first_grapheme == "\n";
18499            let is_whitespace = is_grapheme_whitespace(first_grapheme);
18500            offset += first_grapheme.len();
18501            grapheme_len += 1;
18502            if is_grapheme_ideographic(first_grapheme) && !is_whitespace {
18503                if let Some(grapheme) = iter.peek().copied() {
18504                    if should_stay_with_preceding_ideograph(grapheme) {
18505                        offset += grapheme.len();
18506                        grapheme_len += 1;
18507                    }
18508                }
18509            } else {
18510                let mut words = self.input[offset..].split_word_bound_indices().peekable();
18511                let mut next_word_bound = words.peek().copied();
18512                if next_word_bound.map_or(false, |(i, _)| i == 0) {
18513                    next_word_bound = words.next();
18514                }
18515                while let Some(grapheme) = iter.peek().copied() {
18516                    if next_word_bound.map_or(false, |(i, _)| i == offset) {
18517                        break;
18518                    };
18519                    if is_grapheme_whitespace(grapheme) != is_whitespace
18520                        || (grapheme == "\n") != is_newline
18521                    {
18522                        break;
18523                    };
18524                    offset += grapheme.len();
18525                    grapheme_len += 1;
18526                    iter.next();
18527                }
18528            }
18529            let token = &self.input[..offset];
18530            self.input = &self.input[offset..];
18531            if token == "\n" {
18532                Some(WordBreakToken::Newline)
18533            } else if is_whitespace {
18534                Some(WordBreakToken::InlineWhitespace {
18535                    token,
18536                    grapheme_len,
18537                })
18538            } else {
18539                Some(WordBreakToken::Word {
18540                    token,
18541                    grapheme_len,
18542                })
18543            }
18544        } else {
18545            None
18546        }
18547    }
18548}
18549
18550#[test]
18551fn test_word_breaking_tokenizer() {
18552    let tests: &[(&str, &[WordBreakToken<'static>])] = &[
18553        ("", &[]),
18554        ("  ", &[whitespace("  ", 2)]),
18555        ("Ʒ", &[word("Ʒ", 1)]),
18556        ("Ǽ", &[word("Ǽ", 1)]),
18557        ("", &[word("", 1)]),
18558        ("⋑⋑", &[word("⋑⋑", 2)]),
18559        (
18560            "原理,进而",
18561            &[word("", 1), word("理,", 2), word("", 1), word("", 1)],
18562        ),
18563        (
18564            "hello world",
18565            &[word("hello", 5), whitespace(" ", 1), word("world", 5)],
18566        ),
18567        (
18568            "hello, world",
18569            &[word("hello,", 6), whitespace(" ", 1), word("world", 5)],
18570        ),
18571        (
18572            "  hello world",
18573            &[
18574                whitespace("  ", 2),
18575                word("hello", 5),
18576                whitespace(" ", 1),
18577                word("world", 5),
18578            ],
18579        ),
18580        (
18581            "这是什么 \n 钢笔",
18582            &[
18583                word("", 1),
18584                word("", 1),
18585                word("", 1),
18586                word("", 1),
18587                whitespace(" ", 1),
18588                newline(),
18589                whitespace(" ", 1),
18590                word("", 1),
18591                word("", 1),
18592            ],
18593        ),
18594        (" mutton", &[whitespace("", 1), word("mutton", 6)]),
18595    ];
18596
18597    fn word(token: &'static str, grapheme_len: usize) -> WordBreakToken<'static> {
18598        WordBreakToken::Word {
18599            token,
18600            grapheme_len,
18601        }
18602    }
18603
18604    fn whitespace(token: &'static str, grapheme_len: usize) -> WordBreakToken<'static> {
18605        WordBreakToken::InlineWhitespace {
18606            token,
18607            grapheme_len,
18608        }
18609    }
18610
18611    fn newline() -> WordBreakToken<'static> {
18612        WordBreakToken::Newline
18613    }
18614
18615    for (input, result) in tests {
18616        assert_eq!(
18617            WordBreakingTokenizer::new(input)
18618                .collect::<Vec<_>>()
18619                .as_slice(),
18620            *result,
18621        );
18622    }
18623}
18624
18625fn wrap_with_prefix(
18626    line_prefix: String,
18627    unwrapped_text: String,
18628    wrap_column: usize,
18629    tab_size: NonZeroU32,
18630    preserve_existing_whitespace: bool,
18631) -> String {
18632    let line_prefix_len = char_len_with_expanded_tabs(0, &line_prefix, tab_size);
18633    let mut wrapped_text = String::new();
18634    let mut current_line = line_prefix.clone();
18635
18636    let tokenizer = WordBreakingTokenizer::new(&unwrapped_text);
18637    let mut current_line_len = line_prefix_len;
18638    let mut in_whitespace = false;
18639    for token in tokenizer {
18640        let have_preceding_whitespace = in_whitespace;
18641        match token {
18642            WordBreakToken::Word {
18643                token,
18644                grapheme_len,
18645            } => {
18646                in_whitespace = false;
18647                if current_line_len + grapheme_len > wrap_column
18648                    && current_line_len != line_prefix_len
18649                {
18650                    wrapped_text.push_str(current_line.trim_end());
18651                    wrapped_text.push('\n');
18652                    current_line.truncate(line_prefix.len());
18653                    current_line_len = line_prefix_len;
18654                }
18655                current_line.push_str(token);
18656                current_line_len += grapheme_len;
18657            }
18658            WordBreakToken::InlineWhitespace {
18659                mut token,
18660                mut grapheme_len,
18661            } => {
18662                in_whitespace = true;
18663                if have_preceding_whitespace && !preserve_existing_whitespace {
18664                    continue;
18665                }
18666                if !preserve_existing_whitespace {
18667                    token = " ";
18668                    grapheme_len = 1;
18669                }
18670                if current_line_len + grapheme_len > wrap_column {
18671                    wrapped_text.push_str(current_line.trim_end());
18672                    wrapped_text.push('\n');
18673                    current_line.truncate(line_prefix.len());
18674                    current_line_len = line_prefix_len;
18675                } else if current_line_len != line_prefix_len || preserve_existing_whitespace {
18676                    current_line.push_str(token);
18677                    current_line_len += grapheme_len;
18678                }
18679            }
18680            WordBreakToken::Newline => {
18681                in_whitespace = true;
18682                if preserve_existing_whitespace {
18683                    wrapped_text.push_str(current_line.trim_end());
18684                    wrapped_text.push('\n');
18685                    current_line.truncate(line_prefix.len());
18686                    current_line_len = line_prefix_len;
18687                } else if have_preceding_whitespace {
18688                    continue;
18689                } else if current_line_len + 1 > wrap_column && current_line_len != line_prefix_len
18690                {
18691                    wrapped_text.push_str(current_line.trim_end());
18692                    wrapped_text.push('\n');
18693                    current_line.truncate(line_prefix.len());
18694                    current_line_len = line_prefix_len;
18695                } else if current_line_len != line_prefix_len {
18696                    current_line.push(' ');
18697                    current_line_len += 1;
18698                }
18699            }
18700        }
18701    }
18702
18703    if !current_line.is_empty() {
18704        wrapped_text.push_str(&current_line);
18705    }
18706    wrapped_text
18707}
18708
18709#[test]
18710fn test_wrap_with_prefix() {
18711    assert_eq!(
18712        wrap_with_prefix(
18713            "# ".to_string(),
18714            "abcdefg".to_string(),
18715            4,
18716            NonZeroU32::new(4).unwrap(),
18717            false,
18718        ),
18719        "# abcdefg"
18720    );
18721    assert_eq!(
18722        wrap_with_prefix(
18723            "".to_string(),
18724            "\thello world".to_string(),
18725            8,
18726            NonZeroU32::new(4).unwrap(),
18727            false,
18728        ),
18729        "hello\nworld"
18730    );
18731    assert_eq!(
18732        wrap_with_prefix(
18733            "// ".to_string(),
18734            "xx \nyy zz aa bb cc".to_string(),
18735            12,
18736            NonZeroU32::new(4).unwrap(),
18737            false,
18738        ),
18739        "// xx yy zz\n// aa bb cc"
18740    );
18741    assert_eq!(
18742        wrap_with_prefix(
18743            String::new(),
18744            "这是什么 \n 钢笔".to_string(),
18745            3,
18746            NonZeroU32::new(4).unwrap(),
18747            false,
18748        ),
18749        "这是什\n么 钢\n"
18750    );
18751}
18752
18753pub trait CollaborationHub {
18754    fn collaborators<'a>(&self, cx: &'a App) -> &'a HashMap<PeerId, Collaborator>;
18755    fn user_participant_indices<'a>(&self, cx: &'a App) -> &'a HashMap<u64, ParticipantIndex>;
18756    fn user_names(&self, cx: &App) -> HashMap<u64, SharedString>;
18757}
18758
18759impl CollaborationHub for Entity<Project> {
18760    fn collaborators<'a>(&self, cx: &'a App) -> &'a HashMap<PeerId, Collaborator> {
18761        self.read(cx).collaborators()
18762    }
18763
18764    fn user_participant_indices<'a>(&self, cx: &'a App) -> &'a HashMap<u64, ParticipantIndex> {
18765        self.read(cx).user_store().read(cx).participant_indices()
18766    }
18767
18768    fn user_names(&self, cx: &App) -> HashMap<u64, SharedString> {
18769        let this = self.read(cx);
18770        let user_ids = this.collaborators().values().map(|c| c.user_id);
18771        this.user_store().read_with(cx, |user_store, cx| {
18772            user_store.participant_names(user_ids, cx)
18773        })
18774    }
18775}
18776
18777pub trait SemanticsProvider {
18778    fn hover(
18779        &self,
18780        buffer: &Entity<Buffer>,
18781        position: text::Anchor,
18782        cx: &mut App,
18783    ) -> Option<Task<Vec<project::Hover>>>;
18784
18785    fn inlay_hints(
18786        &self,
18787        buffer_handle: Entity<Buffer>,
18788        range: Range<text::Anchor>,
18789        cx: &mut App,
18790    ) -> Option<Task<anyhow::Result<Vec<InlayHint>>>>;
18791
18792    fn resolve_inlay_hint(
18793        &self,
18794        hint: InlayHint,
18795        buffer_handle: Entity<Buffer>,
18796        server_id: LanguageServerId,
18797        cx: &mut App,
18798    ) -> Option<Task<anyhow::Result<InlayHint>>>;
18799
18800    fn supports_inlay_hints(&self, buffer: &Entity<Buffer>, cx: &mut App) -> bool;
18801
18802    fn document_highlights(
18803        &self,
18804        buffer: &Entity<Buffer>,
18805        position: text::Anchor,
18806        cx: &mut App,
18807    ) -> Option<Task<Result<Vec<DocumentHighlight>>>>;
18808
18809    fn definitions(
18810        &self,
18811        buffer: &Entity<Buffer>,
18812        position: text::Anchor,
18813        kind: GotoDefinitionKind,
18814        cx: &mut App,
18815    ) -> Option<Task<Result<Vec<LocationLink>>>>;
18816
18817    fn range_for_rename(
18818        &self,
18819        buffer: &Entity<Buffer>,
18820        position: text::Anchor,
18821        cx: &mut App,
18822    ) -> Option<Task<Result<Option<Range<text::Anchor>>>>>;
18823
18824    fn perform_rename(
18825        &self,
18826        buffer: &Entity<Buffer>,
18827        position: text::Anchor,
18828        new_name: String,
18829        cx: &mut App,
18830    ) -> Option<Task<Result<ProjectTransaction>>>;
18831}
18832
18833pub trait CompletionProvider {
18834    fn completions(
18835        &self,
18836        excerpt_id: ExcerptId,
18837        buffer: &Entity<Buffer>,
18838        buffer_position: text::Anchor,
18839        trigger: CompletionContext,
18840        window: &mut Window,
18841        cx: &mut Context<Editor>,
18842    ) -> Task<Result<Option<Vec<Completion>>>>;
18843
18844    fn resolve_completions(
18845        &self,
18846        buffer: Entity<Buffer>,
18847        completion_indices: Vec<usize>,
18848        completions: Rc<RefCell<Box<[Completion]>>>,
18849        cx: &mut Context<Editor>,
18850    ) -> Task<Result<bool>>;
18851
18852    fn apply_additional_edits_for_completion(
18853        &self,
18854        _buffer: Entity<Buffer>,
18855        _completions: Rc<RefCell<Box<[Completion]>>>,
18856        _completion_index: usize,
18857        _push_to_history: bool,
18858        _cx: &mut Context<Editor>,
18859    ) -> Task<Result<Option<language::Transaction>>> {
18860        Task::ready(Ok(None))
18861    }
18862
18863    fn is_completion_trigger(
18864        &self,
18865        buffer: &Entity<Buffer>,
18866        position: language::Anchor,
18867        text: &str,
18868        trigger_in_words: bool,
18869        cx: &mut Context<Editor>,
18870    ) -> bool;
18871
18872    fn sort_completions(&self) -> bool {
18873        true
18874    }
18875
18876    fn filter_completions(&self) -> bool {
18877        true
18878    }
18879}
18880
18881pub trait CodeActionProvider {
18882    fn id(&self) -> Arc<str>;
18883
18884    fn code_actions(
18885        &self,
18886        buffer: &Entity<Buffer>,
18887        range: Range<text::Anchor>,
18888        window: &mut Window,
18889        cx: &mut App,
18890    ) -> Task<Result<Vec<CodeAction>>>;
18891
18892    fn apply_code_action(
18893        &self,
18894        buffer_handle: Entity<Buffer>,
18895        action: CodeAction,
18896        excerpt_id: ExcerptId,
18897        push_to_history: bool,
18898        window: &mut Window,
18899        cx: &mut App,
18900    ) -> Task<Result<ProjectTransaction>>;
18901}
18902
18903impl CodeActionProvider for Entity<Project> {
18904    fn id(&self) -> Arc<str> {
18905        "project".into()
18906    }
18907
18908    fn code_actions(
18909        &self,
18910        buffer: &Entity<Buffer>,
18911        range: Range<text::Anchor>,
18912        _window: &mut Window,
18913        cx: &mut App,
18914    ) -> Task<Result<Vec<CodeAction>>> {
18915        self.update(cx, |project, cx| {
18916            let code_lens = project.code_lens(buffer, range.clone(), cx);
18917            let code_actions = project.code_actions(buffer, range, None, cx);
18918            cx.background_spawn(async move {
18919                let (code_lens, code_actions) = join(code_lens, code_actions).await;
18920                Ok(code_lens
18921                    .context("code lens fetch")?
18922                    .into_iter()
18923                    .chain(code_actions.context("code action fetch")?)
18924                    .collect())
18925            })
18926        })
18927    }
18928
18929    fn apply_code_action(
18930        &self,
18931        buffer_handle: Entity<Buffer>,
18932        action: CodeAction,
18933        _excerpt_id: ExcerptId,
18934        push_to_history: bool,
18935        _window: &mut Window,
18936        cx: &mut App,
18937    ) -> Task<Result<ProjectTransaction>> {
18938        self.update(cx, |project, cx| {
18939            project.apply_code_action(buffer_handle, action, push_to_history, cx)
18940        })
18941    }
18942}
18943
18944fn snippet_completions(
18945    project: &Project,
18946    buffer: &Entity<Buffer>,
18947    buffer_position: text::Anchor,
18948    cx: &mut App,
18949) -> Task<Result<Vec<Completion>>> {
18950    let languages = buffer.read(cx).languages_at(buffer_position);
18951    let snippet_store = project.snippets().read(cx);
18952
18953    let scopes: Vec<_> = languages
18954        .iter()
18955        .filter_map(|language| {
18956            let language_name = language.lsp_id();
18957            let snippets = snippet_store.snippets_for(Some(language_name), cx);
18958
18959            if snippets.is_empty() {
18960                None
18961            } else {
18962                Some((language.default_scope(), snippets))
18963            }
18964        })
18965        .collect();
18966
18967    if scopes.is_empty() {
18968        return Task::ready(Ok(vec![]));
18969    }
18970
18971    let snapshot = buffer.read(cx).text_snapshot();
18972    let chars: String = snapshot
18973        .reversed_chars_for_range(text::Anchor::MIN..buffer_position)
18974        .collect();
18975    let executor = cx.background_executor().clone();
18976
18977    cx.background_spawn(async move {
18978        let mut all_results: Vec<Completion> = Vec::new();
18979        for (scope, snippets) in scopes.into_iter() {
18980            let classifier = CharClassifier::new(Some(scope)).for_completion(true);
18981            let mut last_word = chars
18982                .chars()
18983                .take_while(|c| classifier.is_word(*c))
18984                .collect::<String>();
18985            last_word = last_word.chars().rev().collect();
18986
18987            if last_word.is_empty() {
18988                return Ok(vec![]);
18989            }
18990
18991            let as_offset = text::ToOffset::to_offset(&buffer_position, &snapshot);
18992            let to_lsp = |point: &text::Anchor| {
18993                let end = text::ToPointUtf16::to_point_utf16(point, &snapshot);
18994                point_to_lsp(end)
18995            };
18996            let lsp_end = to_lsp(&buffer_position);
18997
18998            let candidates = snippets
18999                .iter()
19000                .enumerate()
19001                .flat_map(|(ix, snippet)| {
19002                    snippet
19003                        .prefix
19004                        .iter()
19005                        .map(move |prefix| StringMatchCandidate::new(ix, &prefix))
19006                })
19007                .collect::<Vec<StringMatchCandidate>>();
19008
19009            let mut matches = fuzzy::match_strings(
19010                &candidates,
19011                &last_word,
19012                last_word.chars().any(|c| c.is_uppercase()),
19013                100,
19014                &Default::default(),
19015                executor.clone(),
19016            )
19017            .await;
19018
19019            // Remove all candidates where the query's start does not match the start of any word in the candidate
19020            if let Some(query_start) = last_word.chars().next() {
19021                matches.retain(|string_match| {
19022                    split_words(&string_match.string).any(|word| {
19023                        // Check that the first codepoint of the word as lowercase matches the first
19024                        // codepoint of the query as lowercase
19025                        word.chars()
19026                            .flat_map(|codepoint| codepoint.to_lowercase())
19027                            .zip(query_start.to_lowercase())
19028                            .all(|(word_cp, query_cp)| word_cp == query_cp)
19029                    })
19030                });
19031            }
19032
19033            let matched_strings = matches
19034                .into_iter()
19035                .map(|m| m.string)
19036                .collect::<HashSet<_>>();
19037
19038            let mut result: Vec<Completion> = snippets
19039                .iter()
19040                .filter_map(|snippet| {
19041                    let matching_prefix = snippet
19042                        .prefix
19043                        .iter()
19044                        .find(|prefix| matched_strings.contains(*prefix))?;
19045                    let start = as_offset - last_word.len();
19046                    let start = snapshot.anchor_before(start);
19047                    let range = start..buffer_position;
19048                    let lsp_start = to_lsp(&start);
19049                    let lsp_range = lsp::Range {
19050                        start: lsp_start,
19051                        end: lsp_end,
19052                    };
19053                    Some(Completion {
19054                        replace_range: range,
19055                        new_text: snippet.body.clone(),
19056                        source: CompletionSource::Lsp {
19057                            insert_range: None,
19058                            server_id: LanguageServerId(usize::MAX),
19059                            resolved: true,
19060                            lsp_completion: Box::new(lsp::CompletionItem {
19061                                label: snippet.prefix.first().unwrap().clone(),
19062                                kind: Some(CompletionItemKind::SNIPPET),
19063                                label_details: snippet.description.as_ref().map(|description| {
19064                                    lsp::CompletionItemLabelDetails {
19065                                        detail: Some(description.clone()),
19066                                        description: None,
19067                                    }
19068                                }),
19069                                insert_text_format: Some(InsertTextFormat::SNIPPET),
19070                                text_edit: Some(lsp::CompletionTextEdit::InsertAndReplace(
19071                                    lsp::InsertReplaceEdit {
19072                                        new_text: snippet.body.clone(),
19073                                        insert: lsp_range,
19074                                        replace: lsp_range,
19075                                    },
19076                                )),
19077                                filter_text: Some(snippet.body.clone()),
19078                                sort_text: Some(char::MAX.to_string()),
19079                                ..lsp::CompletionItem::default()
19080                            }),
19081                            lsp_defaults: None,
19082                        },
19083                        label: CodeLabel {
19084                            text: matching_prefix.clone(),
19085                            runs: Vec::new(),
19086                            filter_range: 0..matching_prefix.len(),
19087                        },
19088                        icon_path: None,
19089                        documentation: snippet.description.clone().map(|description| {
19090                            CompletionDocumentation::SingleLine(description.into())
19091                        }),
19092                        insert_text_mode: None,
19093                        confirm: None,
19094                    })
19095                })
19096                .collect();
19097
19098            all_results.append(&mut result);
19099        }
19100
19101        Ok(all_results)
19102    })
19103}
19104
19105impl CompletionProvider for Entity<Project> {
19106    fn completions(
19107        &self,
19108        _excerpt_id: ExcerptId,
19109        buffer: &Entity<Buffer>,
19110        buffer_position: text::Anchor,
19111        options: CompletionContext,
19112        _window: &mut Window,
19113        cx: &mut Context<Editor>,
19114    ) -> Task<Result<Option<Vec<Completion>>>> {
19115        self.update(cx, |project, cx| {
19116            let snippets = snippet_completions(project, buffer, buffer_position, cx);
19117            let project_completions = project.completions(buffer, buffer_position, options, cx);
19118            cx.background_spawn(async move {
19119                let snippets_completions = snippets.await?;
19120                match project_completions.await? {
19121                    Some(mut completions) => {
19122                        completions.extend(snippets_completions);
19123                        Ok(Some(completions))
19124                    }
19125                    None => {
19126                        if snippets_completions.is_empty() {
19127                            Ok(None)
19128                        } else {
19129                            Ok(Some(snippets_completions))
19130                        }
19131                    }
19132                }
19133            })
19134        })
19135    }
19136
19137    fn resolve_completions(
19138        &self,
19139        buffer: Entity<Buffer>,
19140        completion_indices: Vec<usize>,
19141        completions: Rc<RefCell<Box<[Completion]>>>,
19142        cx: &mut Context<Editor>,
19143    ) -> Task<Result<bool>> {
19144        self.update(cx, |project, cx| {
19145            project.lsp_store().update(cx, |lsp_store, cx| {
19146                lsp_store.resolve_completions(buffer, completion_indices, completions, cx)
19147            })
19148        })
19149    }
19150
19151    fn apply_additional_edits_for_completion(
19152        &self,
19153        buffer: Entity<Buffer>,
19154        completions: Rc<RefCell<Box<[Completion]>>>,
19155        completion_index: usize,
19156        push_to_history: bool,
19157        cx: &mut Context<Editor>,
19158    ) -> Task<Result<Option<language::Transaction>>> {
19159        self.update(cx, |project, cx| {
19160            project.lsp_store().update(cx, |lsp_store, cx| {
19161                lsp_store.apply_additional_edits_for_completion(
19162                    buffer,
19163                    completions,
19164                    completion_index,
19165                    push_to_history,
19166                    cx,
19167                )
19168            })
19169        })
19170    }
19171
19172    fn is_completion_trigger(
19173        &self,
19174        buffer: &Entity<Buffer>,
19175        position: language::Anchor,
19176        text: &str,
19177        trigger_in_words: bool,
19178        cx: &mut Context<Editor>,
19179    ) -> bool {
19180        let mut chars = text.chars();
19181        let char = if let Some(char) = chars.next() {
19182            char
19183        } else {
19184            return false;
19185        };
19186        if chars.next().is_some() {
19187            return false;
19188        }
19189
19190        let buffer = buffer.read(cx);
19191        let snapshot = buffer.snapshot();
19192        if !snapshot.settings_at(position, cx).show_completions_on_input {
19193            return false;
19194        }
19195        let classifier = snapshot.char_classifier_at(position).for_completion(true);
19196        if trigger_in_words && classifier.is_word(char) {
19197            return true;
19198        }
19199
19200        buffer.completion_triggers().contains(text)
19201    }
19202}
19203
19204impl SemanticsProvider for Entity<Project> {
19205    fn hover(
19206        &self,
19207        buffer: &Entity<Buffer>,
19208        position: text::Anchor,
19209        cx: &mut App,
19210    ) -> Option<Task<Vec<project::Hover>>> {
19211        Some(self.update(cx, |project, cx| project.hover(buffer, position, cx)))
19212    }
19213
19214    fn document_highlights(
19215        &self,
19216        buffer: &Entity<Buffer>,
19217        position: text::Anchor,
19218        cx: &mut App,
19219    ) -> Option<Task<Result<Vec<DocumentHighlight>>>> {
19220        Some(self.update(cx, |project, cx| {
19221            project.document_highlights(buffer, position, cx)
19222        }))
19223    }
19224
19225    fn definitions(
19226        &self,
19227        buffer: &Entity<Buffer>,
19228        position: text::Anchor,
19229        kind: GotoDefinitionKind,
19230        cx: &mut App,
19231    ) -> Option<Task<Result<Vec<LocationLink>>>> {
19232        Some(self.update(cx, |project, cx| match kind {
19233            GotoDefinitionKind::Symbol => project.definition(&buffer, position, cx),
19234            GotoDefinitionKind::Declaration => project.declaration(&buffer, position, cx),
19235            GotoDefinitionKind::Type => project.type_definition(&buffer, position, cx),
19236            GotoDefinitionKind::Implementation => project.implementation(&buffer, position, cx),
19237        }))
19238    }
19239
19240    fn supports_inlay_hints(&self, buffer: &Entity<Buffer>, cx: &mut App) -> bool {
19241        // TODO: make this work for remote projects
19242        self.update(cx, |this, cx| {
19243            buffer.update(cx, |buffer, cx| {
19244                this.any_language_server_supports_inlay_hints(buffer, cx)
19245            })
19246        })
19247    }
19248
19249    fn inlay_hints(
19250        &self,
19251        buffer_handle: Entity<Buffer>,
19252        range: Range<text::Anchor>,
19253        cx: &mut App,
19254    ) -> Option<Task<anyhow::Result<Vec<InlayHint>>>> {
19255        Some(self.update(cx, |project, cx| {
19256            project.inlay_hints(buffer_handle, range, cx)
19257        }))
19258    }
19259
19260    fn resolve_inlay_hint(
19261        &self,
19262        hint: InlayHint,
19263        buffer_handle: Entity<Buffer>,
19264        server_id: LanguageServerId,
19265        cx: &mut App,
19266    ) -> Option<Task<anyhow::Result<InlayHint>>> {
19267        Some(self.update(cx, |project, cx| {
19268            project.resolve_inlay_hint(hint, buffer_handle, server_id, cx)
19269        }))
19270    }
19271
19272    fn range_for_rename(
19273        &self,
19274        buffer: &Entity<Buffer>,
19275        position: text::Anchor,
19276        cx: &mut App,
19277    ) -> Option<Task<Result<Option<Range<text::Anchor>>>>> {
19278        Some(self.update(cx, |project, cx| {
19279            let buffer = buffer.clone();
19280            let task = project.prepare_rename(buffer.clone(), position, cx);
19281            cx.spawn(async move |_, cx| {
19282                Ok(match task.await? {
19283                    PrepareRenameResponse::Success(range) => Some(range),
19284                    PrepareRenameResponse::InvalidPosition => None,
19285                    PrepareRenameResponse::OnlyUnpreparedRenameSupported => {
19286                        // Fallback on using TreeSitter info to determine identifier range
19287                        buffer.update(cx, |buffer, _| {
19288                            let snapshot = buffer.snapshot();
19289                            let (range, kind) = snapshot.surrounding_word(position);
19290                            if kind != Some(CharKind::Word) {
19291                                return None;
19292                            }
19293                            Some(
19294                                snapshot.anchor_before(range.start)
19295                                    ..snapshot.anchor_after(range.end),
19296                            )
19297                        })?
19298                    }
19299                })
19300            })
19301        }))
19302    }
19303
19304    fn perform_rename(
19305        &self,
19306        buffer: &Entity<Buffer>,
19307        position: text::Anchor,
19308        new_name: String,
19309        cx: &mut App,
19310    ) -> Option<Task<Result<ProjectTransaction>>> {
19311        Some(self.update(cx, |project, cx| {
19312            project.perform_rename(buffer.clone(), position, new_name, cx)
19313        }))
19314    }
19315}
19316
19317fn inlay_hint_settings(
19318    location: Anchor,
19319    snapshot: &MultiBufferSnapshot,
19320    cx: &mut Context<Editor>,
19321) -> InlayHintSettings {
19322    let file = snapshot.file_at(location);
19323    let language = snapshot.language_at(location).map(|l| l.name());
19324    language_settings(language, file, cx).inlay_hints
19325}
19326
19327fn consume_contiguous_rows(
19328    contiguous_row_selections: &mut Vec<Selection<Point>>,
19329    selection: &Selection<Point>,
19330    display_map: &DisplaySnapshot,
19331    selections: &mut Peekable<std::slice::Iter<Selection<Point>>>,
19332) -> (MultiBufferRow, MultiBufferRow) {
19333    contiguous_row_selections.push(selection.clone());
19334    let start_row = MultiBufferRow(selection.start.row);
19335    let mut end_row = ending_row(selection, display_map);
19336
19337    while let Some(next_selection) = selections.peek() {
19338        if next_selection.start.row <= end_row.0 {
19339            end_row = ending_row(next_selection, display_map);
19340            contiguous_row_selections.push(selections.next().unwrap().clone());
19341        } else {
19342            break;
19343        }
19344    }
19345    (start_row, end_row)
19346}
19347
19348fn ending_row(next_selection: &Selection<Point>, display_map: &DisplaySnapshot) -> MultiBufferRow {
19349    if next_selection.end.column > 0 || next_selection.is_empty() {
19350        MultiBufferRow(display_map.next_line_boundary(next_selection.end).0.row + 1)
19351    } else {
19352        MultiBufferRow(next_selection.end.row)
19353    }
19354}
19355
19356impl EditorSnapshot {
19357    pub fn remote_selections_in_range<'a>(
19358        &'a self,
19359        range: &'a Range<Anchor>,
19360        collaboration_hub: &dyn CollaborationHub,
19361        cx: &'a App,
19362    ) -> impl 'a + Iterator<Item = RemoteSelection> {
19363        let participant_names = collaboration_hub.user_names(cx);
19364        let participant_indices = collaboration_hub.user_participant_indices(cx);
19365        let collaborators_by_peer_id = collaboration_hub.collaborators(cx);
19366        let collaborators_by_replica_id = collaborators_by_peer_id
19367            .iter()
19368            .map(|(_, collaborator)| (collaborator.replica_id, collaborator))
19369            .collect::<HashMap<_, _>>();
19370        self.buffer_snapshot
19371            .selections_in_range(range, false)
19372            .filter_map(move |(replica_id, line_mode, cursor_shape, selection)| {
19373                let collaborator = collaborators_by_replica_id.get(&replica_id)?;
19374                let participant_index = participant_indices.get(&collaborator.user_id).copied();
19375                let user_name = participant_names.get(&collaborator.user_id).cloned();
19376                Some(RemoteSelection {
19377                    replica_id,
19378                    selection,
19379                    cursor_shape,
19380                    line_mode,
19381                    participant_index,
19382                    peer_id: collaborator.peer_id,
19383                    user_name,
19384                })
19385            })
19386    }
19387
19388    pub fn hunks_for_ranges(
19389        &self,
19390        ranges: impl IntoIterator<Item = Range<Point>>,
19391    ) -> Vec<MultiBufferDiffHunk> {
19392        let mut hunks = Vec::new();
19393        let mut processed_buffer_rows: HashMap<BufferId, HashSet<Range<text::Anchor>>> =
19394            HashMap::default();
19395        for query_range in ranges {
19396            let query_rows =
19397                MultiBufferRow(query_range.start.row)..MultiBufferRow(query_range.end.row + 1);
19398            for hunk in self.buffer_snapshot.diff_hunks_in_range(
19399                Point::new(query_rows.start.0, 0)..Point::new(query_rows.end.0, 0),
19400            ) {
19401                // Include deleted hunks that are adjacent to the query range, because
19402                // otherwise they would be missed.
19403                let mut intersects_range = hunk.row_range.overlaps(&query_rows);
19404                if hunk.status().is_deleted() {
19405                    intersects_range |= hunk.row_range.start == query_rows.end;
19406                    intersects_range |= hunk.row_range.end == query_rows.start;
19407                }
19408                if intersects_range {
19409                    if !processed_buffer_rows
19410                        .entry(hunk.buffer_id)
19411                        .or_default()
19412                        .insert(hunk.buffer_range.start..hunk.buffer_range.end)
19413                    {
19414                        continue;
19415                    }
19416                    hunks.push(hunk);
19417                }
19418            }
19419        }
19420
19421        hunks
19422    }
19423
19424    fn display_diff_hunks_for_rows<'a>(
19425        &'a self,
19426        display_rows: Range<DisplayRow>,
19427        folded_buffers: &'a HashSet<BufferId>,
19428    ) -> impl 'a + Iterator<Item = DisplayDiffHunk> {
19429        let buffer_start = DisplayPoint::new(display_rows.start, 0).to_point(self);
19430        let buffer_end = DisplayPoint::new(display_rows.end, 0).to_point(self);
19431
19432        self.buffer_snapshot
19433            .diff_hunks_in_range(buffer_start..buffer_end)
19434            .filter_map(|hunk| {
19435                if folded_buffers.contains(&hunk.buffer_id) {
19436                    return None;
19437                }
19438
19439                let hunk_start_point = Point::new(hunk.row_range.start.0, 0);
19440                let hunk_end_point = Point::new(hunk.row_range.end.0, 0);
19441
19442                let hunk_display_start = self.point_to_display_point(hunk_start_point, Bias::Left);
19443                let hunk_display_end = self.point_to_display_point(hunk_end_point, Bias::Right);
19444
19445                let display_hunk = if hunk_display_start.column() != 0 {
19446                    DisplayDiffHunk::Folded {
19447                        display_row: hunk_display_start.row(),
19448                    }
19449                } else {
19450                    let mut end_row = hunk_display_end.row();
19451                    if hunk_display_end.column() > 0 {
19452                        end_row.0 += 1;
19453                    }
19454                    let is_created_file = hunk.is_created_file();
19455                    DisplayDiffHunk::Unfolded {
19456                        status: hunk.status(),
19457                        diff_base_byte_range: hunk.diff_base_byte_range,
19458                        display_row_range: hunk_display_start.row()..end_row,
19459                        multi_buffer_range: Anchor::range_in_buffer(
19460                            hunk.excerpt_id,
19461                            hunk.buffer_id,
19462                            hunk.buffer_range,
19463                        ),
19464                        is_created_file,
19465                    }
19466                };
19467
19468                Some(display_hunk)
19469            })
19470    }
19471
19472    pub fn language_at<T: ToOffset>(&self, position: T) -> Option<&Arc<Language>> {
19473        self.display_snapshot.buffer_snapshot.language_at(position)
19474    }
19475
19476    pub fn is_focused(&self) -> bool {
19477        self.is_focused
19478    }
19479
19480    pub fn placeholder_text(&self) -> Option<&Arc<str>> {
19481        self.placeholder_text.as_ref()
19482    }
19483
19484    pub fn scroll_position(&self) -> gpui::Point<f32> {
19485        self.scroll_anchor.scroll_position(&self.display_snapshot)
19486    }
19487
19488    fn gutter_dimensions(
19489        &self,
19490        font_id: FontId,
19491        font_size: Pixels,
19492        max_line_number_width: Pixels,
19493        cx: &App,
19494    ) -> Option<GutterDimensions> {
19495        if !self.show_gutter {
19496            return None;
19497        }
19498
19499        let descent = cx.text_system().descent(font_id, font_size);
19500        let em_width = cx.text_system().em_width(font_id, font_size).log_err()?;
19501        let em_advance = cx.text_system().em_advance(font_id, font_size).log_err()?;
19502
19503        let show_git_gutter = self.show_git_diff_gutter.unwrap_or_else(|| {
19504            matches!(
19505                ProjectSettings::get_global(cx).git.git_gutter,
19506                Some(GitGutterSetting::TrackedFiles)
19507            )
19508        });
19509        let gutter_settings = EditorSettings::get_global(cx).gutter;
19510        let show_line_numbers = self
19511            .show_line_numbers
19512            .unwrap_or(gutter_settings.line_numbers);
19513        let line_gutter_width = if show_line_numbers {
19514            // Avoid flicker-like gutter resizes when the line number gains another digit and only resize the gutter on files with N*10^5 lines.
19515            let min_width_for_number_on_gutter = em_advance * MIN_LINE_NUMBER_DIGITS as f32;
19516            max_line_number_width.max(min_width_for_number_on_gutter)
19517        } else {
19518            0.0.into()
19519        };
19520
19521        let show_code_actions = self
19522            .show_code_actions
19523            .unwrap_or(gutter_settings.code_actions);
19524
19525        let show_runnables = self.show_runnables.unwrap_or(gutter_settings.runnables);
19526        let show_breakpoints = self.show_breakpoints.unwrap_or(gutter_settings.breakpoints);
19527
19528        let git_blame_entries_width =
19529            self.git_blame_gutter_max_author_length
19530                .map(|max_author_length| {
19531                    let renderer = cx.global::<GlobalBlameRenderer>().0.clone();
19532                    const MAX_RELATIVE_TIMESTAMP: &str = "60 minutes ago";
19533
19534                    /// The number of characters to dedicate to gaps and margins.
19535                    const SPACING_WIDTH: usize = 4;
19536
19537                    let max_char_count = max_author_length.min(renderer.max_author_length())
19538                        + ::git::SHORT_SHA_LENGTH
19539                        + MAX_RELATIVE_TIMESTAMP.len()
19540                        + SPACING_WIDTH;
19541
19542                    em_advance * max_char_count
19543                });
19544
19545        let is_singleton = self.buffer_snapshot.is_singleton();
19546
19547        let mut left_padding = git_blame_entries_width.unwrap_or(Pixels::ZERO);
19548        left_padding += if !is_singleton {
19549            em_width * 4.0
19550        } else if show_code_actions || show_runnables || show_breakpoints {
19551            em_width * 3.0
19552        } else if show_git_gutter && show_line_numbers {
19553            em_width * 2.0
19554        } else if show_git_gutter || show_line_numbers {
19555            em_width
19556        } else {
19557            px(0.)
19558        };
19559
19560        let shows_folds = is_singleton && gutter_settings.folds;
19561
19562        let right_padding = if shows_folds && show_line_numbers {
19563            em_width * 4.0
19564        } else if shows_folds || (!is_singleton && show_line_numbers) {
19565            em_width * 3.0
19566        } else if show_line_numbers {
19567            em_width
19568        } else {
19569            px(0.)
19570        };
19571
19572        Some(GutterDimensions {
19573            left_padding,
19574            right_padding,
19575            width: line_gutter_width + left_padding + right_padding,
19576            margin: -descent,
19577            git_blame_entries_width,
19578        })
19579    }
19580
19581    pub fn render_crease_toggle(
19582        &self,
19583        buffer_row: MultiBufferRow,
19584        row_contains_cursor: bool,
19585        editor: Entity<Editor>,
19586        window: &mut Window,
19587        cx: &mut App,
19588    ) -> Option<AnyElement> {
19589        let folded = self.is_line_folded(buffer_row);
19590        let mut is_foldable = false;
19591
19592        if let Some(crease) = self
19593            .crease_snapshot
19594            .query_row(buffer_row, &self.buffer_snapshot)
19595        {
19596            is_foldable = true;
19597            match crease {
19598                Crease::Inline { render_toggle, .. } | Crease::Block { render_toggle, .. } => {
19599                    if let Some(render_toggle) = render_toggle {
19600                        let toggle_callback =
19601                            Arc::new(move |folded, window: &mut Window, cx: &mut App| {
19602                                if folded {
19603                                    editor.update(cx, |editor, cx| {
19604                                        editor.fold_at(buffer_row, window, cx)
19605                                    });
19606                                } else {
19607                                    editor.update(cx, |editor, cx| {
19608                                        editor.unfold_at(buffer_row, window, cx)
19609                                    });
19610                                }
19611                            });
19612                        return Some((render_toggle)(
19613                            buffer_row,
19614                            folded,
19615                            toggle_callback,
19616                            window,
19617                            cx,
19618                        ));
19619                    }
19620                }
19621            }
19622        }
19623
19624        is_foldable |= self.starts_indent(buffer_row);
19625
19626        if folded || (is_foldable && (row_contains_cursor || self.gutter_hovered)) {
19627            Some(
19628                Disclosure::new(("gutter_crease", buffer_row.0), !folded)
19629                    .toggle_state(folded)
19630                    .on_click(window.listener_for(&editor, move |this, _e, window, cx| {
19631                        if folded {
19632                            this.unfold_at(buffer_row, window, cx);
19633                        } else {
19634                            this.fold_at(buffer_row, window, cx);
19635                        }
19636                    }))
19637                    .into_any_element(),
19638            )
19639        } else {
19640            None
19641        }
19642    }
19643
19644    pub fn render_crease_trailer(
19645        &self,
19646        buffer_row: MultiBufferRow,
19647        window: &mut Window,
19648        cx: &mut App,
19649    ) -> Option<AnyElement> {
19650        let folded = self.is_line_folded(buffer_row);
19651        if let Crease::Inline { render_trailer, .. } = self
19652            .crease_snapshot
19653            .query_row(buffer_row, &self.buffer_snapshot)?
19654        {
19655            let render_trailer = render_trailer.as_ref()?;
19656            Some(render_trailer(buffer_row, folded, window, cx))
19657        } else {
19658            None
19659        }
19660    }
19661}
19662
19663impl Deref for EditorSnapshot {
19664    type Target = DisplaySnapshot;
19665
19666    fn deref(&self) -> &Self::Target {
19667        &self.display_snapshot
19668    }
19669}
19670
19671#[derive(Clone, Debug, PartialEq, Eq)]
19672pub enum EditorEvent {
19673    InputIgnored {
19674        text: Arc<str>,
19675    },
19676    InputHandled {
19677        utf16_range_to_replace: Option<Range<isize>>,
19678        text: Arc<str>,
19679    },
19680    ExcerptsAdded {
19681        buffer: Entity<Buffer>,
19682        predecessor: ExcerptId,
19683        excerpts: Vec<(ExcerptId, ExcerptRange<language::Anchor>)>,
19684    },
19685    ExcerptsRemoved {
19686        ids: Vec<ExcerptId>,
19687    },
19688    BufferFoldToggled {
19689        ids: Vec<ExcerptId>,
19690        folded: bool,
19691    },
19692    ExcerptsEdited {
19693        ids: Vec<ExcerptId>,
19694    },
19695    ExcerptsExpanded {
19696        ids: Vec<ExcerptId>,
19697    },
19698    BufferEdited,
19699    Edited {
19700        transaction_id: clock::Lamport,
19701    },
19702    Reparsed(BufferId),
19703    Focused,
19704    FocusedIn,
19705    Blurred,
19706    DirtyChanged,
19707    Saved,
19708    TitleChanged,
19709    DiffBaseChanged,
19710    SelectionsChanged {
19711        local: bool,
19712    },
19713    ScrollPositionChanged {
19714        local: bool,
19715        autoscroll: bool,
19716    },
19717    Closed,
19718    TransactionUndone {
19719        transaction_id: clock::Lamport,
19720    },
19721    TransactionBegun {
19722        transaction_id: clock::Lamport,
19723    },
19724    Reloaded,
19725    CursorShapeChanged,
19726    PushedToNavHistory {
19727        anchor: Anchor,
19728        is_deactivate: bool,
19729    },
19730}
19731
19732impl EventEmitter<EditorEvent> for Editor {}
19733
19734impl Focusable for Editor {
19735    fn focus_handle(&self, _cx: &App) -> FocusHandle {
19736        self.focus_handle.clone()
19737    }
19738}
19739
19740impl Render for Editor {
19741    fn render(&mut self, _: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
19742        let settings = ThemeSettings::get_global(cx);
19743
19744        let mut text_style = match self.mode {
19745            EditorMode::SingleLine { .. } | EditorMode::AutoHeight { .. } => TextStyle {
19746                color: cx.theme().colors().editor_foreground,
19747                font_family: settings.ui_font.family.clone(),
19748                font_features: settings.ui_font.features.clone(),
19749                font_fallbacks: settings.ui_font.fallbacks.clone(),
19750                font_size: rems(0.875).into(),
19751                font_weight: settings.ui_font.weight,
19752                line_height: relative(settings.buffer_line_height.value()),
19753                ..Default::default()
19754            },
19755            EditorMode::Full { .. } => TextStyle {
19756                color: cx.theme().colors().editor_foreground,
19757                font_family: settings.buffer_font.family.clone(),
19758                font_features: settings.buffer_font.features.clone(),
19759                font_fallbacks: settings.buffer_font.fallbacks.clone(),
19760                font_size: settings.buffer_font_size(cx).into(),
19761                font_weight: settings.buffer_font.weight,
19762                line_height: relative(settings.buffer_line_height.value()),
19763                ..Default::default()
19764            },
19765        };
19766        if let Some(text_style_refinement) = &self.text_style_refinement {
19767            text_style.refine(text_style_refinement)
19768        }
19769
19770        let background = match self.mode {
19771            EditorMode::SingleLine { .. } => cx.theme().system().transparent,
19772            EditorMode::AutoHeight { max_lines: _ } => cx.theme().system().transparent,
19773            EditorMode::Full { .. } => cx.theme().colors().editor_background,
19774        };
19775
19776        EditorElement::new(
19777            &cx.entity(),
19778            EditorStyle {
19779                background,
19780                local_player: cx.theme().players().local(),
19781                text: text_style,
19782                scrollbar_width: EditorElement::SCROLLBAR_WIDTH,
19783                syntax: cx.theme().syntax().clone(),
19784                status: cx.theme().status().clone(),
19785                inlay_hints_style: make_inlay_hints_style(cx),
19786                inline_completion_styles: make_suggestion_styles(cx),
19787                unnecessary_code_fade: ThemeSettings::get_global(cx).unnecessary_code_fade,
19788            },
19789        )
19790    }
19791}
19792
19793impl EntityInputHandler for Editor {
19794    fn text_for_range(
19795        &mut self,
19796        range_utf16: Range<usize>,
19797        adjusted_range: &mut Option<Range<usize>>,
19798        _: &mut Window,
19799        cx: &mut Context<Self>,
19800    ) -> Option<String> {
19801        let snapshot = self.buffer.read(cx).read(cx);
19802        let start = snapshot.clip_offset_utf16(OffsetUtf16(range_utf16.start), Bias::Left);
19803        let end = snapshot.clip_offset_utf16(OffsetUtf16(range_utf16.end), Bias::Right);
19804        if (start.0..end.0) != range_utf16 {
19805            adjusted_range.replace(start.0..end.0);
19806        }
19807        Some(snapshot.text_for_range(start..end).collect())
19808    }
19809
19810    fn selected_text_range(
19811        &mut self,
19812        ignore_disabled_input: bool,
19813        _: &mut Window,
19814        cx: &mut Context<Self>,
19815    ) -> Option<UTF16Selection> {
19816        // Prevent the IME menu from appearing when holding down an alphabetic key
19817        // while input is disabled.
19818        if !ignore_disabled_input && !self.input_enabled {
19819            return None;
19820        }
19821
19822        let selection = self.selections.newest::<OffsetUtf16>(cx);
19823        let range = selection.range();
19824
19825        Some(UTF16Selection {
19826            range: range.start.0..range.end.0,
19827            reversed: selection.reversed,
19828        })
19829    }
19830
19831    fn marked_text_range(&self, _: &mut Window, cx: &mut Context<Self>) -> Option<Range<usize>> {
19832        let snapshot = self.buffer.read(cx).read(cx);
19833        let range = self.text_highlights::<InputComposition>(cx)?.1.first()?;
19834        Some(range.start.to_offset_utf16(&snapshot).0..range.end.to_offset_utf16(&snapshot).0)
19835    }
19836
19837    fn unmark_text(&mut self, _: &mut Window, cx: &mut Context<Self>) {
19838        self.clear_highlights::<InputComposition>(cx);
19839        self.ime_transaction.take();
19840    }
19841
19842    fn replace_text_in_range(
19843        &mut self,
19844        range_utf16: Option<Range<usize>>,
19845        text: &str,
19846        window: &mut Window,
19847        cx: &mut Context<Self>,
19848    ) {
19849        if !self.input_enabled {
19850            cx.emit(EditorEvent::InputIgnored { text: text.into() });
19851            return;
19852        }
19853
19854        self.transact(window, cx, |this, window, cx| {
19855            let new_selected_ranges = if let Some(range_utf16) = range_utf16 {
19856                let range_utf16 = OffsetUtf16(range_utf16.start)..OffsetUtf16(range_utf16.end);
19857                Some(this.selection_replacement_ranges(range_utf16, cx))
19858            } else {
19859                this.marked_text_ranges(cx)
19860            };
19861
19862            let range_to_replace = new_selected_ranges.as_ref().and_then(|ranges_to_replace| {
19863                let newest_selection_id = this.selections.newest_anchor().id;
19864                this.selections
19865                    .all::<OffsetUtf16>(cx)
19866                    .iter()
19867                    .zip(ranges_to_replace.iter())
19868                    .find_map(|(selection, range)| {
19869                        if selection.id == newest_selection_id {
19870                            Some(
19871                                (range.start.0 as isize - selection.head().0 as isize)
19872                                    ..(range.end.0 as isize - selection.head().0 as isize),
19873                            )
19874                        } else {
19875                            None
19876                        }
19877                    })
19878            });
19879
19880            cx.emit(EditorEvent::InputHandled {
19881                utf16_range_to_replace: range_to_replace,
19882                text: text.into(),
19883            });
19884
19885            if let Some(new_selected_ranges) = new_selected_ranges {
19886                this.change_selections(None, window, cx, |selections| {
19887                    selections.select_ranges(new_selected_ranges)
19888                });
19889                this.backspace(&Default::default(), window, cx);
19890            }
19891
19892            this.handle_input(text, window, cx);
19893        });
19894
19895        if let Some(transaction) = self.ime_transaction {
19896            self.buffer.update(cx, |buffer, cx| {
19897                buffer.group_until_transaction(transaction, cx);
19898            });
19899        }
19900
19901        self.unmark_text(window, cx);
19902    }
19903
19904    fn replace_and_mark_text_in_range(
19905        &mut self,
19906        range_utf16: Option<Range<usize>>,
19907        text: &str,
19908        new_selected_range_utf16: Option<Range<usize>>,
19909        window: &mut Window,
19910        cx: &mut Context<Self>,
19911    ) {
19912        if !self.input_enabled {
19913            return;
19914        }
19915
19916        let transaction = self.transact(window, cx, |this, window, cx| {
19917            let ranges_to_replace = if let Some(mut marked_ranges) = this.marked_text_ranges(cx) {
19918                let snapshot = this.buffer.read(cx).read(cx);
19919                if let Some(relative_range_utf16) = range_utf16.as_ref() {
19920                    for marked_range in &mut marked_ranges {
19921                        marked_range.end.0 = marked_range.start.0 + relative_range_utf16.end;
19922                        marked_range.start.0 += relative_range_utf16.start;
19923                        marked_range.start =
19924                            snapshot.clip_offset_utf16(marked_range.start, Bias::Left);
19925                        marked_range.end =
19926                            snapshot.clip_offset_utf16(marked_range.end, Bias::Right);
19927                    }
19928                }
19929                Some(marked_ranges)
19930            } else if let Some(range_utf16) = range_utf16 {
19931                let range_utf16 = OffsetUtf16(range_utf16.start)..OffsetUtf16(range_utf16.end);
19932                Some(this.selection_replacement_ranges(range_utf16, cx))
19933            } else {
19934                None
19935            };
19936
19937            let range_to_replace = ranges_to_replace.as_ref().and_then(|ranges_to_replace| {
19938                let newest_selection_id = this.selections.newest_anchor().id;
19939                this.selections
19940                    .all::<OffsetUtf16>(cx)
19941                    .iter()
19942                    .zip(ranges_to_replace.iter())
19943                    .find_map(|(selection, range)| {
19944                        if selection.id == newest_selection_id {
19945                            Some(
19946                                (range.start.0 as isize - selection.head().0 as isize)
19947                                    ..(range.end.0 as isize - selection.head().0 as isize),
19948                            )
19949                        } else {
19950                            None
19951                        }
19952                    })
19953            });
19954
19955            cx.emit(EditorEvent::InputHandled {
19956                utf16_range_to_replace: range_to_replace,
19957                text: text.into(),
19958            });
19959
19960            if let Some(ranges) = ranges_to_replace {
19961                this.change_selections(None, window, cx, |s| s.select_ranges(ranges));
19962            }
19963
19964            let marked_ranges = {
19965                let snapshot = this.buffer.read(cx).read(cx);
19966                this.selections
19967                    .disjoint_anchors()
19968                    .iter()
19969                    .map(|selection| {
19970                        selection.start.bias_left(&snapshot)..selection.end.bias_right(&snapshot)
19971                    })
19972                    .collect::<Vec<_>>()
19973            };
19974
19975            if text.is_empty() {
19976                this.unmark_text(window, cx);
19977            } else {
19978                this.highlight_text::<InputComposition>(
19979                    marked_ranges.clone(),
19980                    HighlightStyle {
19981                        underline: Some(UnderlineStyle {
19982                            thickness: px(1.),
19983                            color: None,
19984                            wavy: false,
19985                        }),
19986                        ..Default::default()
19987                    },
19988                    cx,
19989                );
19990            }
19991
19992            // Disable auto-closing when composing text (i.e. typing a `"` on a Brazilian keyboard)
19993            let use_autoclose = this.use_autoclose;
19994            let use_auto_surround = this.use_auto_surround;
19995            this.set_use_autoclose(false);
19996            this.set_use_auto_surround(false);
19997            this.handle_input(text, window, cx);
19998            this.set_use_autoclose(use_autoclose);
19999            this.set_use_auto_surround(use_auto_surround);
20000
20001            if let Some(new_selected_range) = new_selected_range_utf16 {
20002                let snapshot = this.buffer.read(cx).read(cx);
20003                let new_selected_ranges = marked_ranges
20004                    .into_iter()
20005                    .map(|marked_range| {
20006                        let insertion_start = marked_range.start.to_offset_utf16(&snapshot).0;
20007                        let new_start = OffsetUtf16(new_selected_range.start + insertion_start);
20008                        let new_end = OffsetUtf16(new_selected_range.end + insertion_start);
20009                        snapshot.clip_offset_utf16(new_start, Bias::Left)
20010                            ..snapshot.clip_offset_utf16(new_end, Bias::Right)
20011                    })
20012                    .collect::<Vec<_>>();
20013
20014                drop(snapshot);
20015                this.change_selections(None, window, cx, |selections| {
20016                    selections.select_ranges(new_selected_ranges)
20017                });
20018            }
20019        });
20020
20021        self.ime_transaction = self.ime_transaction.or(transaction);
20022        if let Some(transaction) = self.ime_transaction {
20023            self.buffer.update(cx, |buffer, cx| {
20024                buffer.group_until_transaction(transaction, cx);
20025            });
20026        }
20027
20028        if self.text_highlights::<InputComposition>(cx).is_none() {
20029            self.ime_transaction.take();
20030        }
20031    }
20032
20033    fn bounds_for_range(
20034        &mut self,
20035        range_utf16: Range<usize>,
20036        element_bounds: gpui::Bounds<Pixels>,
20037        window: &mut Window,
20038        cx: &mut Context<Self>,
20039    ) -> Option<gpui::Bounds<Pixels>> {
20040        let text_layout_details = self.text_layout_details(window);
20041        let gpui::Size {
20042            width: em_width,
20043            height: line_height,
20044        } = self.character_size(window);
20045
20046        let snapshot = self.snapshot(window, cx);
20047        let scroll_position = snapshot.scroll_position();
20048        let scroll_left = scroll_position.x * em_width;
20049
20050        let start = OffsetUtf16(range_utf16.start).to_display_point(&snapshot);
20051        let x = snapshot.x_for_display_point(start, &text_layout_details) - scroll_left
20052            + self.gutter_dimensions.width
20053            + self.gutter_dimensions.margin;
20054        let y = line_height * (start.row().as_f32() - scroll_position.y);
20055
20056        Some(Bounds {
20057            origin: element_bounds.origin + point(x, y),
20058            size: size(em_width, line_height),
20059        })
20060    }
20061
20062    fn character_index_for_point(
20063        &mut self,
20064        point: gpui::Point<Pixels>,
20065        _window: &mut Window,
20066        _cx: &mut Context<Self>,
20067    ) -> Option<usize> {
20068        let position_map = self.last_position_map.as_ref()?;
20069        if !position_map.text_hitbox.contains(&point) {
20070            return None;
20071        }
20072        let display_point = position_map.point_for_position(point).previous_valid;
20073        let anchor = position_map
20074            .snapshot
20075            .display_point_to_anchor(display_point, Bias::Left);
20076        let utf16_offset = anchor.to_offset_utf16(&position_map.snapshot.buffer_snapshot);
20077        Some(utf16_offset.0)
20078    }
20079}
20080
20081trait SelectionExt {
20082    fn display_range(&self, map: &DisplaySnapshot) -> Range<DisplayPoint>;
20083    fn spanned_rows(
20084        &self,
20085        include_end_if_at_line_start: bool,
20086        map: &DisplaySnapshot,
20087    ) -> Range<MultiBufferRow>;
20088}
20089
20090impl<T: ToPoint + ToOffset> SelectionExt for Selection<T> {
20091    fn display_range(&self, map: &DisplaySnapshot) -> Range<DisplayPoint> {
20092        let start = self
20093            .start
20094            .to_point(&map.buffer_snapshot)
20095            .to_display_point(map);
20096        let end = self
20097            .end
20098            .to_point(&map.buffer_snapshot)
20099            .to_display_point(map);
20100        if self.reversed {
20101            end..start
20102        } else {
20103            start..end
20104        }
20105    }
20106
20107    fn spanned_rows(
20108        &self,
20109        include_end_if_at_line_start: bool,
20110        map: &DisplaySnapshot,
20111    ) -> Range<MultiBufferRow> {
20112        let start = self.start.to_point(&map.buffer_snapshot);
20113        let mut end = self.end.to_point(&map.buffer_snapshot);
20114        if !include_end_if_at_line_start && start.row != end.row && end.column == 0 {
20115            end.row -= 1;
20116        }
20117
20118        let buffer_start = map.prev_line_boundary(start).0;
20119        let buffer_end = map.next_line_boundary(end).0;
20120        MultiBufferRow(buffer_start.row)..MultiBufferRow(buffer_end.row + 1)
20121    }
20122}
20123
20124impl<T: InvalidationRegion> InvalidationStack<T> {
20125    fn invalidate<S>(&mut self, selections: &[Selection<S>], buffer: &MultiBufferSnapshot)
20126    where
20127        S: Clone + ToOffset,
20128    {
20129        while let Some(region) = self.last() {
20130            let all_selections_inside_invalidation_ranges =
20131                if selections.len() == region.ranges().len() {
20132                    selections
20133                        .iter()
20134                        .zip(region.ranges().iter().map(|r| r.to_offset(buffer)))
20135                        .all(|(selection, invalidation_range)| {
20136                            let head = selection.head().to_offset(buffer);
20137                            invalidation_range.start <= head && invalidation_range.end >= head
20138                        })
20139                } else {
20140                    false
20141                };
20142
20143            if all_selections_inside_invalidation_ranges {
20144                break;
20145            } else {
20146                self.pop();
20147            }
20148        }
20149    }
20150}
20151
20152impl<T> Default for InvalidationStack<T> {
20153    fn default() -> Self {
20154        Self(Default::default())
20155    }
20156}
20157
20158impl<T> Deref for InvalidationStack<T> {
20159    type Target = Vec<T>;
20160
20161    fn deref(&self) -> &Self::Target {
20162        &self.0
20163    }
20164}
20165
20166impl<T> DerefMut for InvalidationStack<T> {
20167    fn deref_mut(&mut self) -> &mut Self::Target {
20168        &mut self.0
20169    }
20170}
20171
20172impl InvalidationRegion for SnippetState {
20173    fn ranges(&self) -> &[Range<Anchor>] {
20174        &self.ranges[self.active_index]
20175    }
20176}
20177
20178fn inline_completion_edit_text(
20179    current_snapshot: &BufferSnapshot,
20180    edits: &[(Range<Anchor>, String)],
20181    edit_preview: &EditPreview,
20182    include_deletions: bool,
20183    cx: &App,
20184) -> HighlightedText {
20185    let edits = edits
20186        .iter()
20187        .map(|(anchor, text)| {
20188            (
20189                anchor.start.text_anchor..anchor.end.text_anchor,
20190                text.clone(),
20191            )
20192        })
20193        .collect::<Vec<_>>();
20194
20195    edit_preview.highlight_edits(current_snapshot, &edits, include_deletions, cx)
20196}
20197
20198pub fn diagnostic_style(severity: DiagnosticSeverity, colors: &StatusColors) -> Hsla {
20199    match severity {
20200        DiagnosticSeverity::ERROR => colors.error,
20201        DiagnosticSeverity::WARNING => colors.warning,
20202        DiagnosticSeverity::INFORMATION => colors.info,
20203        DiagnosticSeverity::HINT => colors.info,
20204        _ => colors.ignored,
20205    }
20206}
20207
20208pub fn styled_runs_for_code_label<'a>(
20209    label: &'a CodeLabel,
20210    syntax_theme: &'a theme::SyntaxTheme,
20211) -> impl 'a + Iterator<Item = (Range<usize>, HighlightStyle)> {
20212    let fade_out = HighlightStyle {
20213        fade_out: Some(0.35),
20214        ..Default::default()
20215    };
20216
20217    let mut prev_end = label.filter_range.end;
20218    label
20219        .runs
20220        .iter()
20221        .enumerate()
20222        .flat_map(move |(ix, (range, highlight_id))| {
20223            let style = if let Some(style) = highlight_id.style(syntax_theme) {
20224                style
20225            } else {
20226                return Default::default();
20227            };
20228            let mut muted_style = style;
20229            muted_style.highlight(fade_out);
20230
20231            let mut runs = SmallVec::<[(Range<usize>, HighlightStyle); 3]>::new();
20232            if range.start >= label.filter_range.end {
20233                if range.start > prev_end {
20234                    runs.push((prev_end..range.start, fade_out));
20235                }
20236                runs.push((range.clone(), muted_style));
20237            } else if range.end <= label.filter_range.end {
20238                runs.push((range.clone(), style));
20239            } else {
20240                runs.push((range.start..label.filter_range.end, style));
20241                runs.push((label.filter_range.end..range.end, muted_style));
20242            }
20243            prev_end = cmp::max(prev_end, range.end);
20244
20245            if ix + 1 == label.runs.len() && label.text.len() > prev_end {
20246                runs.push((prev_end..label.text.len(), fade_out));
20247            }
20248
20249            runs
20250        })
20251}
20252
20253pub(crate) fn split_words(text: &str) -> impl std::iter::Iterator<Item = &str> + '_ {
20254    let mut prev_index = 0;
20255    let mut prev_codepoint: Option<char> = None;
20256    text.char_indices()
20257        .chain([(text.len(), '\0')])
20258        .filter_map(move |(index, codepoint)| {
20259            let prev_codepoint = prev_codepoint.replace(codepoint)?;
20260            let is_boundary = index == text.len()
20261                || !prev_codepoint.is_uppercase() && codepoint.is_uppercase()
20262                || !prev_codepoint.is_alphanumeric() && codepoint.is_alphanumeric();
20263            if is_boundary {
20264                let chunk = &text[prev_index..index];
20265                prev_index = index;
20266                Some(chunk)
20267            } else {
20268                None
20269            }
20270        })
20271}
20272
20273pub trait RangeToAnchorExt: Sized {
20274    fn to_anchors(self, snapshot: &MultiBufferSnapshot) -> Range<Anchor>;
20275
20276    fn to_display_points(self, snapshot: &EditorSnapshot) -> Range<DisplayPoint> {
20277        let anchor_range = self.to_anchors(&snapshot.buffer_snapshot);
20278        anchor_range.start.to_display_point(snapshot)..anchor_range.end.to_display_point(snapshot)
20279    }
20280}
20281
20282impl<T: ToOffset> RangeToAnchorExt for Range<T> {
20283    fn to_anchors(self, snapshot: &MultiBufferSnapshot) -> Range<Anchor> {
20284        let start_offset = self.start.to_offset(snapshot);
20285        let end_offset = self.end.to_offset(snapshot);
20286        if start_offset == end_offset {
20287            snapshot.anchor_before(start_offset)..snapshot.anchor_before(end_offset)
20288        } else {
20289            snapshot.anchor_after(self.start)..snapshot.anchor_before(self.end)
20290        }
20291    }
20292}
20293
20294pub trait RowExt {
20295    fn as_f32(&self) -> f32;
20296
20297    fn next_row(&self) -> Self;
20298
20299    fn previous_row(&self) -> Self;
20300
20301    fn minus(&self, other: Self) -> u32;
20302}
20303
20304impl RowExt for DisplayRow {
20305    fn as_f32(&self) -> f32 {
20306        self.0 as f32
20307    }
20308
20309    fn next_row(&self) -> Self {
20310        Self(self.0 + 1)
20311    }
20312
20313    fn previous_row(&self) -> Self {
20314        Self(self.0.saturating_sub(1))
20315    }
20316
20317    fn minus(&self, other: Self) -> u32 {
20318        self.0 - other.0
20319    }
20320}
20321
20322impl RowExt for MultiBufferRow {
20323    fn as_f32(&self) -> f32 {
20324        self.0 as f32
20325    }
20326
20327    fn next_row(&self) -> Self {
20328        Self(self.0 + 1)
20329    }
20330
20331    fn previous_row(&self) -> Self {
20332        Self(self.0.saturating_sub(1))
20333    }
20334
20335    fn minus(&self, other: Self) -> u32 {
20336        self.0 - other.0
20337    }
20338}
20339
20340trait RowRangeExt {
20341    type Row;
20342
20343    fn len(&self) -> usize;
20344
20345    fn iter_rows(&self) -> impl DoubleEndedIterator<Item = Self::Row>;
20346}
20347
20348impl RowRangeExt for Range<MultiBufferRow> {
20349    type Row = MultiBufferRow;
20350
20351    fn len(&self) -> usize {
20352        (self.end.0 - self.start.0) as usize
20353    }
20354
20355    fn iter_rows(&self) -> impl DoubleEndedIterator<Item = MultiBufferRow> {
20356        (self.start.0..self.end.0).map(MultiBufferRow)
20357    }
20358}
20359
20360impl RowRangeExt for Range<DisplayRow> {
20361    type Row = DisplayRow;
20362
20363    fn len(&self) -> usize {
20364        (self.end.0 - self.start.0) as usize
20365    }
20366
20367    fn iter_rows(&self) -> impl DoubleEndedIterator<Item = DisplayRow> {
20368        (self.start.0..self.end.0).map(DisplayRow)
20369    }
20370}
20371
20372/// If select range has more than one line, we
20373/// just point the cursor to range.start.
20374fn collapse_multiline_range(range: Range<Point>) -> Range<Point> {
20375    if range.start.row == range.end.row {
20376        range
20377    } else {
20378        range.start..range.start
20379    }
20380}
20381pub struct KillRing(ClipboardItem);
20382impl Global for KillRing {}
20383
20384const UPDATE_DEBOUNCE: Duration = Duration::from_millis(50);
20385
20386enum BreakpointPromptEditAction {
20387    Log,
20388    Condition,
20389    HitCondition,
20390}
20391
20392struct BreakpointPromptEditor {
20393    pub(crate) prompt: Entity<Editor>,
20394    editor: WeakEntity<Editor>,
20395    breakpoint_anchor: Anchor,
20396    breakpoint: Breakpoint,
20397    edit_action: BreakpointPromptEditAction,
20398    block_ids: HashSet<CustomBlockId>,
20399    gutter_dimensions: Arc<Mutex<GutterDimensions>>,
20400    _subscriptions: Vec<Subscription>,
20401}
20402
20403impl BreakpointPromptEditor {
20404    const MAX_LINES: u8 = 4;
20405
20406    fn new(
20407        editor: WeakEntity<Editor>,
20408        breakpoint_anchor: Anchor,
20409        breakpoint: Breakpoint,
20410        edit_action: BreakpointPromptEditAction,
20411        window: &mut Window,
20412        cx: &mut Context<Self>,
20413    ) -> Self {
20414        let base_text = match edit_action {
20415            BreakpointPromptEditAction::Log => breakpoint.message.as_ref(),
20416            BreakpointPromptEditAction::Condition => breakpoint.condition.as_ref(),
20417            BreakpointPromptEditAction::HitCondition => breakpoint.hit_condition.as_ref(),
20418        }
20419        .map(|msg| msg.to_string())
20420        .unwrap_or_default();
20421
20422        let buffer = cx.new(|cx| Buffer::local(base_text, cx));
20423        let buffer = cx.new(|cx| MultiBuffer::singleton(buffer, cx));
20424
20425        let prompt = cx.new(|cx| {
20426            let mut prompt = Editor::new(
20427                EditorMode::AutoHeight {
20428                    max_lines: Self::MAX_LINES as usize,
20429                },
20430                buffer,
20431                None,
20432                window,
20433                cx,
20434            );
20435            prompt.set_soft_wrap_mode(language::language_settings::SoftWrap::EditorWidth, cx);
20436            prompt.set_show_cursor_when_unfocused(false, cx);
20437            prompt.set_placeholder_text(
20438                match edit_action {
20439                    BreakpointPromptEditAction::Log => "Message to log when a breakpoint is hit. Expressions within {} are interpolated.",
20440                    BreakpointPromptEditAction::Condition => "Condition when a breakpoint is hit. Expressions within {} are interpolated.",
20441                    BreakpointPromptEditAction::HitCondition => "How many breakpoint hits to ignore",
20442                },
20443                cx,
20444            );
20445
20446            prompt
20447        });
20448
20449        Self {
20450            prompt,
20451            editor,
20452            breakpoint_anchor,
20453            breakpoint,
20454            edit_action,
20455            gutter_dimensions: Arc::new(Mutex::new(GutterDimensions::default())),
20456            block_ids: Default::default(),
20457            _subscriptions: vec![],
20458        }
20459    }
20460
20461    pub(crate) fn add_block_ids(&mut self, block_ids: Vec<CustomBlockId>) {
20462        self.block_ids.extend(block_ids)
20463    }
20464
20465    fn confirm(&mut self, _: &menu::Confirm, window: &mut Window, cx: &mut Context<Self>) {
20466        if let Some(editor) = self.editor.upgrade() {
20467            let message = self
20468                .prompt
20469                .read(cx)
20470                .buffer
20471                .read(cx)
20472                .as_singleton()
20473                .expect("A multi buffer in breakpoint prompt isn't possible")
20474                .read(cx)
20475                .as_rope()
20476                .to_string();
20477
20478            editor.update(cx, |editor, cx| {
20479                editor.edit_breakpoint_at_anchor(
20480                    self.breakpoint_anchor,
20481                    self.breakpoint.clone(),
20482                    match self.edit_action {
20483                        BreakpointPromptEditAction::Log => {
20484                            BreakpointEditAction::EditLogMessage(message.into())
20485                        }
20486                        BreakpointPromptEditAction::Condition => {
20487                            BreakpointEditAction::EditCondition(message.into())
20488                        }
20489                        BreakpointPromptEditAction::HitCondition => {
20490                            BreakpointEditAction::EditHitCondition(message.into())
20491                        }
20492                    },
20493                    cx,
20494                );
20495
20496                editor.remove_blocks(self.block_ids.clone(), None, cx);
20497                cx.focus_self(window);
20498            });
20499        }
20500    }
20501
20502    fn cancel(&mut self, _: &menu::Cancel, window: &mut Window, cx: &mut Context<Self>) {
20503        self.editor
20504            .update(cx, |editor, cx| {
20505                editor.remove_blocks(self.block_ids.clone(), None, cx);
20506                window.focus(&editor.focus_handle);
20507            })
20508            .log_err();
20509    }
20510
20511    fn render_prompt_editor(&self, cx: &mut Context<Self>) -> impl IntoElement {
20512        let settings = ThemeSettings::get_global(cx);
20513        let text_style = TextStyle {
20514            color: if self.prompt.read(cx).read_only(cx) {
20515                cx.theme().colors().text_disabled
20516            } else {
20517                cx.theme().colors().text
20518            },
20519            font_family: settings.buffer_font.family.clone(),
20520            font_fallbacks: settings.buffer_font.fallbacks.clone(),
20521            font_size: settings.buffer_font_size(cx).into(),
20522            font_weight: settings.buffer_font.weight,
20523            line_height: relative(settings.buffer_line_height.value()),
20524            ..Default::default()
20525        };
20526        EditorElement::new(
20527            &self.prompt,
20528            EditorStyle {
20529                background: cx.theme().colors().editor_background,
20530                local_player: cx.theme().players().local(),
20531                text: text_style,
20532                ..Default::default()
20533            },
20534        )
20535    }
20536}
20537
20538impl Render for BreakpointPromptEditor {
20539    fn render(&mut self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
20540        let gutter_dimensions = *self.gutter_dimensions.lock();
20541        h_flex()
20542            .key_context("Editor")
20543            .bg(cx.theme().colors().editor_background)
20544            .border_y_1()
20545            .border_color(cx.theme().status().info_border)
20546            .size_full()
20547            .py(window.line_height() / 2.5)
20548            .on_action(cx.listener(Self::confirm))
20549            .on_action(cx.listener(Self::cancel))
20550            .child(h_flex().w(gutter_dimensions.full_width() + (gutter_dimensions.margin / 2.0)))
20551            .child(div().flex_1().child(self.render_prompt_editor(cx)))
20552    }
20553}
20554
20555impl Focusable for BreakpointPromptEditor {
20556    fn focus_handle(&self, cx: &App) -> FocusHandle {
20557        self.prompt.focus_handle(cx)
20558    }
20559}
20560
20561fn all_edits_insertions_or_deletions(
20562    edits: &Vec<(Range<Anchor>, String)>,
20563    snapshot: &MultiBufferSnapshot,
20564) -> bool {
20565    let mut all_insertions = true;
20566    let mut all_deletions = true;
20567
20568    for (range, new_text) in edits.iter() {
20569        let range_is_empty = range.to_offset(&snapshot).is_empty();
20570        let text_is_empty = new_text.is_empty();
20571
20572        if range_is_empty != text_is_empty {
20573            if range_is_empty {
20574                all_deletions = false;
20575            } else {
20576                all_insertions = false;
20577            }
20578        } else {
20579            return false;
20580        }
20581
20582        if !all_insertions && !all_deletions {
20583            return false;
20584        }
20585    }
20586    all_insertions || all_deletions
20587}
20588
20589struct MissingEditPredictionKeybindingTooltip;
20590
20591impl Render for MissingEditPredictionKeybindingTooltip {
20592    fn render(&mut self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
20593        ui::tooltip_container(window, cx, |container, _, cx| {
20594            container
20595                .flex_shrink_0()
20596                .max_w_80()
20597                .min_h(rems_from_px(124.))
20598                .justify_between()
20599                .child(
20600                    v_flex()
20601                        .flex_1()
20602                        .text_ui_sm(cx)
20603                        .child(Label::new("Conflict with Accept Keybinding"))
20604                        .child("Your keymap currently overrides the default accept keybinding. To continue, assign one keybinding for the `editor::AcceptEditPrediction` action.")
20605                )
20606                .child(
20607                    h_flex()
20608                        .pb_1()
20609                        .gap_1()
20610                        .items_end()
20611                        .w_full()
20612                        .child(Button::new("open-keymap", "Assign Keybinding").size(ButtonSize::Compact).on_click(|_ev, window, cx| {
20613                            window.dispatch_action(zed_actions::OpenKeymap.boxed_clone(), cx)
20614                        }))
20615                        .child(Button::new("see-docs", "See Docs").size(ButtonSize::Compact).on_click(|_ev, _window, cx| {
20616                            cx.open_url("https://zed.dev/docs/completions#edit-predictions-missing-keybinding");
20617                        })),
20618                )
20619        })
20620    }
20621}
20622
20623#[derive(Debug, Clone, Copy, PartialEq)]
20624pub struct LineHighlight {
20625    pub background: Background,
20626    pub border: Option<gpui::Hsla>,
20627}
20628
20629impl From<Hsla> for LineHighlight {
20630    fn from(hsla: Hsla) -> Self {
20631        Self {
20632            background: hsla.into(),
20633            border: None,
20634        }
20635    }
20636}
20637
20638impl From<Background> for LineHighlight {
20639    fn from(background: Background) -> Self {
20640        Self {
20641            background,
20642            border: None,
20643        }
20644    }
20645}
20646
20647fn render_diff_hunk_controls(
20648    row: u32,
20649    status: &DiffHunkStatus,
20650    hunk_range: Range<Anchor>,
20651    is_created_file: bool,
20652    line_height: Pixels,
20653    editor: &Entity<Editor>,
20654    _window: &mut Window,
20655    cx: &mut App,
20656) -> AnyElement {
20657    h_flex()
20658        .h(line_height)
20659        .mr_1()
20660        .gap_1()
20661        .px_0p5()
20662        .pb_1()
20663        .border_x_1()
20664        .border_b_1()
20665        .border_color(cx.theme().colors().border_variant)
20666        .rounded_b_lg()
20667        .bg(cx.theme().colors().editor_background)
20668        .gap_1()
20669        .occlude()
20670        .shadow_md()
20671        .child(if status.has_secondary_hunk() {
20672            Button::new(("stage", row as u64), "Stage")
20673                .alpha(if status.is_pending() { 0.66 } else { 1.0 })
20674                .tooltip({
20675                    let focus_handle = editor.focus_handle(cx);
20676                    move |window, cx| {
20677                        Tooltip::for_action_in(
20678                            "Stage Hunk",
20679                            &::git::ToggleStaged,
20680                            &focus_handle,
20681                            window,
20682                            cx,
20683                        )
20684                    }
20685                })
20686                .on_click({
20687                    let editor = editor.clone();
20688                    move |_event, _window, cx| {
20689                        editor.update(cx, |editor, cx| {
20690                            editor.stage_or_unstage_diff_hunks(
20691                                true,
20692                                vec![hunk_range.start..hunk_range.start],
20693                                cx,
20694                            );
20695                        });
20696                    }
20697                })
20698        } else {
20699            Button::new(("unstage", row as u64), "Unstage")
20700                .alpha(if status.is_pending() { 0.66 } else { 1.0 })
20701                .tooltip({
20702                    let focus_handle = editor.focus_handle(cx);
20703                    move |window, cx| {
20704                        Tooltip::for_action_in(
20705                            "Unstage Hunk",
20706                            &::git::ToggleStaged,
20707                            &focus_handle,
20708                            window,
20709                            cx,
20710                        )
20711                    }
20712                })
20713                .on_click({
20714                    let editor = editor.clone();
20715                    move |_event, _window, cx| {
20716                        editor.update(cx, |editor, cx| {
20717                            editor.stage_or_unstage_diff_hunks(
20718                                false,
20719                                vec![hunk_range.start..hunk_range.start],
20720                                cx,
20721                            );
20722                        });
20723                    }
20724                })
20725        })
20726        .child(
20727            Button::new(("restore", row as u64), "Restore")
20728                .tooltip({
20729                    let focus_handle = editor.focus_handle(cx);
20730                    move |window, cx| {
20731                        Tooltip::for_action_in(
20732                            "Restore Hunk",
20733                            &::git::Restore,
20734                            &focus_handle,
20735                            window,
20736                            cx,
20737                        )
20738                    }
20739                })
20740                .on_click({
20741                    let editor = editor.clone();
20742                    move |_event, window, cx| {
20743                        editor.update(cx, |editor, cx| {
20744                            let snapshot = editor.snapshot(window, cx);
20745                            let point = hunk_range.start.to_point(&snapshot.buffer_snapshot);
20746                            editor.restore_hunks_in_ranges(vec![point..point], window, cx);
20747                        });
20748                    }
20749                })
20750                .disabled(is_created_file),
20751        )
20752        .when(
20753            !editor.read(cx).buffer().read(cx).all_diff_hunks_expanded(),
20754            |el| {
20755                el.child(
20756                    IconButton::new(("next-hunk", row as u64), IconName::ArrowDown)
20757                        .shape(IconButtonShape::Square)
20758                        .icon_size(IconSize::Small)
20759                        // .disabled(!has_multiple_hunks)
20760                        .tooltip({
20761                            let focus_handle = editor.focus_handle(cx);
20762                            move |window, cx| {
20763                                Tooltip::for_action_in(
20764                                    "Next Hunk",
20765                                    &GoToHunk,
20766                                    &focus_handle,
20767                                    window,
20768                                    cx,
20769                                )
20770                            }
20771                        })
20772                        .on_click({
20773                            let editor = editor.clone();
20774                            move |_event, window, cx| {
20775                                editor.update(cx, |editor, cx| {
20776                                    let snapshot = editor.snapshot(window, cx);
20777                                    let position =
20778                                        hunk_range.end.to_point(&snapshot.buffer_snapshot);
20779                                    editor.go_to_hunk_before_or_after_position(
20780                                        &snapshot,
20781                                        position,
20782                                        Direction::Next,
20783                                        window,
20784                                        cx,
20785                                    );
20786                                    editor.expand_selected_diff_hunks(cx);
20787                                });
20788                            }
20789                        }),
20790                )
20791                .child(
20792                    IconButton::new(("prev-hunk", row as u64), IconName::ArrowUp)
20793                        .shape(IconButtonShape::Square)
20794                        .icon_size(IconSize::Small)
20795                        // .disabled(!has_multiple_hunks)
20796                        .tooltip({
20797                            let focus_handle = editor.focus_handle(cx);
20798                            move |window, cx| {
20799                                Tooltip::for_action_in(
20800                                    "Previous Hunk",
20801                                    &GoToPreviousHunk,
20802                                    &focus_handle,
20803                                    window,
20804                                    cx,
20805                                )
20806                            }
20807                        })
20808                        .on_click({
20809                            let editor = editor.clone();
20810                            move |_event, window, cx| {
20811                                editor.update(cx, |editor, cx| {
20812                                    let snapshot = editor.snapshot(window, cx);
20813                                    let point =
20814                                        hunk_range.start.to_point(&snapshot.buffer_snapshot);
20815                                    editor.go_to_hunk_before_or_after_position(
20816                                        &snapshot,
20817                                        point,
20818                                        Direction::Prev,
20819                                        window,
20820                                        cx,
20821                                    );
20822                                    editor.expand_selected_diff_hunks(cx);
20823                                });
20824                            }
20825                        }),
20826                )
20827            },
20828        )
20829        .into_any_element()
20830}