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/// Zed's primary implementation of text input, allowing users to edit a [`MultiBuffer`].
  697///
  698/// See the [module level documentation](self) for more information.
  699pub struct Editor {
  700    focus_handle: FocusHandle,
  701    last_focused_descendant: Option<WeakFocusHandle>,
  702    /// The text buffer being edited
  703    buffer: Entity<MultiBuffer>,
  704    /// Map of how text in the buffer should be displayed.
  705    /// Handles soft wraps, folds, fake inlay text insertions, etc.
  706    pub display_map: Entity<DisplayMap>,
  707    pub selections: SelectionsCollection,
  708    pub scroll_manager: ScrollManager,
  709    /// When inline assist editors are linked, they all render cursors because
  710    /// typing enters text into each of them, even the ones that aren't focused.
  711    pub(crate) show_cursor_when_unfocused: bool,
  712    columnar_selection_tail: Option<Anchor>,
  713    add_selections_state: Option<AddSelectionsState>,
  714    select_next_state: Option<SelectNextState>,
  715    select_prev_state: Option<SelectNextState>,
  716    selection_history: SelectionHistory,
  717    autoclose_regions: Vec<AutocloseRegion>,
  718    snippet_stack: InvalidationStack<SnippetState>,
  719    select_syntax_node_history: SelectSyntaxNodeHistory,
  720    ime_transaction: Option<TransactionId>,
  721    active_diagnostics: ActiveDiagnostic,
  722    show_inline_diagnostics: bool,
  723    inline_diagnostics_update: Task<()>,
  724    inline_diagnostics_enabled: bool,
  725    inline_diagnostics: Vec<(Anchor, InlineDiagnostic)>,
  726    soft_wrap_mode_override: Option<language_settings::SoftWrap>,
  727    hard_wrap: Option<usize>,
  728
  729    // TODO: make this a access method
  730    pub project: Option<Entity<Project>>,
  731    semantics_provider: Option<Rc<dyn SemanticsProvider>>,
  732    completion_provider: Option<Box<dyn CompletionProvider>>,
  733    collaboration_hub: Option<Box<dyn CollaborationHub>>,
  734    blink_manager: Entity<BlinkManager>,
  735    show_cursor_names: bool,
  736    hovered_cursors: HashMap<HoveredCursor, Task<()>>,
  737    pub show_local_selections: bool,
  738    mode: EditorMode,
  739    show_breadcrumbs: bool,
  740    show_gutter: bool,
  741    show_scrollbars: bool,
  742    show_line_numbers: Option<bool>,
  743    use_relative_line_numbers: Option<bool>,
  744    show_git_diff_gutter: Option<bool>,
  745    show_code_actions: Option<bool>,
  746    show_runnables: Option<bool>,
  747    show_breakpoints: Option<bool>,
  748    show_wrap_guides: Option<bool>,
  749    show_indent_guides: Option<bool>,
  750    placeholder_text: Option<Arc<str>>,
  751    highlight_order: usize,
  752    highlighted_rows: HashMap<TypeId, Vec<RowHighlight>>,
  753    background_highlights: TreeMap<TypeId, BackgroundHighlight>,
  754    gutter_highlights: TreeMap<TypeId, GutterHighlight>,
  755    scrollbar_marker_state: ScrollbarMarkerState,
  756    active_indent_guides_state: ActiveIndentGuidesState,
  757    nav_history: Option<ItemNavHistory>,
  758    context_menu: RefCell<Option<CodeContextMenu>>,
  759    context_menu_options: Option<ContextMenuOptions>,
  760    mouse_context_menu: Option<MouseContextMenu>,
  761    completion_tasks: Vec<(CompletionId, Task<Option<()>>)>,
  762    signature_help_state: SignatureHelpState,
  763    auto_signature_help: Option<bool>,
  764    find_all_references_task_sources: Vec<Anchor>,
  765    next_completion_id: CompletionId,
  766    available_code_actions: Option<(Location, Rc<[AvailableCodeAction]>)>,
  767    code_actions_task: Option<Task<Result<()>>>,
  768    selection_highlight_task: Option<Task<()>>,
  769    document_highlights_task: Option<Task<()>>,
  770    linked_editing_range_task: Option<Task<Option<()>>>,
  771    linked_edit_ranges: linked_editing_ranges::LinkedEditingRanges,
  772    pending_rename: Option<RenameState>,
  773    searchable: bool,
  774    cursor_shape: CursorShape,
  775    current_line_highlight: Option<CurrentLineHighlight>,
  776    collapse_matches: bool,
  777    autoindent_mode: Option<AutoindentMode>,
  778    workspace: Option<(WeakEntity<Workspace>, Option<WorkspaceId>)>,
  779    input_enabled: bool,
  780    use_modal_editing: bool,
  781    read_only: bool,
  782    leader_peer_id: Option<PeerId>,
  783    remote_id: Option<ViewId>,
  784    hover_state: HoverState,
  785    pending_mouse_down: Option<Rc<RefCell<Option<MouseDownEvent>>>>,
  786    gutter_hovered: bool,
  787    hovered_link_state: Option<HoveredLinkState>,
  788    edit_prediction_provider: Option<RegisteredInlineCompletionProvider>,
  789    code_action_providers: Vec<Rc<dyn CodeActionProvider>>,
  790    active_inline_completion: Option<InlineCompletionState>,
  791    /// Used to prevent flickering as the user types while the menu is open
  792    stale_inline_completion_in_menu: Option<InlineCompletionState>,
  793    edit_prediction_settings: EditPredictionSettings,
  794    inline_completions_hidden_for_vim_mode: bool,
  795    show_inline_completions_override: Option<bool>,
  796    menu_inline_completions_policy: MenuInlineCompletionsPolicy,
  797    edit_prediction_preview: EditPredictionPreview,
  798    edit_prediction_indent_conflict: bool,
  799    edit_prediction_requires_modifier_in_indent_conflict: bool,
  800    inlay_hint_cache: InlayHintCache,
  801    next_inlay_id: usize,
  802    _subscriptions: Vec<Subscription>,
  803    pixel_position_of_newest_cursor: Option<gpui::Point<Pixels>>,
  804    gutter_dimensions: GutterDimensions,
  805    style: Option<EditorStyle>,
  806    text_style_refinement: Option<TextStyleRefinement>,
  807    next_editor_action_id: EditorActionId,
  808    editor_actions:
  809        Rc<RefCell<BTreeMap<EditorActionId, Box<dyn Fn(&mut Window, &mut Context<Self>)>>>>,
  810    use_autoclose: bool,
  811    use_auto_surround: bool,
  812    auto_replace_emoji_shortcode: bool,
  813    jsx_tag_auto_close_enabled_in_any_buffer: bool,
  814    show_git_blame_gutter: bool,
  815    show_git_blame_inline: bool,
  816    show_git_blame_inline_delay_task: Option<Task<()>>,
  817    pub git_blame_inline_tooltip: Option<AnyWeakEntity>,
  818    git_blame_inline_enabled: bool,
  819    render_diff_hunk_controls: RenderDiffHunkControlsFn,
  820    serialize_dirty_buffers: bool,
  821    show_selection_menu: Option<bool>,
  822    blame: Option<Entity<GitBlame>>,
  823    blame_subscription: Option<Subscription>,
  824    custom_context_menu: Option<
  825        Box<
  826            dyn 'static
  827                + Fn(
  828                    &mut Self,
  829                    DisplayPoint,
  830                    &mut Window,
  831                    &mut Context<Self>,
  832                ) -> Option<Entity<ui::ContextMenu>>,
  833        >,
  834    >,
  835    last_bounds: Option<Bounds<Pixels>>,
  836    last_position_map: Option<Rc<PositionMap>>,
  837    expect_bounds_change: Option<Bounds<Pixels>>,
  838    tasks: BTreeMap<(BufferId, BufferRow), RunnableTasks>,
  839    tasks_update_task: Option<Task<()>>,
  840    breakpoint_store: Option<Entity<BreakpointStore>>,
  841    /// Allow's a user to create a breakpoint by selecting this indicator
  842    /// It should be None while a user is not hovering over the gutter
  843    /// Otherwise it represents the point that the breakpoint will be shown
  844    gutter_breakpoint_indicator: (Option<(DisplayPoint, bool)>, Option<Task<()>>),
  845    in_project_search: bool,
  846    previous_search_ranges: Option<Arc<[Range<Anchor>]>>,
  847    breadcrumb_header: Option<String>,
  848    focused_block: Option<FocusedBlock>,
  849    next_scroll_position: NextScrollCursorCenterTopBottom,
  850    addons: HashMap<TypeId, Box<dyn Addon>>,
  851    registered_buffers: HashMap<BufferId, OpenLspBufferHandle>,
  852    load_diff_task: Option<Shared<Task<()>>>,
  853    selection_mark_mode: bool,
  854    toggle_fold_multiple_buffers: Task<()>,
  855    _scroll_cursor_center_top_bottom_task: Task<()>,
  856    serialize_selections: Task<()>,
  857    serialize_folds: Task<()>,
  858    mouse_cursor_hidden: bool,
  859    hide_mouse_mode: HideMouseMode,
  860}
  861
  862#[derive(Copy, Clone, Debug, PartialEq, Eq, Default)]
  863enum NextScrollCursorCenterTopBottom {
  864    #[default]
  865    Center,
  866    Top,
  867    Bottom,
  868}
  869
  870impl NextScrollCursorCenterTopBottom {
  871    fn next(&self) -> Self {
  872        match self {
  873            Self::Center => Self::Top,
  874            Self::Top => Self::Bottom,
  875            Self::Bottom => Self::Center,
  876        }
  877    }
  878}
  879
  880#[derive(Clone)]
  881pub struct EditorSnapshot {
  882    pub mode: EditorMode,
  883    show_gutter: bool,
  884    show_line_numbers: Option<bool>,
  885    show_git_diff_gutter: Option<bool>,
  886    show_code_actions: Option<bool>,
  887    show_runnables: Option<bool>,
  888    show_breakpoints: Option<bool>,
  889    git_blame_gutter_max_author_length: Option<usize>,
  890    pub display_snapshot: DisplaySnapshot,
  891    pub placeholder_text: Option<Arc<str>>,
  892    is_focused: bool,
  893    scroll_anchor: ScrollAnchor,
  894    ongoing_scroll: OngoingScroll,
  895    current_line_highlight: CurrentLineHighlight,
  896    gutter_hovered: bool,
  897}
  898
  899#[derive(Default, Debug, Clone, Copy)]
  900pub struct GutterDimensions {
  901    pub left_padding: Pixels,
  902    pub right_padding: Pixels,
  903    pub width: Pixels,
  904    pub margin: Pixels,
  905    pub git_blame_entries_width: Option<Pixels>,
  906}
  907
  908impl GutterDimensions {
  909    /// The full width of the space taken up by the gutter.
  910    pub fn full_width(&self) -> Pixels {
  911        self.margin + self.width
  912    }
  913
  914    /// The width of the space reserved for the fold indicators,
  915    /// use alongside 'justify_end' and `gutter_width` to
  916    /// right align content with the line numbers
  917    pub fn fold_area_width(&self) -> Pixels {
  918        self.margin + self.right_padding
  919    }
  920}
  921
  922#[derive(Debug)]
  923pub struct RemoteSelection {
  924    pub replica_id: ReplicaId,
  925    pub selection: Selection<Anchor>,
  926    pub cursor_shape: CursorShape,
  927    pub peer_id: PeerId,
  928    pub line_mode: bool,
  929    pub participant_index: Option<ParticipantIndex>,
  930    pub user_name: Option<SharedString>,
  931}
  932
  933#[derive(Clone, Debug)]
  934struct SelectionHistoryEntry {
  935    selections: Arc<[Selection<Anchor>]>,
  936    select_next_state: Option<SelectNextState>,
  937    select_prev_state: Option<SelectNextState>,
  938    add_selections_state: Option<AddSelectionsState>,
  939}
  940
  941enum SelectionHistoryMode {
  942    Normal,
  943    Undoing,
  944    Redoing,
  945}
  946
  947#[derive(Clone, PartialEq, Eq, Hash)]
  948struct HoveredCursor {
  949    replica_id: u16,
  950    selection_id: usize,
  951}
  952
  953impl Default for SelectionHistoryMode {
  954    fn default() -> Self {
  955        Self::Normal
  956    }
  957}
  958
  959#[derive(Default)]
  960struct SelectionHistory {
  961    #[allow(clippy::type_complexity)]
  962    selections_by_transaction:
  963        HashMap<TransactionId, (Arc<[Selection<Anchor>]>, Option<Arc<[Selection<Anchor>]>>)>,
  964    mode: SelectionHistoryMode,
  965    undo_stack: VecDeque<SelectionHistoryEntry>,
  966    redo_stack: VecDeque<SelectionHistoryEntry>,
  967}
  968
  969impl SelectionHistory {
  970    fn insert_transaction(
  971        &mut self,
  972        transaction_id: TransactionId,
  973        selections: Arc<[Selection<Anchor>]>,
  974    ) {
  975        self.selections_by_transaction
  976            .insert(transaction_id, (selections, None));
  977    }
  978
  979    #[allow(clippy::type_complexity)]
  980    fn transaction(
  981        &self,
  982        transaction_id: TransactionId,
  983    ) -> Option<&(Arc<[Selection<Anchor>]>, Option<Arc<[Selection<Anchor>]>>)> {
  984        self.selections_by_transaction.get(&transaction_id)
  985    }
  986
  987    #[allow(clippy::type_complexity)]
  988    fn transaction_mut(
  989        &mut self,
  990        transaction_id: TransactionId,
  991    ) -> Option<&mut (Arc<[Selection<Anchor>]>, Option<Arc<[Selection<Anchor>]>>)> {
  992        self.selections_by_transaction.get_mut(&transaction_id)
  993    }
  994
  995    fn push(&mut self, entry: SelectionHistoryEntry) {
  996        if !entry.selections.is_empty() {
  997            match self.mode {
  998                SelectionHistoryMode::Normal => {
  999                    self.push_undo(entry);
 1000                    self.redo_stack.clear();
 1001                }
 1002                SelectionHistoryMode::Undoing => self.push_redo(entry),
 1003                SelectionHistoryMode::Redoing => self.push_undo(entry),
 1004            }
 1005        }
 1006    }
 1007
 1008    fn push_undo(&mut self, entry: SelectionHistoryEntry) {
 1009        if self
 1010            .undo_stack
 1011            .back()
 1012            .map_or(true, |e| e.selections != entry.selections)
 1013        {
 1014            self.undo_stack.push_back(entry);
 1015            if self.undo_stack.len() > MAX_SELECTION_HISTORY_LEN {
 1016                self.undo_stack.pop_front();
 1017            }
 1018        }
 1019    }
 1020
 1021    fn push_redo(&mut self, entry: SelectionHistoryEntry) {
 1022        if self
 1023            .redo_stack
 1024            .back()
 1025            .map_or(true, |e| e.selections != entry.selections)
 1026        {
 1027            self.redo_stack.push_back(entry);
 1028            if self.redo_stack.len() > MAX_SELECTION_HISTORY_LEN {
 1029                self.redo_stack.pop_front();
 1030            }
 1031        }
 1032    }
 1033}
 1034
 1035struct RowHighlight {
 1036    index: usize,
 1037    range: Range<Anchor>,
 1038    color: Hsla,
 1039    should_autoscroll: bool,
 1040}
 1041
 1042#[derive(Clone, Debug)]
 1043struct AddSelectionsState {
 1044    above: bool,
 1045    stack: Vec<usize>,
 1046}
 1047
 1048#[derive(Clone)]
 1049struct SelectNextState {
 1050    query: AhoCorasick,
 1051    wordwise: bool,
 1052    done: bool,
 1053}
 1054
 1055impl std::fmt::Debug for SelectNextState {
 1056    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
 1057        f.debug_struct(std::any::type_name::<Self>())
 1058            .field("wordwise", &self.wordwise)
 1059            .field("done", &self.done)
 1060            .finish()
 1061    }
 1062}
 1063
 1064#[derive(Debug)]
 1065struct AutocloseRegion {
 1066    selection_id: usize,
 1067    range: Range<Anchor>,
 1068    pair: BracketPair,
 1069}
 1070
 1071#[derive(Debug)]
 1072struct SnippetState {
 1073    ranges: Vec<Vec<Range<Anchor>>>,
 1074    active_index: usize,
 1075    choices: Vec<Option<Vec<String>>>,
 1076}
 1077
 1078#[doc(hidden)]
 1079pub struct RenameState {
 1080    pub range: Range<Anchor>,
 1081    pub old_name: Arc<str>,
 1082    pub editor: Entity<Editor>,
 1083    block_id: CustomBlockId,
 1084}
 1085
 1086struct InvalidationStack<T>(Vec<T>);
 1087
 1088struct RegisteredInlineCompletionProvider {
 1089    provider: Arc<dyn InlineCompletionProviderHandle>,
 1090    _subscription: Subscription,
 1091}
 1092
 1093#[derive(Debug, PartialEq, Eq)]
 1094pub struct ActiveDiagnosticGroup {
 1095    pub active_range: Range<Anchor>,
 1096    pub active_message: String,
 1097    pub group_id: usize,
 1098    pub blocks: HashSet<CustomBlockId>,
 1099}
 1100
 1101#[derive(Debug, PartialEq, Eq)]
 1102#[allow(clippy::large_enum_variant)]
 1103pub(crate) enum ActiveDiagnostic {
 1104    None,
 1105    All,
 1106    Group(ActiveDiagnosticGroup),
 1107}
 1108
 1109#[derive(Serialize, Deserialize, Clone, Debug)]
 1110pub struct ClipboardSelection {
 1111    /// The number of bytes in this selection.
 1112    pub len: usize,
 1113    /// Whether this was a full-line selection.
 1114    pub is_entire_line: bool,
 1115    /// The indentation of the first line when this content was originally copied.
 1116    pub first_line_indent: u32,
 1117}
 1118
 1119// selections, scroll behavior, was newest selection reversed
 1120type SelectSyntaxNodeHistoryState = (
 1121    Box<[Selection<usize>]>,
 1122    SelectSyntaxNodeScrollBehavior,
 1123    bool,
 1124);
 1125
 1126#[derive(Default)]
 1127struct SelectSyntaxNodeHistory {
 1128    stack: Vec<SelectSyntaxNodeHistoryState>,
 1129    // disable temporarily to allow changing selections without losing the stack
 1130    pub disable_clearing: bool,
 1131}
 1132
 1133impl SelectSyntaxNodeHistory {
 1134    pub fn try_clear(&mut self) {
 1135        if !self.disable_clearing {
 1136            self.stack.clear();
 1137        }
 1138    }
 1139
 1140    pub fn push(&mut self, selection: SelectSyntaxNodeHistoryState) {
 1141        self.stack.push(selection);
 1142    }
 1143
 1144    pub fn pop(&mut self) -> Option<SelectSyntaxNodeHistoryState> {
 1145        self.stack.pop()
 1146    }
 1147}
 1148
 1149enum SelectSyntaxNodeScrollBehavior {
 1150    CursorTop,
 1151    FitSelection,
 1152    CursorBottom,
 1153}
 1154
 1155#[derive(Debug)]
 1156pub(crate) struct NavigationData {
 1157    cursor_anchor: Anchor,
 1158    cursor_position: Point,
 1159    scroll_anchor: ScrollAnchor,
 1160    scroll_top_row: u32,
 1161}
 1162
 1163#[derive(Debug, Clone, Copy, PartialEq, Eq)]
 1164pub enum GotoDefinitionKind {
 1165    Symbol,
 1166    Declaration,
 1167    Type,
 1168    Implementation,
 1169}
 1170
 1171#[derive(Debug, Clone)]
 1172enum InlayHintRefreshReason {
 1173    ModifiersChanged(bool),
 1174    Toggle(bool),
 1175    SettingsChange(InlayHintSettings),
 1176    NewLinesShown,
 1177    BufferEdited(HashSet<Arc<Language>>),
 1178    RefreshRequested,
 1179    ExcerptsRemoved(Vec<ExcerptId>),
 1180}
 1181
 1182impl InlayHintRefreshReason {
 1183    fn description(&self) -> &'static str {
 1184        match self {
 1185            Self::ModifiersChanged(_) => "modifiers changed",
 1186            Self::Toggle(_) => "toggle",
 1187            Self::SettingsChange(_) => "settings change",
 1188            Self::NewLinesShown => "new lines shown",
 1189            Self::BufferEdited(_) => "buffer edited",
 1190            Self::RefreshRequested => "refresh requested",
 1191            Self::ExcerptsRemoved(_) => "excerpts removed",
 1192        }
 1193    }
 1194}
 1195
 1196pub enum FormatTarget {
 1197    Buffers,
 1198    Ranges(Vec<Range<MultiBufferPoint>>),
 1199}
 1200
 1201pub(crate) struct FocusedBlock {
 1202    id: BlockId,
 1203    focus_handle: WeakFocusHandle,
 1204}
 1205
 1206#[derive(Clone)]
 1207enum JumpData {
 1208    MultiBufferRow {
 1209        row: MultiBufferRow,
 1210        line_offset_from_top: u32,
 1211    },
 1212    MultiBufferPoint {
 1213        excerpt_id: ExcerptId,
 1214        position: Point,
 1215        anchor: text::Anchor,
 1216        line_offset_from_top: u32,
 1217    },
 1218}
 1219
 1220pub enum MultibufferSelectionMode {
 1221    First,
 1222    All,
 1223}
 1224
 1225#[derive(Clone, Copy, Debug, Default)]
 1226pub struct RewrapOptions {
 1227    pub override_language_settings: bool,
 1228    pub preserve_existing_whitespace: bool,
 1229}
 1230
 1231impl Editor {
 1232    pub fn single_line(window: &mut Window, cx: &mut Context<Self>) -> Self {
 1233        let buffer = cx.new(|cx| Buffer::local("", cx));
 1234        let buffer = cx.new(|cx| MultiBuffer::singleton(buffer, cx));
 1235        Self::new(
 1236            EditorMode::SingleLine { auto_width: false },
 1237            buffer,
 1238            None,
 1239            window,
 1240            cx,
 1241        )
 1242    }
 1243
 1244    pub fn multi_line(window: &mut Window, cx: &mut Context<Self>) -> Self {
 1245        let buffer = cx.new(|cx| Buffer::local("", cx));
 1246        let buffer = cx.new(|cx| MultiBuffer::singleton(buffer, cx));
 1247        Self::new(EditorMode::full(), buffer, None, window, cx)
 1248    }
 1249
 1250    pub fn auto_width(window: &mut Window, cx: &mut Context<Self>) -> Self {
 1251        let buffer = cx.new(|cx| Buffer::local("", cx));
 1252        let buffer = cx.new(|cx| MultiBuffer::singleton(buffer, cx));
 1253        Self::new(
 1254            EditorMode::SingleLine { auto_width: true },
 1255            buffer,
 1256            None,
 1257            window,
 1258            cx,
 1259        )
 1260    }
 1261
 1262    pub fn auto_height(max_lines: usize, window: &mut Window, cx: &mut Context<Self>) -> Self {
 1263        let buffer = cx.new(|cx| Buffer::local("", cx));
 1264        let buffer = cx.new(|cx| MultiBuffer::singleton(buffer, cx));
 1265        Self::new(
 1266            EditorMode::AutoHeight { max_lines },
 1267            buffer,
 1268            None,
 1269            window,
 1270            cx,
 1271        )
 1272    }
 1273
 1274    pub fn for_buffer(
 1275        buffer: Entity<Buffer>,
 1276        project: Option<Entity<Project>>,
 1277        window: &mut Window,
 1278        cx: &mut Context<Self>,
 1279    ) -> Self {
 1280        let buffer = cx.new(|cx| MultiBuffer::singleton(buffer, cx));
 1281        Self::new(EditorMode::full(), buffer, project, window, cx)
 1282    }
 1283
 1284    pub fn for_multibuffer(
 1285        buffer: Entity<MultiBuffer>,
 1286        project: Option<Entity<Project>>,
 1287        window: &mut Window,
 1288        cx: &mut Context<Self>,
 1289    ) -> Self {
 1290        Self::new(EditorMode::full(), buffer, project, window, cx)
 1291    }
 1292
 1293    pub fn clone(&self, window: &mut Window, cx: &mut Context<Self>) -> Self {
 1294        let mut clone = Self::new(
 1295            self.mode,
 1296            self.buffer.clone(),
 1297            self.project.clone(),
 1298            window,
 1299            cx,
 1300        );
 1301        self.display_map.update(cx, |display_map, cx| {
 1302            let snapshot = display_map.snapshot(cx);
 1303            clone.display_map.update(cx, |display_map, cx| {
 1304                display_map.set_state(&snapshot, cx);
 1305            });
 1306        });
 1307        clone.folds_did_change(cx);
 1308        clone.selections.clone_state(&self.selections);
 1309        clone.scroll_manager.clone_state(&self.scroll_manager);
 1310        clone.searchable = self.searchable;
 1311        clone.read_only = self.read_only;
 1312        clone
 1313    }
 1314
 1315    pub fn new(
 1316        mode: EditorMode,
 1317        buffer: Entity<MultiBuffer>,
 1318        project: Option<Entity<Project>>,
 1319        window: &mut Window,
 1320        cx: &mut Context<Self>,
 1321    ) -> Self {
 1322        let style = window.text_style();
 1323        let font_size = style.font_size.to_pixels(window.rem_size());
 1324        let editor = cx.entity().downgrade();
 1325        let fold_placeholder = FoldPlaceholder {
 1326            constrain_width: true,
 1327            render: Arc::new(move |fold_id, fold_range, cx| {
 1328                let editor = editor.clone();
 1329                div()
 1330                    .id(fold_id)
 1331                    .bg(cx.theme().colors().ghost_element_background)
 1332                    .hover(|style| style.bg(cx.theme().colors().ghost_element_hover))
 1333                    .active(|style| style.bg(cx.theme().colors().ghost_element_active))
 1334                    .rounded_xs()
 1335                    .size_full()
 1336                    .cursor_pointer()
 1337                    .child("")
 1338                    .on_mouse_down(MouseButton::Left, |_, _, cx| cx.stop_propagation())
 1339                    .on_click(move |_, _window, cx| {
 1340                        editor
 1341                            .update(cx, |editor, cx| {
 1342                                editor.unfold_ranges(
 1343                                    &[fold_range.start..fold_range.end],
 1344                                    true,
 1345                                    false,
 1346                                    cx,
 1347                                );
 1348                                cx.stop_propagation();
 1349                            })
 1350                            .ok();
 1351                    })
 1352                    .into_any()
 1353            }),
 1354            merge_adjacent: true,
 1355            ..Default::default()
 1356        };
 1357        let display_map = cx.new(|cx| {
 1358            DisplayMap::new(
 1359                buffer.clone(),
 1360                style.font(),
 1361                font_size,
 1362                None,
 1363                FILE_HEADER_HEIGHT,
 1364                MULTI_BUFFER_EXCERPT_HEADER_HEIGHT,
 1365                fold_placeholder,
 1366                cx,
 1367            )
 1368        });
 1369
 1370        let selections = SelectionsCollection::new(display_map.clone(), buffer.clone());
 1371
 1372        let blink_manager = cx.new(|cx| BlinkManager::new(CURSOR_BLINK_INTERVAL, cx));
 1373
 1374        let soft_wrap_mode_override = matches!(mode, EditorMode::SingleLine { .. })
 1375            .then(|| language_settings::SoftWrap::None);
 1376
 1377        let mut project_subscriptions = Vec::new();
 1378        if mode.is_full() {
 1379            if let Some(project) = project.as_ref() {
 1380                project_subscriptions.push(cx.subscribe_in(
 1381                    project,
 1382                    window,
 1383                    |editor, _, event, window, cx| match event {
 1384                        project::Event::RefreshCodeLens => {
 1385                            // we always query lens with actions, without storing them, always refreshing them
 1386                        }
 1387                        project::Event::RefreshInlayHints => {
 1388                            editor
 1389                                .refresh_inlay_hints(InlayHintRefreshReason::RefreshRequested, cx);
 1390                        }
 1391                        project::Event::SnippetEdit(id, snippet_edits) => {
 1392                            if let Some(buffer) = editor.buffer.read(cx).buffer(*id) {
 1393                                let focus_handle = editor.focus_handle(cx);
 1394                                if focus_handle.is_focused(window) {
 1395                                    let snapshot = buffer.read(cx).snapshot();
 1396                                    for (range, snippet) in snippet_edits {
 1397                                        let editor_range =
 1398                                            language::range_from_lsp(*range).to_offset(&snapshot);
 1399                                        editor
 1400                                            .insert_snippet(
 1401                                                &[editor_range],
 1402                                                snippet.clone(),
 1403                                                window,
 1404                                                cx,
 1405                                            )
 1406                                            .ok();
 1407                                    }
 1408                                }
 1409                            }
 1410                        }
 1411                        _ => {}
 1412                    },
 1413                ));
 1414                if let Some(task_inventory) = project
 1415                    .read(cx)
 1416                    .task_store()
 1417                    .read(cx)
 1418                    .task_inventory()
 1419                    .cloned()
 1420                {
 1421                    project_subscriptions.push(cx.observe_in(
 1422                        &task_inventory,
 1423                        window,
 1424                        |editor, _, window, cx| {
 1425                            editor.tasks_update_task = Some(editor.refresh_runnables(window, cx));
 1426                        },
 1427                    ));
 1428                };
 1429
 1430                project_subscriptions.push(cx.subscribe_in(
 1431                    &project.read(cx).breakpoint_store(),
 1432                    window,
 1433                    |editor, _, event, window, cx| match event {
 1434                        BreakpointStoreEvent::ActiveDebugLineChanged => {
 1435                            if editor.go_to_active_debug_line(window, cx) {
 1436                                cx.stop_propagation();
 1437                            }
 1438                        }
 1439                        _ => {}
 1440                    },
 1441                ));
 1442            }
 1443        }
 1444
 1445        let buffer_snapshot = buffer.read(cx).snapshot(cx);
 1446
 1447        let inlay_hint_settings =
 1448            inlay_hint_settings(selections.newest_anchor().head(), &buffer_snapshot, cx);
 1449        let focus_handle = cx.focus_handle();
 1450        cx.on_focus(&focus_handle, window, Self::handle_focus)
 1451            .detach();
 1452        cx.on_focus_in(&focus_handle, window, Self::handle_focus_in)
 1453            .detach();
 1454        cx.on_focus_out(&focus_handle, window, Self::handle_focus_out)
 1455            .detach();
 1456        cx.on_blur(&focus_handle, window, Self::handle_blur)
 1457            .detach();
 1458
 1459        let show_indent_guides = if matches!(mode, EditorMode::SingleLine { .. }) {
 1460            Some(false)
 1461        } else {
 1462            None
 1463        };
 1464
 1465        let breakpoint_store = match (mode, project.as_ref()) {
 1466            (EditorMode::Full { .. }, Some(project)) => Some(project.read(cx).breakpoint_store()),
 1467            _ => None,
 1468        };
 1469
 1470        let mut code_action_providers = Vec::new();
 1471        let mut load_uncommitted_diff = None;
 1472        if let Some(project) = project.clone() {
 1473            load_uncommitted_diff = Some(
 1474                get_uncommitted_diff_for_buffer(
 1475                    &project,
 1476                    buffer.read(cx).all_buffers(),
 1477                    buffer.clone(),
 1478                    cx,
 1479                )
 1480                .shared(),
 1481            );
 1482            code_action_providers.push(Rc::new(project) as Rc<_>);
 1483        }
 1484
 1485        let mut this = Self {
 1486            focus_handle,
 1487            show_cursor_when_unfocused: false,
 1488            last_focused_descendant: None,
 1489            buffer: buffer.clone(),
 1490            display_map: display_map.clone(),
 1491            selections,
 1492            scroll_manager: ScrollManager::new(cx),
 1493            columnar_selection_tail: None,
 1494            add_selections_state: None,
 1495            select_next_state: None,
 1496            select_prev_state: None,
 1497            selection_history: Default::default(),
 1498            autoclose_regions: Default::default(),
 1499            snippet_stack: Default::default(),
 1500            select_syntax_node_history: SelectSyntaxNodeHistory::default(),
 1501            ime_transaction: Default::default(),
 1502            active_diagnostics: ActiveDiagnostic::None,
 1503            show_inline_diagnostics: ProjectSettings::get_global(cx).diagnostics.inline.enabled,
 1504            inline_diagnostics_update: Task::ready(()),
 1505            inline_diagnostics: Vec::new(),
 1506            soft_wrap_mode_override,
 1507            hard_wrap: None,
 1508            completion_provider: project.clone().map(|project| Box::new(project) as _),
 1509            semantics_provider: project.clone().map(|project| Rc::new(project) as _),
 1510            collaboration_hub: project.clone().map(|project| Box::new(project) as _),
 1511            project,
 1512            blink_manager: blink_manager.clone(),
 1513            show_local_selections: true,
 1514            show_scrollbars: true,
 1515            mode,
 1516            show_breadcrumbs: EditorSettings::get_global(cx).toolbar.breadcrumbs,
 1517            show_gutter: mode.is_full(),
 1518            show_line_numbers: None,
 1519            use_relative_line_numbers: None,
 1520            show_git_diff_gutter: None,
 1521            show_code_actions: None,
 1522            show_runnables: None,
 1523            show_breakpoints: None,
 1524            show_wrap_guides: None,
 1525            show_indent_guides,
 1526            placeholder_text: None,
 1527            highlight_order: 0,
 1528            highlighted_rows: HashMap::default(),
 1529            background_highlights: Default::default(),
 1530            gutter_highlights: TreeMap::default(),
 1531            scrollbar_marker_state: ScrollbarMarkerState::default(),
 1532            active_indent_guides_state: ActiveIndentGuidesState::default(),
 1533            nav_history: None,
 1534            context_menu: RefCell::new(None),
 1535            context_menu_options: None,
 1536            mouse_context_menu: None,
 1537            completion_tasks: Default::default(),
 1538            signature_help_state: SignatureHelpState::default(),
 1539            auto_signature_help: None,
 1540            find_all_references_task_sources: Vec::new(),
 1541            next_completion_id: 0,
 1542            next_inlay_id: 0,
 1543            code_action_providers,
 1544            available_code_actions: Default::default(),
 1545            code_actions_task: Default::default(),
 1546            selection_highlight_task: Default::default(),
 1547            document_highlights_task: Default::default(),
 1548            linked_editing_range_task: Default::default(),
 1549            pending_rename: Default::default(),
 1550            searchable: true,
 1551            cursor_shape: EditorSettings::get_global(cx)
 1552                .cursor_shape
 1553                .unwrap_or_default(),
 1554            current_line_highlight: None,
 1555            autoindent_mode: Some(AutoindentMode::EachLine),
 1556            collapse_matches: false,
 1557            workspace: None,
 1558            input_enabled: true,
 1559            use_modal_editing: mode.is_full(),
 1560            read_only: false,
 1561            use_autoclose: true,
 1562            use_auto_surround: true,
 1563            auto_replace_emoji_shortcode: false,
 1564            jsx_tag_auto_close_enabled_in_any_buffer: false,
 1565            leader_peer_id: None,
 1566            remote_id: None,
 1567            hover_state: Default::default(),
 1568            pending_mouse_down: None,
 1569            hovered_link_state: Default::default(),
 1570            edit_prediction_provider: None,
 1571            active_inline_completion: None,
 1572            stale_inline_completion_in_menu: None,
 1573            edit_prediction_preview: EditPredictionPreview::Inactive {
 1574                released_too_fast: false,
 1575            },
 1576            inline_diagnostics_enabled: mode.is_full(),
 1577            inlay_hint_cache: InlayHintCache::new(inlay_hint_settings),
 1578
 1579            gutter_hovered: false,
 1580            pixel_position_of_newest_cursor: None,
 1581            last_bounds: None,
 1582            last_position_map: None,
 1583            expect_bounds_change: None,
 1584            gutter_dimensions: GutterDimensions::default(),
 1585            style: None,
 1586            show_cursor_names: false,
 1587            hovered_cursors: Default::default(),
 1588            next_editor_action_id: EditorActionId::default(),
 1589            editor_actions: Rc::default(),
 1590            inline_completions_hidden_for_vim_mode: false,
 1591            show_inline_completions_override: None,
 1592            menu_inline_completions_policy: MenuInlineCompletionsPolicy::ByProvider,
 1593            edit_prediction_settings: EditPredictionSettings::Disabled,
 1594            edit_prediction_indent_conflict: false,
 1595            edit_prediction_requires_modifier_in_indent_conflict: true,
 1596            custom_context_menu: None,
 1597            show_git_blame_gutter: false,
 1598            show_git_blame_inline: false,
 1599            show_selection_menu: None,
 1600            show_git_blame_inline_delay_task: None,
 1601            git_blame_inline_tooltip: None,
 1602            git_blame_inline_enabled: ProjectSettings::get_global(cx).git.inline_blame_enabled(),
 1603            render_diff_hunk_controls: Arc::new(render_diff_hunk_controls),
 1604            serialize_dirty_buffers: ProjectSettings::get_global(cx)
 1605                .session
 1606                .restore_unsaved_buffers,
 1607            blame: None,
 1608            blame_subscription: None,
 1609            tasks: Default::default(),
 1610
 1611            breakpoint_store,
 1612            gutter_breakpoint_indicator: (None, None),
 1613            _subscriptions: vec![
 1614                cx.observe(&buffer, Self::on_buffer_changed),
 1615                cx.subscribe_in(&buffer, window, Self::on_buffer_event),
 1616                cx.observe_in(&display_map, window, Self::on_display_map_changed),
 1617                cx.observe(&blink_manager, |_, _, cx| cx.notify()),
 1618                cx.observe_global_in::<SettingsStore>(window, Self::settings_changed),
 1619                observe_buffer_font_size_adjustment(cx, |_, cx| cx.notify()),
 1620                cx.observe_window_activation(window, |editor, window, cx| {
 1621                    let active = window.is_window_active();
 1622                    editor.blink_manager.update(cx, |blink_manager, cx| {
 1623                        if active {
 1624                            blink_manager.enable(cx);
 1625                        } else {
 1626                            blink_manager.disable(cx);
 1627                        }
 1628                    });
 1629                }),
 1630            ],
 1631            tasks_update_task: None,
 1632            linked_edit_ranges: Default::default(),
 1633            in_project_search: false,
 1634            previous_search_ranges: None,
 1635            breadcrumb_header: None,
 1636            focused_block: None,
 1637            next_scroll_position: NextScrollCursorCenterTopBottom::default(),
 1638            addons: HashMap::default(),
 1639            registered_buffers: HashMap::default(),
 1640            _scroll_cursor_center_top_bottom_task: Task::ready(()),
 1641            selection_mark_mode: false,
 1642            toggle_fold_multiple_buffers: Task::ready(()),
 1643            serialize_selections: Task::ready(()),
 1644            serialize_folds: Task::ready(()),
 1645            text_style_refinement: None,
 1646            load_diff_task: load_uncommitted_diff,
 1647            mouse_cursor_hidden: false,
 1648            hide_mouse_mode: EditorSettings::get_global(cx)
 1649                .hide_mouse
 1650                .unwrap_or_default(),
 1651        };
 1652        if let Some(breakpoints) = this.breakpoint_store.as_ref() {
 1653            this._subscriptions
 1654                .push(cx.observe(breakpoints, |_, _, cx| {
 1655                    cx.notify();
 1656                }));
 1657        }
 1658        this.tasks_update_task = Some(this.refresh_runnables(window, cx));
 1659        this._subscriptions.extend(project_subscriptions);
 1660
 1661        this._subscriptions.push(cx.subscribe_in(
 1662            &cx.entity(),
 1663            window,
 1664            |editor, _, e: &EditorEvent, window, cx| {
 1665                if let EditorEvent::SelectionsChanged { local } = e {
 1666                    if *local {
 1667                        let new_anchor = editor.scroll_manager.anchor();
 1668                        let snapshot = editor.snapshot(window, cx);
 1669                        editor.update_restoration_data(cx, move |data| {
 1670                            data.scroll_position = (
 1671                                new_anchor.top_row(&snapshot.buffer_snapshot),
 1672                                new_anchor.offset,
 1673                            );
 1674                        });
 1675                    }
 1676                }
 1677            },
 1678        ));
 1679
 1680        this.end_selection(window, cx);
 1681        this.scroll_manager.show_scrollbars(window, cx);
 1682        jsx_tag_auto_close::refresh_enabled_in_any_buffer(&mut this, &buffer, cx);
 1683
 1684        if mode.is_full() {
 1685            let should_auto_hide_scrollbars = cx.should_auto_hide_scrollbars();
 1686            cx.set_global(ScrollbarAutoHide(should_auto_hide_scrollbars));
 1687
 1688            if this.git_blame_inline_enabled {
 1689                this.git_blame_inline_enabled = true;
 1690                this.start_git_blame_inline(false, window, cx);
 1691            }
 1692
 1693            this.go_to_active_debug_line(window, cx);
 1694
 1695            if let Some(buffer) = buffer.read(cx).as_singleton() {
 1696                if let Some(project) = this.project.as_ref() {
 1697                    let handle = project.update(cx, |project, cx| {
 1698                        project.register_buffer_with_language_servers(&buffer, cx)
 1699                    });
 1700                    this.registered_buffers
 1701                        .insert(buffer.read(cx).remote_id(), handle);
 1702                }
 1703            }
 1704        }
 1705
 1706        this.report_editor_event("Editor Opened", None, cx);
 1707        this
 1708    }
 1709
 1710    pub fn deploy_mouse_context_menu(
 1711        &mut self,
 1712        position: gpui::Point<Pixels>,
 1713        context_menu: Entity<ContextMenu>,
 1714        window: &mut Window,
 1715        cx: &mut Context<Self>,
 1716    ) {
 1717        self.mouse_context_menu = Some(MouseContextMenu::new(
 1718            crate::mouse_context_menu::MenuPosition::PinnedToScreen(position),
 1719            context_menu,
 1720            None,
 1721            window,
 1722            cx,
 1723        ));
 1724    }
 1725
 1726    pub fn mouse_menu_is_focused(&self, window: &Window, cx: &App) -> bool {
 1727        self.mouse_context_menu
 1728            .as_ref()
 1729            .is_some_and(|menu| menu.context_menu.focus_handle(cx).is_focused(window))
 1730    }
 1731
 1732    fn key_context(&self, window: &Window, cx: &App) -> KeyContext {
 1733        self.key_context_internal(self.has_active_inline_completion(), window, cx)
 1734    }
 1735
 1736    fn key_context_internal(
 1737        &self,
 1738        has_active_edit_prediction: bool,
 1739        window: &Window,
 1740        cx: &App,
 1741    ) -> KeyContext {
 1742        let mut key_context = KeyContext::new_with_defaults();
 1743        key_context.add("Editor");
 1744        let mode = match self.mode {
 1745            EditorMode::SingleLine { .. } => "single_line",
 1746            EditorMode::AutoHeight { .. } => "auto_height",
 1747            EditorMode::Full { .. } => "full",
 1748        };
 1749
 1750        if EditorSettings::jupyter_enabled(cx) {
 1751            key_context.add("jupyter");
 1752        }
 1753
 1754        key_context.set("mode", mode);
 1755        if self.pending_rename.is_some() {
 1756            key_context.add("renaming");
 1757        }
 1758
 1759        match self.context_menu.borrow().as_ref() {
 1760            Some(CodeContextMenu::Completions(_)) => {
 1761                key_context.add("menu");
 1762                key_context.add("showing_completions");
 1763            }
 1764            Some(CodeContextMenu::CodeActions(_)) => {
 1765                key_context.add("menu");
 1766                key_context.add("showing_code_actions")
 1767            }
 1768            None => {}
 1769        }
 1770
 1771        // Disable vim contexts when a sub-editor (e.g. rename/inline assistant) is focused.
 1772        if !self.focus_handle(cx).contains_focused(window, cx)
 1773            || (self.is_focused(window) || self.mouse_menu_is_focused(window, cx))
 1774        {
 1775            for addon in self.addons.values() {
 1776                addon.extend_key_context(&mut key_context, cx)
 1777            }
 1778        }
 1779
 1780        if let Some(singleton_buffer) = self.buffer.read(cx).as_singleton() {
 1781            if let Some(extension) = singleton_buffer
 1782                .read(cx)
 1783                .file()
 1784                .and_then(|file| file.path().extension()?.to_str())
 1785            {
 1786                key_context.set("extension", extension.to_string());
 1787            }
 1788        } else {
 1789            key_context.add("multibuffer");
 1790        }
 1791
 1792        if has_active_edit_prediction {
 1793            if self.edit_prediction_in_conflict() {
 1794                key_context.add(EDIT_PREDICTION_CONFLICT_KEY_CONTEXT);
 1795            } else {
 1796                key_context.add(EDIT_PREDICTION_KEY_CONTEXT);
 1797                key_context.add("copilot_suggestion");
 1798            }
 1799        }
 1800
 1801        if self.selection_mark_mode {
 1802            key_context.add("selection_mode");
 1803        }
 1804
 1805        key_context
 1806    }
 1807
 1808    pub fn hide_mouse_cursor(&mut self, origin: &HideMouseCursorOrigin) {
 1809        self.mouse_cursor_hidden = match origin {
 1810            HideMouseCursorOrigin::TypingAction => {
 1811                matches!(
 1812                    self.hide_mouse_mode,
 1813                    HideMouseMode::OnTyping | HideMouseMode::OnTypingAndMovement
 1814                )
 1815            }
 1816            HideMouseCursorOrigin::MovementAction => {
 1817                matches!(self.hide_mouse_mode, HideMouseMode::OnTypingAndMovement)
 1818            }
 1819        };
 1820    }
 1821
 1822    pub fn edit_prediction_in_conflict(&self) -> bool {
 1823        if !self.show_edit_predictions_in_menu() {
 1824            return false;
 1825        }
 1826
 1827        let showing_completions = self
 1828            .context_menu
 1829            .borrow()
 1830            .as_ref()
 1831            .map_or(false, |context| {
 1832                matches!(context, CodeContextMenu::Completions(_))
 1833            });
 1834
 1835        showing_completions
 1836            || self.edit_prediction_requires_modifier()
 1837            // Require modifier key when the cursor is on leading whitespace, to allow `tab`
 1838            // bindings to insert tab characters.
 1839            || (self.edit_prediction_requires_modifier_in_indent_conflict && self.edit_prediction_indent_conflict)
 1840    }
 1841
 1842    pub fn accept_edit_prediction_keybind(
 1843        &self,
 1844        window: &Window,
 1845        cx: &App,
 1846    ) -> AcceptEditPredictionBinding {
 1847        let key_context = self.key_context_internal(true, window, cx);
 1848        let in_conflict = self.edit_prediction_in_conflict();
 1849
 1850        AcceptEditPredictionBinding(
 1851            window
 1852                .bindings_for_action_in_context(&AcceptEditPrediction, key_context)
 1853                .into_iter()
 1854                .filter(|binding| {
 1855                    !in_conflict
 1856                        || binding
 1857                            .keystrokes()
 1858                            .first()
 1859                            .map_or(false, |keystroke| keystroke.modifiers.modified())
 1860                })
 1861                .rev()
 1862                .min_by_key(|binding| {
 1863                    binding
 1864                        .keystrokes()
 1865                        .first()
 1866                        .map_or(u8::MAX, |k| k.modifiers.number_of_modifiers())
 1867                }),
 1868        )
 1869    }
 1870
 1871    pub fn new_file(
 1872        workspace: &mut Workspace,
 1873        _: &workspace::NewFile,
 1874        window: &mut Window,
 1875        cx: &mut Context<Workspace>,
 1876    ) {
 1877        Self::new_in_workspace(workspace, window, cx).detach_and_prompt_err(
 1878            "Failed to create buffer",
 1879            window,
 1880            cx,
 1881            |e, _, _| match e.error_code() {
 1882                ErrorCode::RemoteUpgradeRequired => Some(format!(
 1883                "The remote instance of Zed does not support this yet. It must be upgraded to {}",
 1884                e.error_tag("required").unwrap_or("the latest version")
 1885            )),
 1886                _ => None,
 1887            },
 1888        );
 1889    }
 1890
 1891    pub fn new_in_workspace(
 1892        workspace: &mut Workspace,
 1893        window: &mut Window,
 1894        cx: &mut Context<Workspace>,
 1895    ) -> Task<Result<Entity<Editor>>> {
 1896        let project = workspace.project().clone();
 1897        let create = project.update(cx, |project, cx| project.create_buffer(cx));
 1898
 1899        cx.spawn_in(window, async move |workspace, cx| {
 1900            let buffer = create.await?;
 1901            workspace.update_in(cx, |workspace, window, cx| {
 1902                let editor =
 1903                    cx.new(|cx| Editor::for_buffer(buffer, Some(project.clone()), window, cx));
 1904                workspace.add_item_to_active_pane(Box::new(editor.clone()), None, true, window, cx);
 1905                editor
 1906            })
 1907        })
 1908    }
 1909
 1910    fn new_file_vertical(
 1911        workspace: &mut Workspace,
 1912        _: &workspace::NewFileSplitVertical,
 1913        window: &mut Window,
 1914        cx: &mut Context<Workspace>,
 1915    ) {
 1916        Self::new_file_in_direction(workspace, SplitDirection::vertical(cx), window, cx)
 1917    }
 1918
 1919    fn new_file_horizontal(
 1920        workspace: &mut Workspace,
 1921        _: &workspace::NewFileSplitHorizontal,
 1922        window: &mut Window,
 1923        cx: &mut Context<Workspace>,
 1924    ) {
 1925        Self::new_file_in_direction(workspace, SplitDirection::horizontal(cx), window, cx)
 1926    }
 1927
 1928    fn new_file_in_direction(
 1929        workspace: &mut Workspace,
 1930        direction: SplitDirection,
 1931        window: &mut Window,
 1932        cx: &mut Context<Workspace>,
 1933    ) {
 1934        let project = workspace.project().clone();
 1935        let create = project.update(cx, |project, cx| project.create_buffer(cx));
 1936
 1937        cx.spawn_in(window, async move |workspace, cx| {
 1938            let buffer = create.await?;
 1939            workspace.update_in(cx, move |workspace, window, cx| {
 1940                workspace.split_item(
 1941                    direction,
 1942                    Box::new(
 1943                        cx.new(|cx| Editor::for_buffer(buffer, Some(project.clone()), window, cx)),
 1944                    ),
 1945                    window,
 1946                    cx,
 1947                )
 1948            })?;
 1949            anyhow::Ok(())
 1950        })
 1951        .detach_and_prompt_err("Failed to create buffer", window, cx, |e, _, _| {
 1952            match e.error_code() {
 1953                ErrorCode::RemoteUpgradeRequired => Some(format!(
 1954                "The remote instance of Zed does not support this yet. It must be upgraded to {}",
 1955                e.error_tag("required").unwrap_or("the latest version")
 1956            )),
 1957                _ => None,
 1958            }
 1959        });
 1960    }
 1961
 1962    pub fn leader_peer_id(&self) -> Option<PeerId> {
 1963        self.leader_peer_id
 1964    }
 1965
 1966    pub fn buffer(&self) -> &Entity<MultiBuffer> {
 1967        &self.buffer
 1968    }
 1969
 1970    pub fn workspace(&self) -> Option<Entity<Workspace>> {
 1971        self.workspace.as_ref()?.0.upgrade()
 1972    }
 1973
 1974    pub fn title<'a>(&self, cx: &'a App) -> Cow<'a, str> {
 1975        self.buffer().read(cx).title(cx)
 1976    }
 1977
 1978    pub fn snapshot(&self, window: &mut Window, cx: &mut App) -> EditorSnapshot {
 1979        let git_blame_gutter_max_author_length = self
 1980            .render_git_blame_gutter(cx)
 1981            .then(|| {
 1982                if let Some(blame) = self.blame.as_ref() {
 1983                    let max_author_length =
 1984                        blame.update(cx, |blame, cx| blame.max_author_length(cx));
 1985                    Some(max_author_length)
 1986                } else {
 1987                    None
 1988                }
 1989            })
 1990            .flatten();
 1991
 1992        EditorSnapshot {
 1993            mode: self.mode,
 1994            show_gutter: self.show_gutter,
 1995            show_line_numbers: self.show_line_numbers,
 1996            show_git_diff_gutter: self.show_git_diff_gutter,
 1997            show_code_actions: self.show_code_actions,
 1998            show_runnables: self.show_runnables,
 1999            show_breakpoints: self.show_breakpoints,
 2000            git_blame_gutter_max_author_length,
 2001            display_snapshot: self.display_map.update(cx, |map, cx| map.snapshot(cx)),
 2002            scroll_anchor: self.scroll_manager.anchor(),
 2003            ongoing_scroll: self.scroll_manager.ongoing_scroll(),
 2004            placeholder_text: self.placeholder_text.clone(),
 2005            is_focused: self.focus_handle.is_focused(window),
 2006            current_line_highlight: self
 2007                .current_line_highlight
 2008                .unwrap_or_else(|| EditorSettings::get_global(cx).current_line_highlight),
 2009            gutter_hovered: self.gutter_hovered,
 2010        }
 2011    }
 2012
 2013    pub fn language_at<T: ToOffset>(&self, point: T, cx: &App) -> Option<Arc<Language>> {
 2014        self.buffer.read(cx).language_at(point, cx)
 2015    }
 2016
 2017    pub fn file_at<T: ToOffset>(&self, point: T, cx: &App) -> Option<Arc<dyn language::File>> {
 2018        self.buffer.read(cx).read(cx).file_at(point).cloned()
 2019    }
 2020
 2021    pub fn active_excerpt(
 2022        &self,
 2023        cx: &App,
 2024    ) -> Option<(ExcerptId, Entity<Buffer>, Range<text::Anchor>)> {
 2025        self.buffer
 2026            .read(cx)
 2027            .excerpt_containing(self.selections.newest_anchor().head(), cx)
 2028    }
 2029
 2030    pub fn mode(&self) -> EditorMode {
 2031        self.mode
 2032    }
 2033
 2034    pub fn set_mode(&mut self, mode: EditorMode) {
 2035        self.mode = mode;
 2036    }
 2037
 2038    pub fn collaboration_hub(&self) -> Option<&dyn CollaborationHub> {
 2039        self.collaboration_hub.as_deref()
 2040    }
 2041
 2042    pub fn set_collaboration_hub(&mut self, hub: Box<dyn CollaborationHub>) {
 2043        self.collaboration_hub = Some(hub);
 2044    }
 2045
 2046    pub fn set_in_project_search(&mut self, in_project_search: bool) {
 2047        self.in_project_search = in_project_search;
 2048    }
 2049
 2050    pub fn set_custom_context_menu(
 2051        &mut self,
 2052        f: impl 'static
 2053        + Fn(
 2054            &mut Self,
 2055            DisplayPoint,
 2056            &mut Window,
 2057            &mut Context<Self>,
 2058        ) -> Option<Entity<ui::ContextMenu>>,
 2059    ) {
 2060        self.custom_context_menu = Some(Box::new(f))
 2061    }
 2062
 2063    pub fn set_completion_provider(&mut self, provider: Option<Box<dyn CompletionProvider>>) {
 2064        self.completion_provider = provider;
 2065    }
 2066
 2067    pub fn semantics_provider(&self) -> Option<Rc<dyn SemanticsProvider>> {
 2068        self.semantics_provider.clone()
 2069    }
 2070
 2071    pub fn set_semantics_provider(&mut self, provider: Option<Rc<dyn SemanticsProvider>>) {
 2072        self.semantics_provider = provider;
 2073    }
 2074
 2075    pub fn set_edit_prediction_provider<T>(
 2076        &mut self,
 2077        provider: Option<Entity<T>>,
 2078        window: &mut Window,
 2079        cx: &mut Context<Self>,
 2080    ) where
 2081        T: EditPredictionProvider,
 2082    {
 2083        self.edit_prediction_provider =
 2084            provider.map(|provider| RegisteredInlineCompletionProvider {
 2085                _subscription: cx.observe_in(&provider, window, |this, _, window, cx| {
 2086                    if this.focus_handle.is_focused(window) {
 2087                        this.update_visible_inline_completion(window, cx);
 2088                    }
 2089                }),
 2090                provider: Arc::new(provider),
 2091            });
 2092        self.update_edit_prediction_settings(cx);
 2093        self.refresh_inline_completion(false, false, window, cx);
 2094    }
 2095
 2096    pub fn placeholder_text(&self) -> Option<&str> {
 2097        self.placeholder_text.as_deref()
 2098    }
 2099
 2100    pub fn set_placeholder_text(
 2101        &mut self,
 2102        placeholder_text: impl Into<Arc<str>>,
 2103        cx: &mut Context<Self>,
 2104    ) {
 2105        let placeholder_text = Some(placeholder_text.into());
 2106        if self.placeholder_text != placeholder_text {
 2107            self.placeholder_text = placeholder_text;
 2108            cx.notify();
 2109        }
 2110    }
 2111
 2112    pub fn set_cursor_shape(&mut self, cursor_shape: CursorShape, cx: &mut Context<Self>) {
 2113        self.cursor_shape = cursor_shape;
 2114
 2115        // Disrupt blink for immediate user feedback that the cursor shape has changed
 2116        self.blink_manager.update(cx, BlinkManager::show_cursor);
 2117
 2118        cx.notify();
 2119    }
 2120
 2121    pub fn set_current_line_highlight(
 2122        &mut self,
 2123        current_line_highlight: Option<CurrentLineHighlight>,
 2124    ) {
 2125        self.current_line_highlight = current_line_highlight;
 2126    }
 2127
 2128    pub fn set_collapse_matches(&mut self, collapse_matches: bool) {
 2129        self.collapse_matches = collapse_matches;
 2130    }
 2131
 2132    fn register_buffers_with_language_servers(&mut self, cx: &mut Context<Self>) {
 2133        let buffers = self.buffer.read(cx).all_buffers();
 2134        let Some(project) = self.project.as_ref() else {
 2135            return;
 2136        };
 2137        project.update(cx, |project, cx| {
 2138            for buffer in buffers {
 2139                self.registered_buffers
 2140                    .entry(buffer.read(cx).remote_id())
 2141                    .or_insert_with(|| project.register_buffer_with_language_servers(&buffer, cx));
 2142            }
 2143        })
 2144    }
 2145
 2146    pub fn range_for_match<T: std::marker::Copy>(&self, range: &Range<T>) -> Range<T> {
 2147        if self.collapse_matches {
 2148            return range.start..range.start;
 2149        }
 2150        range.clone()
 2151    }
 2152
 2153    pub fn set_clip_at_line_ends(&mut self, clip: bool, cx: &mut Context<Self>) {
 2154        if self.display_map.read(cx).clip_at_line_ends != clip {
 2155            self.display_map
 2156                .update(cx, |map, _| map.clip_at_line_ends = clip);
 2157        }
 2158    }
 2159
 2160    pub fn set_input_enabled(&mut self, input_enabled: bool) {
 2161        self.input_enabled = input_enabled;
 2162    }
 2163
 2164    pub fn set_inline_completions_hidden_for_vim_mode(
 2165        &mut self,
 2166        hidden: bool,
 2167        window: &mut Window,
 2168        cx: &mut Context<Self>,
 2169    ) {
 2170        if hidden != self.inline_completions_hidden_for_vim_mode {
 2171            self.inline_completions_hidden_for_vim_mode = hidden;
 2172            if hidden {
 2173                self.update_visible_inline_completion(window, cx);
 2174            } else {
 2175                self.refresh_inline_completion(true, false, window, cx);
 2176            }
 2177        }
 2178    }
 2179
 2180    pub fn set_menu_inline_completions_policy(&mut self, value: MenuInlineCompletionsPolicy) {
 2181        self.menu_inline_completions_policy = value;
 2182    }
 2183
 2184    pub fn set_autoindent(&mut self, autoindent: bool) {
 2185        if autoindent {
 2186            self.autoindent_mode = Some(AutoindentMode::EachLine);
 2187        } else {
 2188            self.autoindent_mode = None;
 2189        }
 2190    }
 2191
 2192    pub fn read_only(&self, cx: &App) -> bool {
 2193        self.read_only || self.buffer.read(cx).read_only()
 2194    }
 2195
 2196    pub fn set_read_only(&mut self, read_only: bool) {
 2197        self.read_only = read_only;
 2198    }
 2199
 2200    pub fn set_use_autoclose(&mut self, autoclose: bool) {
 2201        self.use_autoclose = autoclose;
 2202    }
 2203
 2204    pub fn set_use_auto_surround(&mut self, auto_surround: bool) {
 2205        self.use_auto_surround = auto_surround;
 2206    }
 2207
 2208    pub fn set_auto_replace_emoji_shortcode(&mut self, auto_replace: bool) {
 2209        self.auto_replace_emoji_shortcode = auto_replace;
 2210    }
 2211
 2212    pub fn toggle_edit_predictions(
 2213        &mut self,
 2214        _: &ToggleEditPrediction,
 2215        window: &mut Window,
 2216        cx: &mut Context<Self>,
 2217    ) {
 2218        if self.show_inline_completions_override.is_some() {
 2219            self.set_show_edit_predictions(None, window, cx);
 2220        } else {
 2221            let show_edit_predictions = !self.edit_predictions_enabled();
 2222            self.set_show_edit_predictions(Some(show_edit_predictions), window, cx);
 2223        }
 2224    }
 2225
 2226    pub fn set_show_edit_predictions(
 2227        &mut self,
 2228        show_edit_predictions: Option<bool>,
 2229        window: &mut Window,
 2230        cx: &mut Context<Self>,
 2231    ) {
 2232        self.show_inline_completions_override = show_edit_predictions;
 2233        self.update_edit_prediction_settings(cx);
 2234
 2235        if let Some(false) = show_edit_predictions {
 2236            self.discard_inline_completion(false, cx);
 2237        } else {
 2238            self.refresh_inline_completion(false, true, window, cx);
 2239        }
 2240    }
 2241
 2242    fn inline_completions_disabled_in_scope(
 2243        &self,
 2244        buffer: &Entity<Buffer>,
 2245        buffer_position: language::Anchor,
 2246        cx: &App,
 2247    ) -> bool {
 2248        let snapshot = buffer.read(cx).snapshot();
 2249        let settings = snapshot.settings_at(buffer_position, cx);
 2250
 2251        let Some(scope) = snapshot.language_scope_at(buffer_position) else {
 2252            return false;
 2253        };
 2254
 2255        scope.override_name().map_or(false, |scope_name| {
 2256            settings
 2257                .edit_predictions_disabled_in
 2258                .iter()
 2259                .any(|s| s == scope_name)
 2260        })
 2261    }
 2262
 2263    pub fn set_use_modal_editing(&mut self, to: bool) {
 2264        self.use_modal_editing = to;
 2265    }
 2266
 2267    pub fn use_modal_editing(&self) -> bool {
 2268        self.use_modal_editing
 2269    }
 2270
 2271    fn selections_did_change(
 2272        &mut self,
 2273        local: bool,
 2274        old_cursor_position: &Anchor,
 2275        show_completions: bool,
 2276        window: &mut Window,
 2277        cx: &mut Context<Self>,
 2278    ) {
 2279        window.invalidate_character_coordinates();
 2280
 2281        // Copy selections to primary selection buffer
 2282        #[cfg(any(target_os = "linux", target_os = "freebsd"))]
 2283        if local {
 2284            let selections = self.selections.all::<usize>(cx);
 2285            let buffer_handle = self.buffer.read(cx).read(cx);
 2286
 2287            let mut text = String::new();
 2288            for (index, selection) in selections.iter().enumerate() {
 2289                let text_for_selection = buffer_handle
 2290                    .text_for_range(selection.start..selection.end)
 2291                    .collect::<String>();
 2292
 2293                text.push_str(&text_for_selection);
 2294                if index != selections.len() - 1 {
 2295                    text.push('\n');
 2296                }
 2297            }
 2298
 2299            if !text.is_empty() {
 2300                cx.write_to_primary(ClipboardItem::new_string(text));
 2301            }
 2302        }
 2303
 2304        if self.focus_handle.is_focused(window) && self.leader_peer_id.is_none() {
 2305            self.buffer.update(cx, |buffer, cx| {
 2306                buffer.set_active_selections(
 2307                    &self.selections.disjoint_anchors(),
 2308                    self.selections.line_mode,
 2309                    self.cursor_shape,
 2310                    cx,
 2311                )
 2312            });
 2313        }
 2314        let display_map = self
 2315            .display_map
 2316            .update(cx, |display_map, cx| display_map.snapshot(cx));
 2317        let buffer = &display_map.buffer_snapshot;
 2318        self.add_selections_state = None;
 2319        self.select_next_state = None;
 2320        self.select_prev_state = None;
 2321        self.select_syntax_node_history.try_clear();
 2322        self.invalidate_autoclose_regions(&self.selections.disjoint_anchors(), buffer);
 2323        self.snippet_stack
 2324            .invalidate(&self.selections.disjoint_anchors(), buffer);
 2325        self.take_rename(false, window, cx);
 2326
 2327        let new_cursor_position = self.selections.newest_anchor().head();
 2328
 2329        self.push_to_nav_history(
 2330            *old_cursor_position,
 2331            Some(new_cursor_position.to_point(buffer)),
 2332            false,
 2333            cx,
 2334        );
 2335
 2336        if local {
 2337            let new_cursor_position = self.selections.newest_anchor().head();
 2338            let mut context_menu = self.context_menu.borrow_mut();
 2339            let completion_menu = match context_menu.as_ref() {
 2340                Some(CodeContextMenu::Completions(menu)) => Some(menu),
 2341                _ => {
 2342                    *context_menu = None;
 2343                    None
 2344                }
 2345            };
 2346            if let Some(buffer_id) = new_cursor_position.buffer_id {
 2347                if !self.registered_buffers.contains_key(&buffer_id) {
 2348                    if let Some(project) = self.project.as_ref() {
 2349                        project.update(cx, |project, cx| {
 2350                            let Some(buffer) = self.buffer.read(cx).buffer(buffer_id) else {
 2351                                return;
 2352                            };
 2353                            self.registered_buffers.insert(
 2354                                buffer_id,
 2355                                project.register_buffer_with_language_servers(&buffer, cx),
 2356                            );
 2357                        })
 2358                    }
 2359                }
 2360            }
 2361
 2362            if let Some(completion_menu) = completion_menu {
 2363                let cursor_position = new_cursor_position.to_offset(buffer);
 2364                let (word_range, kind) =
 2365                    buffer.surrounding_word(completion_menu.initial_position, true);
 2366                if kind == Some(CharKind::Word)
 2367                    && word_range.to_inclusive().contains(&cursor_position)
 2368                {
 2369                    let mut completion_menu = completion_menu.clone();
 2370                    drop(context_menu);
 2371
 2372                    let query = Self::completion_query(buffer, cursor_position);
 2373                    cx.spawn(async move |this, cx| {
 2374                        completion_menu
 2375                            .filter(query.as_deref(), cx.background_executor().clone())
 2376                            .await;
 2377
 2378                        this.update(cx, |this, cx| {
 2379                            let mut context_menu = this.context_menu.borrow_mut();
 2380                            let Some(CodeContextMenu::Completions(menu)) = context_menu.as_ref()
 2381                            else {
 2382                                return;
 2383                            };
 2384
 2385                            if menu.id > completion_menu.id {
 2386                                return;
 2387                            }
 2388
 2389                            *context_menu = Some(CodeContextMenu::Completions(completion_menu));
 2390                            drop(context_menu);
 2391                            cx.notify();
 2392                        })
 2393                    })
 2394                    .detach();
 2395
 2396                    if show_completions {
 2397                        self.show_completions(&ShowCompletions { trigger: None }, window, cx);
 2398                    }
 2399                } else {
 2400                    drop(context_menu);
 2401                    self.hide_context_menu(window, cx);
 2402                }
 2403            } else {
 2404                drop(context_menu);
 2405            }
 2406
 2407            hide_hover(self, cx);
 2408
 2409            if old_cursor_position.to_display_point(&display_map).row()
 2410                != new_cursor_position.to_display_point(&display_map).row()
 2411            {
 2412                self.available_code_actions.take();
 2413            }
 2414            self.refresh_code_actions(window, cx);
 2415            self.refresh_document_highlights(cx);
 2416            self.refresh_selected_text_highlights(window, cx);
 2417            refresh_matching_bracket_highlights(self, window, cx);
 2418            self.update_visible_inline_completion(window, cx);
 2419            self.edit_prediction_requires_modifier_in_indent_conflict = true;
 2420            linked_editing_ranges::refresh_linked_ranges(self, window, cx);
 2421            if self.git_blame_inline_enabled {
 2422                self.start_inline_blame_timer(window, cx);
 2423            }
 2424        }
 2425
 2426        self.blink_manager.update(cx, BlinkManager::pause_blinking);
 2427        cx.emit(EditorEvent::SelectionsChanged { local });
 2428
 2429        let selections = &self.selections.disjoint;
 2430        if selections.len() == 1 {
 2431            cx.emit(SearchEvent::ActiveMatchChanged)
 2432        }
 2433        if local {
 2434            if let Some((_, _, buffer_snapshot)) = buffer.as_singleton() {
 2435                let inmemory_selections = selections
 2436                    .iter()
 2437                    .map(|s| {
 2438                        text::ToPoint::to_point(&s.range().start.text_anchor, buffer_snapshot)
 2439                            ..text::ToPoint::to_point(&s.range().end.text_anchor, buffer_snapshot)
 2440                    })
 2441                    .collect();
 2442                self.update_restoration_data(cx, |data| {
 2443                    data.selections = inmemory_selections;
 2444                });
 2445
 2446                if WorkspaceSettings::get(None, cx).restore_on_startup
 2447                    != RestoreOnStartupBehavior::None
 2448                {
 2449                    if let Some(workspace_id) =
 2450                        self.workspace.as_ref().and_then(|workspace| workspace.1)
 2451                    {
 2452                        let snapshot = self.buffer().read(cx).snapshot(cx);
 2453                        let selections = selections.clone();
 2454                        let background_executor = cx.background_executor().clone();
 2455                        let editor_id = cx.entity().entity_id().as_u64() as ItemId;
 2456                        self.serialize_selections = cx.background_spawn(async move {
 2457                    background_executor.timer(SERIALIZATION_THROTTLE_TIME).await;
 2458                    let db_selections = selections
 2459                        .iter()
 2460                        .map(|selection| {
 2461                            (
 2462                                selection.start.to_offset(&snapshot),
 2463                                selection.end.to_offset(&snapshot),
 2464                            )
 2465                        })
 2466                        .collect();
 2467
 2468                    DB.save_editor_selections(editor_id, workspace_id, db_selections)
 2469                        .await
 2470                        .with_context(|| format!("persisting editor selections for editor {editor_id}, workspace {workspace_id:?}"))
 2471                        .log_err();
 2472                });
 2473                    }
 2474                }
 2475            }
 2476        }
 2477
 2478        cx.notify();
 2479    }
 2480
 2481    fn folds_did_change(&mut self, cx: &mut Context<Self>) {
 2482        use text::ToOffset as _;
 2483        use text::ToPoint as _;
 2484
 2485        if WorkspaceSettings::get(None, cx).restore_on_startup == RestoreOnStartupBehavior::None {
 2486            return;
 2487        }
 2488
 2489        let Some(singleton) = self.buffer().read(cx).as_singleton() else {
 2490            return;
 2491        };
 2492
 2493        let snapshot = singleton.read(cx).snapshot();
 2494        let inmemory_folds = self.display_map.update(cx, |display_map, cx| {
 2495            let display_snapshot = display_map.snapshot(cx);
 2496
 2497            display_snapshot
 2498                .folds_in_range(0..display_snapshot.buffer_snapshot.len())
 2499                .map(|fold| {
 2500                    fold.range.start.text_anchor.to_point(&snapshot)
 2501                        ..fold.range.end.text_anchor.to_point(&snapshot)
 2502                })
 2503                .collect()
 2504        });
 2505        self.update_restoration_data(cx, |data| {
 2506            data.folds = inmemory_folds;
 2507        });
 2508
 2509        let Some(workspace_id) = self.workspace.as_ref().and_then(|workspace| workspace.1) else {
 2510            return;
 2511        };
 2512        let background_executor = cx.background_executor().clone();
 2513        let editor_id = cx.entity().entity_id().as_u64() as ItemId;
 2514        let db_folds = self.display_map.update(cx, |display_map, cx| {
 2515            display_map
 2516                .snapshot(cx)
 2517                .folds_in_range(0..snapshot.len())
 2518                .map(|fold| {
 2519                    (
 2520                        fold.range.start.text_anchor.to_offset(&snapshot),
 2521                        fold.range.end.text_anchor.to_offset(&snapshot),
 2522                    )
 2523                })
 2524                .collect()
 2525        });
 2526        self.serialize_folds = cx.background_spawn(async move {
 2527            background_executor.timer(SERIALIZATION_THROTTLE_TIME).await;
 2528            DB.save_editor_folds(editor_id, workspace_id, db_folds)
 2529                .await
 2530                .with_context(|| {
 2531                    format!(
 2532                        "persisting editor folds for editor {editor_id}, workspace {workspace_id:?}"
 2533                    )
 2534                })
 2535                .log_err();
 2536        });
 2537    }
 2538
 2539    pub fn sync_selections(
 2540        &mut self,
 2541        other: Entity<Editor>,
 2542        cx: &mut Context<Self>,
 2543    ) -> gpui::Subscription {
 2544        let other_selections = other.read(cx).selections.disjoint.to_vec();
 2545        self.selections.change_with(cx, |selections| {
 2546            selections.select_anchors(other_selections);
 2547        });
 2548
 2549        let other_subscription =
 2550            cx.subscribe(&other, |this, other, other_evt, cx| match other_evt {
 2551                EditorEvent::SelectionsChanged { local: true } => {
 2552                    let other_selections = other.read(cx).selections.disjoint.to_vec();
 2553                    if other_selections.is_empty() {
 2554                        return;
 2555                    }
 2556                    this.selections.change_with(cx, |selections| {
 2557                        selections.select_anchors(other_selections);
 2558                    });
 2559                }
 2560                _ => {}
 2561            });
 2562
 2563        let this_subscription =
 2564            cx.subscribe_self::<EditorEvent>(move |this, this_evt, cx| match this_evt {
 2565                EditorEvent::SelectionsChanged { local: true } => {
 2566                    let these_selections = this.selections.disjoint.to_vec();
 2567                    if these_selections.is_empty() {
 2568                        return;
 2569                    }
 2570                    other.update(cx, |other_editor, cx| {
 2571                        other_editor.selections.change_with(cx, |selections| {
 2572                            selections.select_anchors(these_selections);
 2573                        })
 2574                    });
 2575                }
 2576                _ => {}
 2577            });
 2578
 2579        Subscription::join(other_subscription, this_subscription)
 2580    }
 2581
 2582    pub fn change_selections<R>(
 2583        &mut self,
 2584        autoscroll: Option<Autoscroll>,
 2585        window: &mut Window,
 2586        cx: &mut Context<Self>,
 2587        change: impl FnOnce(&mut MutableSelectionsCollection<'_>) -> R,
 2588    ) -> R {
 2589        self.change_selections_inner(autoscroll, true, window, cx, change)
 2590    }
 2591
 2592    fn change_selections_inner<R>(
 2593        &mut self,
 2594        autoscroll: Option<Autoscroll>,
 2595        request_completions: bool,
 2596        window: &mut Window,
 2597        cx: &mut Context<Self>,
 2598        change: impl FnOnce(&mut MutableSelectionsCollection<'_>) -> R,
 2599    ) -> R {
 2600        let old_cursor_position = self.selections.newest_anchor().head();
 2601        self.push_to_selection_history();
 2602
 2603        let (changed, result) = self.selections.change_with(cx, change);
 2604
 2605        if changed {
 2606            if let Some(autoscroll) = autoscroll {
 2607                self.request_autoscroll(autoscroll, cx);
 2608            }
 2609            self.selections_did_change(true, &old_cursor_position, request_completions, window, cx);
 2610
 2611            if self.should_open_signature_help_automatically(
 2612                &old_cursor_position,
 2613                self.signature_help_state.backspace_pressed(),
 2614                cx,
 2615            ) {
 2616                self.show_signature_help(&ShowSignatureHelp, window, cx);
 2617            }
 2618            self.signature_help_state.set_backspace_pressed(false);
 2619        }
 2620
 2621        result
 2622    }
 2623
 2624    pub fn edit<I, S, T>(&mut self, edits: I, cx: &mut Context<Self>)
 2625    where
 2626        I: IntoIterator<Item = (Range<S>, T)>,
 2627        S: ToOffset,
 2628        T: Into<Arc<str>>,
 2629    {
 2630        if self.read_only(cx) {
 2631            return;
 2632        }
 2633
 2634        self.buffer
 2635            .update(cx, |buffer, cx| buffer.edit(edits, None, cx));
 2636    }
 2637
 2638    pub fn edit_with_autoindent<I, S, T>(&mut self, edits: I, cx: &mut Context<Self>)
 2639    where
 2640        I: IntoIterator<Item = (Range<S>, T)>,
 2641        S: ToOffset,
 2642        T: Into<Arc<str>>,
 2643    {
 2644        if self.read_only(cx) {
 2645            return;
 2646        }
 2647
 2648        self.buffer.update(cx, |buffer, cx| {
 2649            buffer.edit(edits, self.autoindent_mode.clone(), cx)
 2650        });
 2651    }
 2652
 2653    pub fn edit_with_block_indent<I, S, T>(
 2654        &mut self,
 2655        edits: I,
 2656        original_indent_columns: Vec<Option<u32>>,
 2657        cx: &mut Context<Self>,
 2658    ) where
 2659        I: IntoIterator<Item = (Range<S>, T)>,
 2660        S: ToOffset,
 2661        T: Into<Arc<str>>,
 2662    {
 2663        if self.read_only(cx) {
 2664            return;
 2665        }
 2666
 2667        self.buffer.update(cx, |buffer, cx| {
 2668            buffer.edit(
 2669                edits,
 2670                Some(AutoindentMode::Block {
 2671                    original_indent_columns,
 2672                }),
 2673                cx,
 2674            )
 2675        });
 2676    }
 2677
 2678    fn select(&mut self, phase: SelectPhase, window: &mut Window, cx: &mut Context<Self>) {
 2679        self.hide_context_menu(window, cx);
 2680
 2681        match phase {
 2682            SelectPhase::Begin {
 2683                position,
 2684                add,
 2685                click_count,
 2686            } => self.begin_selection(position, add, click_count, window, cx),
 2687            SelectPhase::BeginColumnar {
 2688                position,
 2689                goal_column,
 2690                reset,
 2691            } => self.begin_columnar_selection(position, goal_column, reset, window, cx),
 2692            SelectPhase::Extend {
 2693                position,
 2694                click_count,
 2695            } => self.extend_selection(position, click_count, window, cx),
 2696            SelectPhase::Update {
 2697                position,
 2698                goal_column,
 2699                scroll_delta,
 2700            } => self.update_selection(position, goal_column, scroll_delta, window, cx),
 2701            SelectPhase::End => self.end_selection(window, cx),
 2702        }
 2703    }
 2704
 2705    fn extend_selection(
 2706        &mut self,
 2707        position: DisplayPoint,
 2708        click_count: usize,
 2709        window: &mut Window,
 2710        cx: &mut Context<Self>,
 2711    ) {
 2712        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 2713        let tail = self.selections.newest::<usize>(cx).tail();
 2714        self.begin_selection(position, false, click_count, window, cx);
 2715
 2716        let position = position.to_offset(&display_map, Bias::Left);
 2717        let tail_anchor = display_map.buffer_snapshot.anchor_before(tail);
 2718
 2719        let mut pending_selection = self
 2720            .selections
 2721            .pending_anchor()
 2722            .expect("extend_selection not called with pending selection");
 2723        if position >= tail {
 2724            pending_selection.start = tail_anchor;
 2725        } else {
 2726            pending_selection.end = tail_anchor;
 2727            pending_selection.reversed = true;
 2728        }
 2729
 2730        let mut pending_mode = self.selections.pending_mode().unwrap();
 2731        match &mut pending_mode {
 2732            SelectMode::Word(range) | SelectMode::Line(range) => *range = tail_anchor..tail_anchor,
 2733            _ => {}
 2734        }
 2735
 2736        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 2737            s.set_pending(pending_selection, pending_mode)
 2738        });
 2739    }
 2740
 2741    fn begin_selection(
 2742        &mut self,
 2743        position: DisplayPoint,
 2744        add: bool,
 2745        click_count: usize,
 2746        window: &mut Window,
 2747        cx: &mut Context<Self>,
 2748    ) {
 2749        if !self.focus_handle.is_focused(window) {
 2750            self.last_focused_descendant = None;
 2751            window.focus(&self.focus_handle);
 2752        }
 2753
 2754        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 2755        let buffer = &display_map.buffer_snapshot;
 2756        let newest_selection = self.selections.newest_anchor().clone();
 2757        let position = display_map.clip_point(position, Bias::Left);
 2758
 2759        let start;
 2760        let end;
 2761        let mode;
 2762        let mut auto_scroll;
 2763        match click_count {
 2764            1 => {
 2765                start = buffer.anchor_before(position.to_point(&display_map));
 2766                end = start;
 2767                mode = SelectMode::Character;
 2768                auto_scroll = true;
 2769            }
 2770            2 => {
 2771                let range = movement::surrounding_word(&display_map, position);
 2772                start = buffer.anchor_before(range.start.to_point(&display_map));
 2773                end = buffer.anchor_before(range.end.to_point(&display_map));
 2774                mode = SelectMode::Word(start..end);
 2775                auto_scroll = true;
 2776            }
 2777            3 => {
 2778                let position = display_map
 2779                    .clip_point(position, Bias::Left)
 2780                    .to_point(&display_map);
 2781                let line_start = display_map.prev_line_boundary(position).0;
 2782                let next_line_start = buffer.clip_point(
 2783                    display_map.next_line_boundary(position).0 + Point::new(1, 0),
 2784                    Bias::Left,
 2785                );
 2786                start = buffer.anchor_before(line_start);
 2787                end = buffer.anchor_before(next_line_start);
 2788                mode = SelectMode::Line(start..end);
 2789                auto_scroll = true;
 2790            }
 2791            _ => {
 2792                start = buffer.anchor_before(0);
 2793                end = buffer.anchor_before(buffer.len());
 2794                mode = SelectMode::All;
 2795                auto_scroll = false;
 2796            }
 2797        }
 2798        auto_scroll &= EditorSettings::get_global(cx).autoscroll_on_clicks;
 2799
 2800        let point_to_delete: Option<usize> = {
 2801            let selected_points: Vec<Selection<Point>> =
 2802                self.selections.disjoint_in_range(start..end, cx);
 2803
 2804            if !add || click_count > 1 {
 2805                None
 2806            } else if !selected_points.is_empty() {
 2807                Some(selected_points[0].id)
 2808            } else {
 2809                let clicked_point_already_selected =
 2810                    self.selections.disjoint.iter().find(|selection| {
 2811                        selection.start.to_point(buffer) == start.to_point(buffer)
 2812                            || selection.end.to_point(buffer) == end.to_point(buffer)
 2813                    });
 2814
 2815                clicked_point_already_selected.map(|selection| selection.id)
 2816            }
 2817        };
 2818
 2819        let selections_count = self.selections.count();
 2820
 2821        self.change_selections(auto_scroll.then(Autoscroll::newest), window, cx, |s| {
 2822            if let Some(point_to_delete) = point_to_delete {
 2823                s.delete(point_to_delete);
 2824
 2825                if selections_count == 1 {
 2826                    s.set_pending_anchor_range(start..end, mode);
 2827                }
 2828            } else {
 2829                if !add {
 2830                    s.clear_disjoint();
 2831                } else if click_count > 1 {
 2832                    s.delete(newest_selection.id)
 2833                }
 2834
 2835                s.set_pending_anchor_range(start..end, mode);
 2836            }
 2837        });
 2838    }
 2839
 2840    fn begin_columnar_selection(
 2841        &mut self,
 2842        position: DisplayPoint,
 2843        goal_column: u32,
 2844        reset: bool,
 2845        window: &mut Window,
 2846        cx: &mut Context<Self>,
 2847    ) {
 2848        if !self.focus_handle.is_focused(window) {
 2849            self.last_focused_descendant = None;
 2850            window.focus(&self.focus_handle);
 2851        }
 2852
 2853        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 2854
 2855        if reset {
 2856            let pointer_position = display_map
 2857                .buffer_snapshot
 2858                .anchor_before(position.to_point(&display_map));
 2859
 2860            self.change_selections(Some(Autoscroll::newest()), window, cx, |s| {
 2861                s.clear_disjoint();
 2862                s.set_pending_anchor_range(
 2863                    pointer_position..pointer_position,
 2864                    SelectMode::Character,
 2865                );
 2866            });
 2867        }
 2868
 2869        let tail = self.selections.newest::<Point>(cx).tail();
 2870        self.columnar_selection_tail = Some(display_map.buffer_snapshot.anchor_before(tail));
 2871
 2872        if !reset {
 2873            self.select_columns(
 2874                tail.to_display_point(&display_map),
 2875                position,
 2876                goal_column,
 2877                &display_map,
 2878                window,
 2879                cx,
 2880            );
 2881        }
 2882    }
 2883
 2884    fn update_selection(
 2885        &mut self,
 2886        position: DisplayPoint,
 2887        goal_column: u32,
 2888        scroll_delta: gpui::Point<f32>,
 2889        window: &mut Window,
 2890        cx: &mut Context<Self>,
 2891    ) {
 2892        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 2893
 2894        if let Some(tail) = self.columnar_selection_tail.as_ref() {
 2895            let tail = tail.to_display_point(&display_map);
 2896            self.select_columns(tail, position, goal_column, &display_map, window, cx);
 2897        } else if let Some(mut pending) = self.selections.pending_anchor() {
 2898            let buffer = self.buffer.read(cx).snapshot(cx);
 2899            let head;
 2900            let tail;
 2901            let mode = self.selections.pending_mode().unwrap();
 2902            match &mode {
 2903                SelectMode::Character => {
 2904                    head = position.to_point(&display_map);
 2905                    tail = pending.tail().to_point(&buffer);
 2906                }
 2907                SelectMode::Word(original_range) => {
 2908                    let original_display_range = original_range.start.to_display_point(&display_map)
 2909                        ..original_range.end.to_display_point(&display_map);
 2910                    let original_buffer_range = original_display_range.start.to_point(&display_map)
 2911                        ..original_display_range.end.to_point(&display_map);
 2912                    if movement::is_inside_word(&display_map, position)
 2913                        || original_display_range.contains(&position)
 2914                    {
 2915                        let word_range = movement::surrounding_word(&display_map, position);
 2916                        if word_range.start < original_display_range.start {
 2917                            head = word_range.start.to_point(&display_map);
 2918                        } else {
 2919                            head = word_range.end.to_point(&display_map);
 2920                        }
 2921                    } else {
 2922                        head = position.to_point(&display_map);
 2923                    }
 2924
 2925                    if head <= original_buffer_range.start {
 2926                        tail = original_buffer_range.end;
 2927                    } else {
 2928                        tail = original_buffer_range.start;
 2929                    }
 2930                }
 2931                SelectMode::Line(original_range) => {
 2932                    let original_range = original_range.to_point(&display_map.buffer_snapshot);
 2933
 2934                    let position = display_map
 2935                        .clip_point(position, Bias::Left)
 2936                        .to_point(&display_map);
 2937                    let line_start = display_map.prev_line_boundary(position).0;
 2938                    let next_line_start = buffer.clip_point(
 2939                        display_map.next_line_boundary(position).0 + Point::new(1, 0),
 2940                        Bias::Left,
 2941                    );
 2942
 2943                    if line_start < original_range.start {
 2944                        head = line_start
 2945                    } else {
 2946                        head = next_line_start
 2947                    }
 2948
 2949                    if head <= original_range.start {
 2950                        tail = original_range.end;
 2951                    } else {
 2952                        tail = original_range.start;
 2953                    }
 2954                }
 2955                SelectMode::All => {
 2956                    return;
 2957                }
 2958            };
 2959
 2960            if head < tail {
 2961                pending.start = buffer.anchor_before(head);
 2962                pending.end = buffer.anchor_before(tail);
 2963                pending.reversed = true;
 2964            } else {
 2965                pending.start = buffer.anchor_before(tail);
 2966                pending.end = buffer.anchor_before(head);
 2967                pending.reversed = false;
 2968            }
 2969
 2970            self.change_selections(None, window, cx, |s| {
 2971                s.set_pending(pending, mode);
 2972            });
 2973        } else {
 2974            log::error!("update_selection dispatched with no pending selection");
 2975            return;
 2976        }
 2977
 2978        self.apply_scroll_delta(scroll_delta, window, cx);
 2979        cx.notify();
 2980    }
 2981
 2982    fn end_selection(&mut self, window: &mut Window, cx: &mut Context<Self>) {
 2983        self.columnar_selection_tail.take();
 2984        if self.selections.pending_anchor().is_some() {
 2985            let selections = self.selections.all::<usize>(cx);
 2986            self.change_selections(None, window, cx, |s| {
 2987                s.select(selections);
 2988                s.clear_pending();
 2989            });
 2990        }
 2991    }
 2992
 2993    fn select_columns(
 2994        &mut self,
 2995        tail: DisplayPoint,
 2996        head: DisplayPoint,
 2997        goal_column: u32,
 2998        display_map: &DisplaySnapshot,
 2999        window: &mut Window,
 3000        cx: &mut Context<Self>,
 3001    ) {
 3002        let start_row = cmp::min(tail.row(), head.row());
 3003        let end_row = cmp::max(tail.row(), head.row());
 3004        let start_column = cmp::min(tail.column(), goal_column);
 3005        let end_column = cmp::max(tail.column(), goal_column);
 3006        let reversed = start_column < tail.column();
 3007
 3008        let selection_ranges = (start_row.0..=end_row.0)
 3009            .map(DisplayRow)
 3010            .filter_map(|row| {
 3011                if start_column <= display_map.line_len(row) && !display_map.is_block_line(row) {
 3012                    let start = display_map
 3013                        .clip_point(DisplayPoint::new(row, start_column), Bias::Left)
 3014                        .to_point(display_map);
 3015                    let end = display_map
 3016                        .clip_point(DisplayPoint::new(row, end_column), Bias::Right)
 3017                        .to_point(display_map);
 3018                    if reversed {
 3019                        Some(end..start)
 3020                    } else {
 3021                        Some(start..end)
 3022                    }
 3023                } else {
 3024                    None
 3025                }
 3026            })
 3027            .collect::<Vec<_>>();
 3028
 3029        self.change_selections(None, window, cx, |s| {
 3030            s.select_ranges(selection_ranges);
 3031        });
 3032        cx.notify();
 3033    }
 3034
 3035    pub fn has_pending_nonempty_selection(&self) -> bool {
 3036        let pending_nonempty_selection = match self.selections.pending_anchor() {
 3037            Some(Selection { start, end, .. }) => start != end,
 3038            None => false,
 3039        };
 3040
 3041        pending_nonempty_selection
 3042            || (self.columnar_selection_tail.is_some() && self.selections.disjoint.len() > 1)
 3043    }
 3044
 3045    pub fn has_pending_selection(&self) -> bool {
 3046        self.selections.pending_anchor().is_some() || self.columnar_selection_tail.is_some()
 3047    }
 3048
 3049    pub fn cancel(&mut self, _: &Cancel, window: &mut Window, cx: &mut Context<Self>) {
 3050        self.selection_mark_mode = false;
 3051
 3052        if self.clear_expanded_diff_hunks(cx) {
 3053            cx.notify();
 3054            return;
 3055        }
 3056        if self.dismiss_menus_and_popups(true, window, cx) {
 3057            return;
 3058        }
 3059
 3060        if self.mode.is_full()
 3061            && self.change_selections(Some(Autoscroll::fit()), window, cx, |s| s.try_cancel())
 3062        {
 3063            return;
 3064        }
 3065
 3066        cx.propagate();
 3067    }
 3068
 3069    pub fn dismiss_menus_and_popups(
 3070        &mut self,
 3071        is_user_requested: bool,
 3072        window: &mut Window,
 3073        cx: &mut Context<Self>,
 3074    ) -> bool {
 3075        if self.take_rename(false, window, cx).is_some() {
 3076            return true;
 3077        }
 3078
 3079        if hide_hover(self, cx) {
 3080            return true;
 3081        }
 3082
 3083        if self.hide_signature_help(cx, SignatureHelpHiddenBy::Escape) {
 3084            return true;
 3085        }
 3086
 3087        if self.hide_context_menu(window, cx).is_some() {
 3088            return true;
 3089        }
 3090
 3091        if self.mouse_context_menu.take().is_some() {
 3092            return true;
 3093        }
 3094
 3095        if is_user_requested && self.discard_inline_completion(true, cx) {
 3096            return true;
 3097        }
 3098
 3099        if self.snippet_stack.pop().is_some() {
 3100            return true;
 3101        }
 3102
 3103        if self.mode.is_full() && matches!(self.active_diagnostics, ActiveDiagnostic::Group(_)) {
 3104            self.dismiss_diagnostics(cx);
 3105            return true;
 3106        }
 3107
 3108        false
 3109    }
 3110
 3111    fn linked_editing_ranges_for(
 3112        &self,
 3113        selection: Range<text::Anchor>,
 3114        cx: &App,
 3115    ) -> Option<HashMap<Entity<Buffer>, Vec<Range<text::Anchor>>>> {
 3116        if self.linked_edit_ranges.is_empty() {
 3117            return None;
 3118        }
 3119        let ((base_range, linked_ranges), buffer_snapshot, buffer) =
 3120            selection.end.buffer_id.and_then(|end_buffer_id| {
 3121                if selection.start.buffer_id != Some(end_buffer_id) {
 3122                    return None;
 3123                }
 3124                let buffer = self.buffer.read(cx).buffer(end_buffer_id)?;
 3125                let snapshot = buffer.read(cx).snapshot();
 3126                self.linked_edit_ranges
 3127                    .get(end_buffer_id, selection.start..selection.end, &snapshot)
 3128                    .map(|ranges| (ranges, snapshot, buffer))
 3129            })?;
 3130        use text::ToOffset as TO;
 3131        // find offset from the start of current range to current cursor position
 3132        let start_byte_offset = TO::to_offset(&base_range.start, &buffer_snapshot);
 3133
 3134        let start_offset = TO::to_offset(&selection.start, &buffer_snapshot);
 3135        let start_difference = start_offset - start_byte_offset;
 3136        let end_offset = TO::to_offset(&selection.end, &buffer_snapshot);
 3137        let end_difference = end_offset - start_byte_offset;
 3138        // Current range has associated linked ranges.
 3139        let mut linked_edits = HashMap::<_, Vec<_>>::default();
 3140        for range in linked_ranges.iter() {
 3141            let start_offset = TO::to_offset(&range.start, &buffer_snapshot);
 3142            let end_offset = start_offset + end_difference;
 3143            let start_offset = start_offset + start_difference;
 3144            if start_offset > buffer_snapshot.len() || end_offset > buffer_snapshot.len() {
 3145                continue;
 3146            }
 3147            if self.selections.disjoint_anchor_ranges().any(|s| {
 3148                if s.start.buffer_id != selection.start.buffer_id
 3149                    || s.end.buffer_id != selection.end.buffer_id
 3150                {
 3151                    return false;
 3152                }
 3153                TO::to_offset(&s.start.text_anchor, &buffer_snapshot) <= end_offset
 3154                    && TO::to_offset(&s.end.text_anchor, &buffer_snapshot) >= start_offset
 3155            }) {
 3156                continue;
 3157            }
 3158            let start = buffer_snapshot.anchor_after(start_offset);
 3159            let end = buffer_snapshot.anchor_after(end_offset);
 3160            linked_edits
 3161                .entry(buffer.clone())
 3162                .or_default()
 3163                .push(start..end);
 3164        }
 3165        Some(linked_edits)
 3166    }
 3167
 3168    pub fn handle_input(&mut self, text: &str, window: &mut Window, cx: &mut Context<Self>) {
 3169        let text: Arc<str> = text.into();
 3170
 3171        if self.read_only(cx) {
 3172            return;
 3173        }
 3174
 3175        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
 3176
 3177        let selections = self.selections.all_adjusted(cx);
 3178        let mut bracket_inserted = false;
 3179        let mut edits = Vec::new();
 3180        let mut linked_edits = HashMap::<_, Vec<_>>::default();
 3181        let mut new_selections = Vec::with_capacity(selections.len());
 3182        let mut new_autoclose_regions = Vec::new();
 3183        let snapshot = self.buffer.read(cx).read(cx);
 3184        let mut clear_linked_edit_ranges = false;
 3185
 3186        for (selection, autoclose_region) in
 3187            self.selections_with_autoclose_regions(selections, &snapshot)
 3188        {
 3189            if let Some(scope) = snapshot.language_scope_at(selection.head()) {
 3190                // Determine if the inserted text matches the opening or closing
 3191                // bracket of any of this language's bracket pairs.
 3192                let mut bracket_pair = None;
 3193                let mut is_bracket_pair_start = false;
 3194                let mut is_bracket_pair_end = false;
 3195                if !text.is_empty() {
 3196                    let mut bracket_pair_matching_end = None;
 3197                    // `text` can be empty when a user is using IME (e.g. Chinese Wubi Simplified)
 3198                    //  and they are removing the character that triggered IME popup.
 3199                    for (pair, enabled) in scope.brackets() {
 3200                        if !pair.close && !pair.surround {
 3201                            continue;
 3202                        }
 3203
 3204                        if enabled && pair.start.ends_with(text.as_ref()) {
 3205                            let prefix_len = pair.start.len() - text.len();
 3206                            let preceding_text_matches_prefix = prefix_len == 0
 3207                                || (selection.start.column >= (prefix_len as u32)
 3208                                    && snapshot.contains_str_at(
 3209                                        Point::new(
 3210                                            selection.start.row,
 3211                                            selection.start.column - (prefix_len as u32),
 3212                                        ),
 3213                                        &pair.start[..prefix_len],
 3214                                    ));
 3215                            if preceding_text_matches_prefix {
 3216                                bracket_pair = Some(pair.clone());
 3217                                is_bracket_pair_start = true;
 3218                                break;
 3219                            }
 3220                        }
 3221                        if pair.end.as_str() == text.as_ref() && bracket_pair_matching_end.is_none()
 3222                        {
 3223                            // take first bracket pair matching end, but don't break in case a later bracket
 3224                            // pair matches start
 3225                            bracket_pair_matching_end = Some(pair.clone());
 3226                        }
 3227                    }
 3228                    if bracket_pair.is_none() && bracket_pair_matching_end.is_some() {
 3229                        bracket_pair = Some(bracket_pair_matching_end.unwrap());
 3230                        is_bracket_pair_end = true;
 3231                    }
 3232                }
 3233
 3234                if let Some(bracket_pair) = bracket_pair {
 3235                    let snapshot_settings = snapshot.language_settings_at(selection.start, cx);
 3236                    let autoclose = self.use_autoclose && snapshot_settings.use_autoclose;
 3237                    let auto_surround =
 3238                        self.use_auto_surround && snapshot_settings.use_auto_surround;
 3239                    if selection.is_empty() {
 3240                        if is_bracket_pair_start {
 3241                            // If the inserted text is a suffix of an opening bracket and the
 3242                            // selection is preceded by the rest of the opening bracket, then
 3243                            // insert the closing bracket.
 3244                            let following_text_allows_autoclose = snapshot
 3245                                .chars_at(selection.start)
 3246                                .next()
 3247                                .map_or(true, |c| scope.should_autoclose_before(c));
 3248
 3249                            let preceding_text_allows_autoclose = selection.start.column == 0
 3250                                || snapshot.reversed_chars_at(selection.start).next().map_or(
 3251                                    true,
 3252                                    |c| {
 3253                                        bracket_pair.start != bracket_pair.end
 3254                                            || !snapshot
 3255                                                .char_classifier_at(selection.start)
 3256                                                .is_word(c)
 3257                                    },
 3258                                );
 3259
 3260                            let is_closing_quote = if bracket_pair.end == bracket_pair.start
 3261                                && bracket_pair.start.len() == 1
 3262                            {
 3263                                let target = bracket_pair.start.chars().next().unwrap();
 3264                                let current_line_count = snapshot
 3265                                    .reversed_chars_at(selection.start)
 3266                                    .take_while(|&c| c != '\n')
 3267                                    .filter(|&c| c == target)
 3268                                    .count();
 3269                                current_line_count % 2 == 1
 3270                            } else {
 3271                                false
 3272                            };
 3273
 3274                            if autoclose
 3275                                && bracket_pair.close
 3276                                && following_text_allows_autoclose
 3277                                && preceding_text_allows_autoclose
 3278                                && !is_closing_quote
 3279                            {
 3280                                let anchor = snapshot.anchor_before(selection.end);
 3281                                new_selections.push((selection.map(|_| anchor), text.len()));
 3282                                new_autoclose_regions.push((
 3283                                    anchor,
 3284                                    text.len(),
 3285                                    selection.id,
 3286                                    bracket_pair.clone(),
 3287                                ));
 3288                                edits.push((
 3289                                    selection.range(),
 3290                                    format!("{}{}", text, bracket_pair.end).into(),
 3291                                ));
 3292                                bracket_inserted = true;
 3293                                continue;
 3294                            }
 3295                        }
 3296
 3297                        if let Some(region) = autoclose_region {
 3298                            // If the selection is followed by an auto-inserted closing bracket,
 3299                            // then don't insert that closing bracket again; just move the selection
 3300                            // past the closing bracket.
 3301                            let should_skip = selection.end == region.range.end.to_point(&snapshot)
 3302                                && text.as_ref() == region.pair.end.as_str();
 3303                            if should_skip {
 3304                                let anchor = snapshot.anchor_after(selection.end);
 3305                                new_selections
 3306                                    .push((selection.map(|_| anchor), region.pair.end.len()));
 3307                                continue;
 3308                            }
 3309                        }
 3310
 3311                        let always_treat_brackets_as_autoclosed = snapshot
 3312                            .language_settings_at(selection.start, cx)
 3313                            .always_treat_brackets_as_autoclosed;
 3314                        if always_treat_brackets_as_autoclosed
 3315                            && is_bracket_pair_end
 3316                            && snapshot.contains_str_at(selection.end, text.as_ref())
 3317                        {
 3318                            // Otherwise, when `always_treat_brackets_as_autoclosed` is set to `true
 3319                            // and the inserted text is a closing bracket and the selection is followed
 3320                            // by the closing bracket then move the selection past the closing bracket.
 3321                            let anchor = snapshot.anchor_after(selection.end);
 3322                            new_selections.push((selection.map(|_| anchor), text.len()));
 3323                            continue;
 3324                        }
 3325                    }
 3326                    // If an opening bracket is 1 character long and is typed while
 3327                    // text is selected, then surround that text with the bracket pair.
 3328                    else if auto_surround
 3329                        && bracket_pair.surround
 3330                        && is_bracket_pair_start
 3331                        && bracket_pair.start.chars().count() == 1
 3332                    {
 3333                        edits.push((selection.start..selection.start, text.clone()));
 3334                        edits.push((
 3335                            selection.end..selection.end,
 3336                            bracket_pair.end.as_str().into(),
 3337                        ));
 3338                        bracket_inserted = true;
 3339                        new_selections.push((
 3340                            Selection {
 3341                                id: selection.id,
 3342                                start: snapshot.anchor_after(selection.start),
 3343                                end: snapshot.anchor_before(selection.end),
 3344                                reversed: selection.reversed,
 3345                                goal: selection.goal,
 3346                            },
 3347                            0,
 3348                        ));
 3349                        continue;
 3350                    }
 3351                }
 3352            }
 3353
 3354            if self.auto_replace_emoji_shortcode
 3355                && selection.is_empty()
 3356                && text.as_ref().ends_with(':')
 3357            {
 3358                if let Some(possible_emoji_short_code) =
 3359                    Self::find_possible_emoji_shortcode_at_position(&snapshot, selection.start)
 3360                {
 3361                    if !possible_emoji_short_code.is_empty() {
 3362                        if let Some(emoji) = emojis::get_by_shortcode(&possible_emoji_short_code) {
 3363                            let emoji_shortcode_start = Point::new(
 3364                                selection.start.row,
 3365                                selection.start.column - possible_emoji_short_code.len() as u32 - 1,
 3366                            );
 3367
 3368                            // Remove shortcode from buffer
 3369                            edits.push((
 3370                                emoji_shortcode_start..selection.start,
 3371                                "".to_string().into(),
 3372                            ));
 3373                            new_selections.push((
 3374                                Selection {
 3375                                    id: selection.id,
 3376                                    start: snapshot.anchor_after(emoji_shortcode_start),
 3377                                    end: snapshot.anchor_before(selection.start),
 3378                                    reversed: selection.reversed,
 3379                                    goal: selection.goal,
 3380                                },
 3381                                0,
 3382                            ));
 3383
 3384                            // Insert emoji
 3385                            let selection_start_anchor = snapshot.anchor_after(selection.start);
 3386                            new_selections.push((selection.map(|_| selection_start_anchor), 0));
 3387                            edits.push((selection.start..selection.end, emoji.to_string().into()));
 3388
 3389                            continue;
 3390                        }
 3391                    }
 3392                }
 3393            }
 3394
 3395            // If not handling any auto-close operation, then just replace the selected
 3396            // text with the given input and move the selection to the end of the
 3397            // newly inserted text.
 3398            let anchor = snapshot.anchor_after(selection.end);
 3399            if !self.linked_edit_ranges.is_empty() {
 3400                let start_anchor = snapshot.anchor_before(selection.start);
 3401
 3402                let is_word_char = text.chars().next().map_or(true, |char| {
 3403                    let classifier = snapshot.char_classifier_at(start_anchor.to_offset(&snapshot));
 3404                    classifier.is_word(char)
 3405                });
 3406
 3407                if is_word_char {
 3408                    if let Some(ranges) = self
 3409                        .linked_editing_ranges_for(start_anchor.text_anchor..anchor.text_anchor, cx)
 3410                    {
 3411                        for (buffer, edits) in ranges {
 3412                            linked_edits
 3413                                .entry(buffer.clone())
 3414                                .or_default()
 3415                                .extend(edits.into_iter().map(|range| (range, text.clone())));
 3416                        }
 3417                    }
 3418                } else {
 3419                    clear_linked_edit_ranges = true;
 3420                }
 3421            }
 3422
 3423            new_selections.push((selection.map(|_| anchor), 0));
 3424            edits.push((selection.start..selection.end, text.clone()));
 3425        }
 3426
 3427        drop(snapshot);
 3428
 3429        self.transact(window, cx, |this, window, cx| {
 3430            if clear_linked_edit_ranges {
 3431                this.linked_edit_ranges.clear();
 3432            }
 3433            let initial_buffer_versions =
 3434                jsx_tag_auto_close::construct_initial_buffer_versions_map(this, &edits, cx);
 3435
 3436            this.buffer.update(cx, |buffer, cx| {
 3437                buffer.edit(edits, this.autoindent_mode.clone(), cx);
 3438            });
 3439            for (buffer, edits) in linked_edits {
 3440                buffer.update(cx, |buffer, cx| {
 3441                    let snapshot = buffer.snapshot();
 3442                    let edits = edits
 3443                        .into_iter()
 3444                        .map(|(range, text)| {
 3445                            use text::ToPoint as TP;
 3446                            let end_point = TP::to_point(&range.end, &snapshot);
 3447                            let start_point = TP::to_point(&range.start, &snapshot);
 3448                            (start_point..end_point, text)
 3449                        })
 3450                        .sorted_by_key(|(range, _)| range.start);
 3451                    buffer.edit(edits, None, cx);
 3452                })
 3453            }
 3454            let new_anchor_selections = new_selections.iter().map(|e| &e.0);
 3455            let new_selection_deltas = new_selections.iter().map(|e| e.1);
 3456            let map = this.display_map.update(cx, |map, cx| map.snapshot(cx));
 3457            let new_selections = resolve_selections::<usize, _>(new_anchor_selections, &map)
 3458                .zip(new_selection_deltas)
 3459                .map(|(selection, delta)| Selection {
 3460                    id: selection.id,
 3461                    start: selection.start + delta,
 3462                    end: selection.end + delta,
 3463                    reversed: selection.reversed,
 3464                    goal: SelectionGoal::None,
 3465                })
 3466                .collect::<Vec<_>>();
 3467
 3468            let mut i = 0;
 3469            for (position, delta, selection_id, pair) in new_autoclose_regions {
 3470                let position = position.to_offset(&map.buffer_snapshot) + delta;
 3471                let start = map.buffer_snapshot.anchor_before(position);
 3472                let end = map.buffer_snapshot.anchor_after(position);
 3473                while let Some(existing_state) = this.autoclose_regions.get(i) {
 3474                    match existing_state.range.start.cmp(&start, &map.buffer_snapshot) {
 3475                        Ordering::Less => i += 1,
 3476                        Ordering::Greater => break,
 3477                        Ordering::Equal => {
 3478                            match end.cmp(&existing_state.range.end, &map.buffer_snapshot) {
 3479                                Ordering::Less => i += 1,
 3480                                Ordering::Equal => break,
 3481                                Ordering::Greater => break,
 3482                            }
 3483                        }
 3484                    }
 3485                }
 3486                this.autoclose_regions.insert(
 3487                    i,
 3488                    AutocloseRegion {
 3489                        selection_id,
 3490                        range: start..end,
 3491                        pair,
 3492                    },
 3493                );
 3494            }
 3495
 3496            let had_active_inline_completion = this.has_active_inline_completion();
 3497            this.change_selections_inner(Some(Autoscroll::fit()), false, window, cx, |s| {
 3498                s.select(new_selections)
 3499            });
 3500
 3501            if !bracket_inserted {
 3502                if let Some(on_type_format_task) =
 3503                    this.trigger_on_type_formatting(text.to_string(), window, cx)
 3504                {
 3505                    on_type_format_task.detach_and_log_err(cx);
 3506                }
 3507            }
 3508
 3509            let editor_settings = EditorSettings::get_global(cx);
 3510            if bracket_inserted
 3511                && (editor_settings.auto_signature_help
 3512                    || editor_settings.show_signature_help_after_edits)
 3513            {
 3514                this.show_signature_help(&ShowSignatureHelp, window, cx);
 3515            }
 3516
 3517            let trigger_in_words =
 3518                this.show_edit_predictions_in_menu() || !had_active_inline_completion;
 3519            if this.hard_wrap.is_some() {
 3520                let latest: Range<Point> = this.selections.newest(cx).range();
 3521                if latest.is_empty()
 3522                    && this
 3523                        .buffer()
 3524                        .read(cx)
 3525                        .snapshot(cx)
 3526                        .line_len(MultiBufferRow(latest.start.row))
 3527                        == latest.start.column
 3528                {
 3529                    this.rewrap_impl(
 3530                        RewrapOptions {
 3531                            override_language_settings: true,
 3532                            preserve_existing_whitespace: true,
 3533                        },
 3534                        cx,
 3535                    )
 3536                }
 3537            }
 3538            this.trigger_completion_on_input(&text, trigger_in_words, window, cx);
 3539            linked_editing_ranges::refresh_linked_ranges(this, window, cx);
 3540            this.refresh_inline_completion(true, false, window, cx);
 3541            jsx_tag_auto_close::handle_from(this, initial_buffer_versions, window, cx);
 3542        });
 3543    }
 3544
 3545    fn find_possible_emoji_shortcode_at_position(
 3546        snapshot: &MultiBufferSnapshot,
 3547        position: Point,
 3548    ) -> Option<String> {
 3549        let mut chars = Vec::new();
 3550        let mut found_colon = false;
 3551        for char in snapshot.reversed_chars_at(position).take(100) {
 3552            // Found a possible emoji shortcode in the middle of the buffer
 3553            if found_colon {
 3554                if char.is_whitespace() {
 3555                    chars.reverse();
 3556                    return Some(chars.iter().collect());
 3557                }
 3558                // If the previous character is not a whitespace, we are in the middle of a word
 3559                // and we only want to complete the shortcode if the word is made up of other emojis
 3560                let mut containing_word = String::new();
 3561                for ch in snapshot
 3562                    .reversed_chars_at(position)
 3563                    .skip(chars.len() + 1)
 3564                    .take(100)
 3565                {
 3566                    if ch.is_whitespace() {
 3567                        break;
 3568                    }
 3569                    containing_word.push(ch);
 3570                }
 3571                let containing_word = containing_word.chars().rev().collect::<String>();
 3572                if util::word_consists_of_emojis(containing_word.as_str()) {
 3573                    chars.reverse();
 3574                    return Some(chars.iter().collect());
 3575                }
 3576            }
 3577
 3578            if char.is_whitespace() || !char.is_ascii() {
 3579                return None;
 3580            }
 3581            if char == ':' {
 3582                found_colon = true;
 3583            } else {
 3584                chars.push(char);
 3585            }
 3586        }
 3587        // Found a possible emoji shortcode at the beginning of the buffer
 3588        chars.reverse();
 3589        Some(chars.iter().collect())
 3590    }
 3591
 3592    pub fn newline(&mut self, _: &Newline, window: &mut Window, cx: &mut Context<Self>) {
 3593        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
 3594        self.transact(window, cx, |this, window, cx| {
 3595            let (edits, selection_fixup_info): (Vec<_>, Vec<_>) = {
 3596                let selections = this.selections.all::<usize>(cx);
 3597                let multi_buffer = this.buffer.read(cx);
 3598                let buffer = multi_buffer.snapshot(cx);
 3599                selections
 3600                    .iter()
 3601                    .map(|selection| {
 3602                        let start_point = selection.start.to_point(&buffer);
 3603                        let mut indent =
 3604                            buffer.indent_size_for_line(MultiBufferRow(start_point.row));
 3605                        indent.len = cmp::min(indent.len, start_point.column);
 3606                        let start = selection.start;
 3607                        let end = selection.end;
 3608                        let selection_is_empty = start == end;
 3609                        let language_scope = buffer.language_scope_at(start);
 3610                        let (comment_delimiter, insert_extra_newline) = if let Some(language) =
 3611                            &language_scope
 3612                        {
 3613                            let insert_extra_newline =
 3614                                insert_extra_newline_brackets(&buffer, start..end, language)
 3615                                    || insert_extra_newline_tree_sitter(&buffer, start..end);
 3616
 3617                            // Comment extension on newline is allowed only for cursor selections
 3618                            let comment_delimiter = maybe!({
 3619                                if !selection_is_empty {
 3620                                    return None;
 3621                                }
 3622
 3623                                if !multi_buffer.language_settings(cx).extend_comment_on_newline {
 3624                                    return None;
 3625                                }
 3626
 3627                                let delimiters = language.line_comment_prefixes();
 3628                                let max_len_of_delimiter =
 3629                                    delimiters.iter().map(|delimiter| delimiter.len()).max()?;
 3630                                let (snapshot, range) =
 3631                                    buffer.buffer_line_for_row(MultiBufferRow(start_point.row))?;
 3632
 3633                                let mut index_of_first_non_whitespace = 0;
 3634                                let comment_candidate = snapshot
 3635                                    .chars_for_range(range)
 3636                                    .skip_while(|c| {
 3637                                        let should_skip = c.is_whitespace();
 3638                                        if should_skip {
 3639                                            index_of_first_non_whitespace += 1;
 3640                                        }
 3641                                        should_skip
 3642                                    })
 3643                                    .take(max_len_of_delimiter)
 3644                                    .collect::<String>();
 3645                                let comment_prefix = delimiters.iter().find(|comment_prefix| {
 3646                                    comment_candidate.starts_with(comment_prefix.as_ref())
 3647                                })?;
 3648                                let cursor_is_placed_after_comment_marker =
 3649                                    index_of_first_non_whitespace + comment_prefix.len()
 3650                                        <= start_point.column as usize;
 3651                                if cursor_is_placed_after_comment_marker {
 3652                                    Some(comment_prefix.clone())
 3653                                } else {
 3654                                    None
 3655                                }
 3656                            });
 3657                            (comment_delimiter, insert_extra_newline)
 3658                        } else {
 3659                            (None, false)
 3660                        };
 3661
 3662                        let capacity_for_delimiter = comment_delimiter
 3663                            .as_deref()
 3664                            .map(str::len)
 3665                            .unwrap_or_default();
 3666                        let mut new_text =
 3667                            String::with_capacity(1 + capacity_for_delimiter + indent.len as usize);
 3668                        new_text.push('\n');
 3669                        new_text.extend(indent.chars());
 3670                        if let Some(delimiter) = &comment_delimiter {
 3671                            new_text.push_str(delimiter);
 3672                        }
 3673                        if insert_extra_newline {
 3674                            new_text = new_text.repeat(2);
 3675                        }
 3676
 3677                        let anchor = buffer.anchor_after(end);
 3678                        let new_selection = selection.map(|_| anchor);
 3679                        (
 3680                            (start..end, new_text),
 3681                            (insert_extra_newline, new_selection),
 3682                        )
 3683                    })
 3684                    .unzip()
 3685            };
 3686
 3687            this.edit_with_autoindent(edits, cx);
 3688            let buffer = this.buffer.read(cx).snapshot(cx);
 3689            let new_selections = selection_fixup_info
 3690                .into_iter()
 3691                .map(|(extra_newline_inserted, new_selection)| {
 3692                    let mut cursor = new_selection.end.to_point(&buffer);
 3693                    if extra_newline_inserted {
 3694                        cursor.row -= 1;
 3695                        cursor.column = buffer.line_len(MultiBufferRow(cursor.row));
 3696                    }
 3697                    new_selection.map(|_| cursor)
 3698                })
 3699                .collect();
 3700
 3701            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 3702                s.select(new_selections)
 3703            });
 3704            this.refresh_inline_completion(true, false, window, cx);
 3705        });
 3706    }
 3707
 3708    pub fn newline_above(&mut self, _: &NewlineAbove, window: &mut Window, cx: &mut Context<Self>) {
 3709        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
 3710
 3711        let buffer = self.buffer.read(cx);
 3712        let snapshot = buffer.snapshot(cx);
 3713
 3714        let mut edits = Vec::new();
 3715        let mut rows = Vec::new();
 3716
 3717        for (rows_inserted, selection) in self.selections.all_adjusted(cx).into_iter().enumerate() {
 3718            let cursor = selection.head();
 3719            let row = cursor.row;
 3720
 3721            let start_of_line = snapshot.clip_point(Point::new(row, 0), Bias::Left);
 3722
 3723            let newline = "\n".to_string();
 3724            edits.push((start_of_line..start_of_line, newline));
 3725
 3726            rows.push(row + rows_inserted as u32);
 3727        }
 3728
 3729        self.transact(window, cx, |editor, window, cx| {
 3730            editor.edit(edits, cx);
 3731
 3732            editor.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 3733                let mut index = 0;
 3734                s.move_cursors_with(|map, _, _| {
 3735                    let row = rows[index];
 3736                    index += 1;
 3737
 3738                    let point = Point::new(row, 0);
 3739                    let boundary = map.next_line_boundary(point).1;
 3740                    let clipped = map.clip_point(boundary, Bias::Left);
 3741
 3742                    (clipped, SelectionGoal::None)
 3743                });
 3744            });
 3745
 3746            let mut indent_edits = Vec::new();
 3747            let multibuffer_snapshot = editor.buffer.read(cx).snapshot(cx);
 3748            for row in rows {
 3749                let indents = multibuffer_snapshot.suggested_indents(row..row + 1, cx);
 3750                for (row, indent) in indents {
 3751                    if indent.len == 0 {
 3752                        continue;
 3753                    }
 3754
 3755                    let text = match indent.kind {
 3756                        IndentKind::Space => " ".repeat(indent.len as usize),
 3757                        IndentKind::Tab => "\t".repeat(indent.len as usize),
 3758                    };
 3759                    let point = Point::new(row.0, 0);
 3760                    indent_edits.push((point..point, text));
 3761                }
 3762            }
 3763            editor.edit(indent_edits, cx);
 3764        });
 3765    }
 3766
 3767    pub fn newline_below(&mut self, _: &NewlineBelow, window: &mut Window, cx: &mut Context<Self>) {
 3768        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
 3769
 3770        let buffer = self.buffer.read(cx);
 3771        let snapshot = buffer.snapshot(cx);
 3772
 3773        let mut edits = Vec::new();
 3774        let mut rows = Vec::new();
 3775        let mut rows_inserted = 0;
 3776
 3777        for selection in self.selections.all_adjusted(cx) {
 3778            let cursor = selection.head();
 3779            let row = cursor.row;
 3780
 3781            let point = Point::new(row + 1, 0);
 3782            let start_of_line = snapshot.clip_point(point, Bias::Left);
 3783
 3784            let newline = "\n".to_string();
 3785            edits.push((start_of_line..start_of_line, newline));
 3786
 3787            rows_inserted += 1;
 3788            rows.push(row + rows_inserted);
 3789        }
 3790
 3791        self.transact(window, cx, |editor, window, cx| {
 3792            editor.edit(edits, cx);
 3793
 3794            editor.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 3795                let mut index = 0;
 3796                s.move_cursors_with(|map, _, _| {
 3797                    let row = rows[index];
 3798                    index += 1;
 3799
 3800                    let point = Point::new(row, 0);
 3801                    let boundary = map.next_line_boundary(point).1;
 3802                    let clipped = map.clip_point(boundary, Bias::Left);
 3803
 3804                    (clipped, SelectionGoal::None)
 3805                });
 3806            });
 3807
 3808            let mut indent_edits = Vec::new();
 3809            let multibuffer_snapshot = editor.buffer.read(cx).snapshot(cx);
 3810            for row in rows {
 3811                let indents = multibuffer_snapshot.suggested_indents(row..row + 1, cx);
 3812                for (row, indent) in indents {
 3813                    if indent.len == 0 {
 3814                        continue;
 3815                    }
 3816
 3817                    let text = match indent.kind {
 3818                        IndentKind::Space => " ".repeat(indent.len as usize),
 3819                        IndentKind::Tab => "\t".repeat(indent.len as usize),
 3820                    };
 3821                    let point = Point::new(row.0, 0);
 3822                    indent_edits.push((point..point, text));
 3823                }
 3824            }
 3825            editor.edit(indent_edits, cx);
 3826        });
 3827    }
 3828
 3829    pub fn insert(&mut self, text: &str, window: &mut Window, cx: &mut Context<Self>) {
 3830        let autoindent = text.is_empty().not().then(|| AutoindentMode::Block {
 3831            original_indent_columns: Vec::new(),
 3832        });
 3833        self.insert_with_autoindent_mode(text, autoindent, window, cx);
 3834    }
 3835
 3836    fn insert_with_autoindent_mode(
 3837        &mut self,
 3838        text: &str,
 3839        autoindent_mode: Option<AutoindentMode>,
 3840        window: &mut Window,
 3841        cx: &mut Context<Self>,
 3842    ) {
 3843        if self.read_only(cx) {
 3844            return;
 3845        }
 3846
 3847        let text: Arc<str> = text.into();
 3848        self.transact(window, cx, |this, window, cx| {
 3849            let old_selections = this.selections.all_adjusted(cx);
 3850            let selection_anchors = this.buffer.update(cx, |buffer, cx| {
 3851                let anchors = {
 3852                    let snapshot = buffer.read(cx);
 3853                    old_selections
 3854                        .iter()
 3855                        .map(|s| {
 3856                            let anchor = snapshot.anchor_after(s.head());
 3857                            s.map(|_| anchor)
 3858                        })
 3859                        .collect::<Vec<_>>()
 3860                };
 3861                buffer.edit(
 3862                    old_selections
 3863                        .iter()
 3864                        .map(|s| (s.start..s.end, text.clone())),
 3865                    autoindent_mode,
 3866                    cx,
 3867                );
 3868                anchors
 3869            });
 3870
 3871            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 3872                s.select_anchors(selection_anchors);
 3873            });
 3874
 3875            cx.notify();
 3876        });
 3877    }
 3878
 3879    fn trigger_completion_on_input(
 3880        &mut self,
 3881        text: &str,
 3882        trigger_in_words: bool,
 3883        window: &mut Window,
 3884        cx: &mut Context<Self>,
 3885    ) {
 3886        let ignore_completion_provider = self
 3887            .context_menu
 3888            .borrow()
 3889            .as_ref()
 3890            .map(|menu| match menu {
 3891                CodeContextMenu::Completions(completions_menu) => {
 3892                    completions_menu.ignore_completion_provider
 3893                }
 3894                CodeContextMenu::CodeActions(_) => false,
 3895            })
 3896            .unwrap_or(false);
 3897
 3898        if ignore_completion_provider {
 3899            self.show_word_completions(&ShowWordCompletions, window, cx);
 3900        } else if self.is_completion_trigger(text, trigger_in_words, cx) {
 3901            self.show_completions(
 3902                &ShowCompletions {
 3903                    trigger: Some(text.to_owned()).filter(|x| !x.is_empty()),
 3904                },
 3905                window,
 3906                cx,
 3907            );
 3908        } else {
 3909            self.hide_context_menu(window, cx);
 3910        }
 3911    }
 3912
 3913    fn is_completion_trigger(
 3914        &self,
 3915        text: &str,
 3916        trigger_in_words: bool,
 3917        cx: &mut Context<Self>,
 3918    ) -> bool {
 3919        let position = self.selections.newest_anchor().head();
 3920        let multibuffer = self.buffer.read(cx);
 3921        let Some(buffer) = position
 3922            .buffer_id
 3923            .and_then(|buffer_id| multibuffer.buffer(buffer_id).clone())
 3924        else {
 3925            return false;
 3926        };
 3927
 3928        if let Some(completion_provider) = &self.completion_provider {
 3929            completion_provider.is_completion_trigger(
 3930                &buffer,
 3931                position.text_anchor,
 3932                text,
 3933                trigger_in_words,
 3934                cx,
 3935            )
 3936        } else {
 3937            false
 3938        }
 3939    }
 3940
 3941    /// If any empty selections is touching the start of its innermost containing autoclose
 3942    /// region, expand it to select the brackets.
 3943    fn select_autoclose_pair(&mut self, window: &mut Window, cx: &mut Context<Self>) {
 3944        let selections = self.selections.all::<usize>(cx);
 3945        let buffer = self.buffer.read(cx).read(cx);
 3946        let new_selections = self
 3947            .selections_with_autoclose_regions(selections, &buffer)
 3948            .map(|(mut selection, region)| {
 3949                if !selection.is_empty() {
 3950                    return selection;
 3951                }
 3952
 3953                if let Some(region) = region {
 3954                    let mut range = region.range.to_offset(&buffer);
 3955                    if selection.start == range.start && range.start >= region.pair.start.len() {
 3956                        range.start -= region.pair.start.len();
 3957                        if buffer.contains_str_at(range.start, &region.pair.start)
 3958                            && buffer.contains_str_at(range.end, &region.pair.end)
 3959                        {
 3960                            range.end += region.pair.end.len();
 3961                            selection.start = range.start;
 3962                            selection.end = range.end;
 3963
 3964                            return selection;
 3965                        }
 3966                    }
 3967                }
 3968
 3969                let always_treat_brackets_as_autoclosed = buffer
 3970                    .language_settings_at(selection.start, cx)
 3971                    .always_treat_brackets_as_autoclosed;
 3972
 3973                if !always_treat_brackets_as_autoclosed {
 3974                    return selection;
 3975                }
 3976
 3977                if let Some(scope) = buffer.language_scope_at(selection.start) {
 3978                    for (pair, enabled) in scope.brackets() {
 3979                        if !enabled || !pair.close {
 3980                            continue;
 3981                        }
 3982
 3983                        if buffer.contains_str_at(selection.start, &pair.end) {
 3984                            let pair_start_len = pair.start.len();
 3985                            if buffer.contains_str_at(
 3986                                selection.start.saturating_sub(pair_start_len),
 3987                                &pair.start,
 3988                            ) {
 3989                                selection.start -= pair_start_len;
 3990                                selection.end += pair.end.len();
 3991
 3992                                return selection;
 3993                            }
 3994                        }
 3995                    }
 3996                }
 3997
 3998                selection
 3999            })
 4000            .collect();
 4001
 4002        drop(buffer);
 4003        self.change_selections(None, window, cx, |selections| {
 4004            selections.select(new_selections)
 4005        });
 4006    }
 4007
 4008    /// Iterate the given selections, and for each one, find the smallest surrounding
 4009    /// autoclose region. This uses the ordering of the selections and the autoclose
 4010    /// regions to avoid repeated comparisons.
 4011    fn selections_with_autoclose_regions<'a, D: ToOffset + Clone>(
 4012        &'a self,
 4013        selections: impl IntoIterator<Item = Selection<D>>,
 4014        buffer: &'a MultiBufferSnapshot,
 4015    ) -> impl Iterator<Item = (Selection<D>, Option<&'a AutocloseRegion>)> {
 4016        let mut i = 0;
 4017        let mut regions = self.autoclose_regions.as_slice();
 4018        selections.into_iter().map(move |selection| {
 4019            let range = selection.start.to_offset(buffer)..selection.end.to_offset(buffer);
 4020
 4021            let mut enclosing = None;
 4022            while let Some(pair_state) = regions.get(i) {
 4023                if pair_state.range.end.to_offset(buffer) < range.start {
 4024                    regions = &regions[i + 1..];
 4025                    i = 0;
 4026                } else if pair_state.range.start.to_offset(buffer) > range.end {
 4027                    break;
 4028                } else {
 4029                    if pair_state.selection_id == selection.id {
 4030                        enclosing = Some(pair_state);
 4031                    }
 4032                    i += 1;
 4033                }
 4034            }
 4035
 4036            (selection, enclosing)
 4037        })
 4038    }
 4039
 4040    /// Remove any autoclose regions that no longer contain their selection.
 4041    fn invalidate_autoclose_regions(
 4042        &mut self,
 4043        mut selections: &[Selection<Anchor>],
 4044        buffer: &MultiBufferSnapshot,
 4045    ) {
 4046        self.autoclose_regions.retain(|state| {
 4047            let mut i = 0;
 4048            while let Some(selection) = selections.get(i) {
 4049                if selection.end.cmp(&state.range.start, buffer).is_lt() {
 4050                    selections = &selections[1..];
 4051                    continue;
 4052                }
 4053                if selection.start.cmp(&state.range.end, buffer).is_gt() {
 4054                    break;
 4055                }
 4056                if selection.id == state.selection_id {
 4057                    return true;
 4058                } else {
 4059                    i += 1;
 4060                }
 4061            }
 4062            false
 4063        });
 4064    }
 4065
 4066    fn completion_query(buffer: &MultiBufferSnapshot, position: impl ToOffset) -> Option<String> {
 4067        let offset = position.to_offset(buffer);
 4068        let (word_range, kind) = buffer.surrounding_word(offset, true);
 4069        if offset > word_range.start && kind == Some(CharKind::Word) {
 4070            Some(
 4071                buffer
 4072                    .text_for_range(word_range.start..offset)
 4073                    .collect::<String>(),
 4074            )
 4075        } else {
 4076            None
 4077        }
 4078    }
 4079
 4080    pub fn toggle_inlay_hints(
 4081        &mut self,
 4082        _: &ToggleInlayHints,
 4083        _: &mut Window,
 4084        cx: &mut Context<Self>,
 4085    ) {
 4086        self.refresh_inlay_hints(
 4087            InlayHintRefreshReason::Toggle(!self.inlay_hints_enabled()),
 4088            cx,
 4089        );
 4090    }
 4091
 4092    pub fn inlay_hints_enabled(&self) -> bool {
 4093        self.inlay_hint_cache.enabled
 4094    }
 4095
 4096    fn refresh_inlay_hints(&mut self, reason: InlayHintRefreshReason, cx: &mut Context<Self>) {
 4097        if self.semantics_provider.is_none() || !self.mode.is_full() {
 4098            return;
 4099        }
 4100
 4101        let reason_description = reason.description();
 4102        let ignore_debounce = matches!(
 4103            reason,
 4104            InlayHintRefreshReason::SettingsChange(_)
 4105                | InlayHintRefreshReason::Toggle(_)
 4106                | InlayHintRefreshReason::ExcerptsRemoved(_)
 4107                | InlayHintRefreshReason::ModifiersChanged(_)
 4108        );
 4109        let (invalidate_cache, required_languages) = match reason {
 4110            InlayHintRefreshReason::ModifiersChanged(enabled) => {
 4111                match self.inlay_hint_cache.modifiers_override(enabled) {
 4112                    Some(enabled) => {
 4113                        if enabled {
 4114                            (InvalidationStrategy::RefreshRequested, None)
 4115                        } else {
 4116                            self.splice_inlays(
 4117                                &self
 4118                                    .visible_inlay_hints(cx)
 4119                                    .iter()
 4120                                    .map(|inlay| inlay.id)
 4121                                    .collect::<Vec<InlayId>>(),
 4122                                Vec::new(),
 4123                                cx,
 4124                            );
 4125                            return;
 4126                        }
 4127                    }
 4128                    None => return,
 4129                }
 4130            }
 4131            InlayHintRefreshReason::Toggle(enabled) => {
 4132                if self.inlay_hint_cache.toggle(enabled) {
 4133                    if enabled {
 4134                        (InvalidationStrategy::RefreshRequested, None)
 4135                    } else {
 4136                        self.splice_inlays(
 4137                            &self
 4138                                .visible_inlay_hints(cx)
 4139                                .iter()
 4140                                .map(|inlay| inlay.id)
 4141                                .collect::<Vec<InlayId>>(),
 4142                            Vec::new(),
 4143                            cx,
 4144                        );
 4145                        return;
 4146                    }
 4147                } else {
 4148                    return;
 4149                }
 4150            }
 4151            InlayHintRefreshReason::SettingsChange(new_settings) => {
 4152                match self.inlay_hint_cache.update_settings(
 4153                    &self.buffer,
 4154                    new_settings,
 4155                    self.visible_inlay_hints(cx),
 4156                    cx,
 4157                ) {
 4158                    ControlFlow::Break(Some(InlaySplice {
 4159                        to_remove,
 4160                        to_insert,
 4161                    })) => {
 4162                        self.splice_inlays(&to_remove, to_insert, cx);
 4163                        return;
 4164                    }
 4165                    ControlFlow::Break(None) => return,
 4166                    ControlFlow::Continue(()) => (InvalidationStrategy::RefreshRequested, None),
 4167                }
 4168            }
 4169            InlayHintRefreshReason::ExcerptsRemoved(excerpts_removed) => {
 4170                if let Some(InlaySplice {
 4171                    to_remove,
 4172                    to_insert,
 4173                }) = self.inlay_hint_cache.remove_excerpts(&excerpts_removed)
 4174                {
 4175                    self.splice_inlays(&to_remove, to_insert, cx);
 4176                }
 4177                self.display_map.update(cx, |display_map, _| {
 4178                    display_map.remove_inlays_for_excerpts(&excerpts_removed)
 4179                });
 4180                return;
 4181            }
 4182            InlayHintRefreshReason::NewLinesShown => (InvalidationStrategy::None, None),
 4183            InlayHintRefreshReason::BufferEdited(buffer_languages) => {
 4184                (InvalidationStrategy::BufferEdited, Some(buffer_languages))
 4185            }
 4186            InlayHintRefreshReason::RefreshRequested => {
 4187                (InvalidationStrategy::RefreshRequested, None)
 4188            }
 4189        };
 4190
 4191        if let Some(InlaySplice {
 4192            to_remove,
 4193            to_insert,
 4194        }) = self.inlay_hint_cache.spawn_hint_refresh(
 4195            reason_description,
 4196            self.excerpts_for_inlay_hints_query(required_languages.as_ref(), cx),
 4197            invalidate_cache,
 4198            ignore_debounce,
 4199            cx,
 4200        ) {
 4201            self.splice_inlays(&to_remove, to_insert, cx);
 4202        }
 4203    }
 4204
 4205    fn visible_inlay_hints(&self, cx: &Context<Editor>) -> Vec<Inlay> {
 4206        self.display_map
 4207            .read(cx)
 4208            .current_inlays()
 4209            .filter(move |inlay| matches!(inlay.id, InlayId::Hint(_)))
 4210            .cloned()
 4211            .collect()
 4212    }
 4213
 4214    pub fn excerpts_for_inlay_hints_query(
 4215        &self,
 4216        restrict_to_languages: Option<&HashSet<Arc<Language>>>,
 4217        cx: &mut Context<Editor>,
 4218    ) -> HashMap<ExcerptId, (Entity<Buffer>, clock::Global, Range<usize>)> {
 4219        let Some(project) = self.project.as_ref() else {
 4220            return HashMap::default();
 4221        };
 4222        let project = project.read(cx);
 4223        let multi_buffer = self.buffer().read(cx);
 4224        let multi_buffer_snapshot = multi_buffer.snapshot(cx);
 4225        let multi_buffer_visible_start = self
 4226            .scroll_manager
 4227            .anchor()
 4228            .anchor
 4229            .to_point(&multi_buffer_snapshot);
 4230        let multi_buffer_visible_end = multi_buffer_snapshot.clip_point(
 4231            multi_buffer_visible_start
 4232                + Point::new(self.visible_line_count().unwrap_or(0.).ceil() as u32, 0),
 4233            Bias::Left,
 4234        );
 4235        let multi_buffer_visible_range = multi_buffer_visible_start..multi_buffer_visible_end;
 4236        multi_buffer_snapshot
 4237            .range_to_buffer_ranges(multi_buffer_visible_range)
 4238            .into_iter()
 4239            .filter(|(_, excerpt_visible_range, _)| !excerpt_visible_range.is_empty())
 4240            .filter_map(|(buffer, excerpt_visible_range, excerpt_id)| {
 4241                let buffer_file = project::File::from_dyn(buffer.file())?;
 4242                let buffer_worktree = project.worktree_for_id(buffer_file.worktree_id(cx), cx)?;
 4243                let worktree_entry = buffer_worktree
 4244                    .read(cx)
 4245                    .entry_for_id(buffer_file.project_entry_id(cx)?)?;
 4246                if worktree_entry.is_ignored {
 4247                    return None;
 4248                }
 4249
 4250                let language = buffer.language()?;
 4251                if let Some(restrict_to_languages) = restrict_to_languages {
 4252                    if !restrict_to_languages.contains(language) {
 4253                        return None;
 4254                    }
 4255                }
 4256                Some((
 4257                    excerpt_id,
 4258                    (
 4259                        multi_buffer.buffer(buffer.remote_id()).unwrap(),
 4260                        buffer.version().clone(),
 4261                        excerpt_visible_range,
 4262                    ),
 4263                ))
 4264            })
 4265            .collect()
 4266    }
 4267
 4268    pub fn text_layout_details(&self, window: &mut Window) -> TextLayoutDetails {
 4269        TextLayoutDetails {
 4270            text_system: window.text_system().clone(),
 4271            editor_style: self.style.clone().unwrap(),
 4272            rem_size: window.rem_size(),
 4273            scroll_anchor: self.scroll_manager.anchor(),
 4274            visible_rows: self.visible_line_count(),
 4275            vertical_scroll_margin: self.scroll_manager.vertical_scroll_margin,
 4276        }
 4277    }
 4278
 4279    pub fn splice_inlays(
 4280        &self,
 4281        to_remove: &[InlayId],
 4282        to_insert: Vec<Inlay>,
 4283        cx: &mut Context<Self>,
 4284    ) {
 4285        self.display_map.update(cx, |display_map, cx| {
 4286            display_map.splice_inlays(to_remove, to_insert, cx)
 4287        });
 4288        cx.notify();
 4289    }
 4290
 4291    fn trigger_on_type_formatting(
 4292        &self,
 4293        input: String,
 4294        window: &mut Window,
 4295        cx: &mut Context<Self>,
 4296    ) -> Option<Task<Result<()>>> {
 4297        if input.len() != 1 {
 4298            return None;
 4299        }
 4300
 4301        let project = self.project.as_ref()?;
 4302        let position = self.selections.newest_anchor().head();
 4303        let (buffer, buffer_position) = self
 4304            .buffer
 4305            .read(cx)
 4306            .text_anchor_for_position(position, cx)?;
 4307
 4308        let settings = language_settings::language_settings(
 4309            buffer
 4310                .read(cx)
 4311                .language_at(buffer_position)
 4312                .map(|l| l.name()),
 4313            buffer.read(cx).file(),
 4314            cx,
 4315        );
 4316        if !settings.use_on_type_format {
 4317            return None;
 4318        }
 4319
 4320        // OnTypeFormatting returns a list of edits, no need to pass them between Zed instances,
 4321        // hence we do LSP request & edit on host side only — add formats to host's history.
 4322        let push_to_lsp_host_history = true;
 4323        // If this is not the host, append its history with new edits.
 4324        let push_to_client_history = project.read(cx).is_via_collab();
 4325
 4326        let on_type_formatting = project.update(cx, |project, cx| {
 4327            project.on_type_format(
 4328                buffer.clone(),
 4329                buffer_position,
 4330                input,
 4331                push_to_lsp_host_history,
 4332                cx,
 4333            )
 4334        });
 4335        Some(cx.spawn_in(window, async move |editor, cx| {
 4336            if let Some(transaction) = on_type_formatting.await? {
 4337                if push_to_client_history {
 4338                    buffer
 4339                        .update(cx, |buffer, _| {
 4340                            buffer.push_transaction(transaction, Instant::now());
 4341                            buffer.finalize_last_transaction();
 4342                        })
 4343                        .ok();
 4344                }
 4345                editor.update(cx, |editor, cx| {
 4346                    editor.refresh_document_highlights(cx);
 4347                })?;
 4348            }
 4349            Ok(())
 4350        }))
 4351    }
 4352
 4353    pub fn show_word_completions(
 4354        &mut self,
 4355        _: &ShowWordCompletions,
 4356        window: &mut Window,
 4357        cx: &mut Context<Self>,
 4358    ) {
 4359        self.open_completions_menu(true, None, window, cx);
 4360    }
 4361
 4362    pub fn show_completions(
 4363        &mut self,
 4364        options: &ShowCompletions,
 4365        window: &mut Window,
 4366        cx: &mut Context<Self>,
 4367    ) {
 4368        self.open_completions_menu(false, options.trigger.as_deref(), window, cx);
 4369    }
 4370
 4371    fn open_completions_menu(
 4372        &mut self,
 4373        ignore_completion_provider: bool,
 4374        trigger: Option<&str>,
 4375        window: &mut Window,
 4376        cx: &mut Context<Self>,
 4377    ) {
 4378        if self.pending_rename.is_some() {
 4379            return;
 4380        }
 4381        if !self.snippet_stack.is_empty() && self.context_menu.borrow().as_ref().is_some() {
 4382            return;
 4383        }
 4384
 4385        let position = self.selections.newest_anchor().head();
 4386        if position.diff_base_anchor.is_some() {
 4387            return;
 4388        }
 4389        let (buffer, buffer_position) =
 4390            if let Some(output) = self.buffer.read(cx).text_anchor_for_position(position, cx) {
 4391                output
 4392            } else {
 4393                return;
 4394            };
 4395        let buffer_snapshot = buffer.read(cx).snapshot();
 4396        let show_completion_documentation = buffer_snapshot
 4397            .settings_at(buffer_position, cx)
 4398            .show_completion_documentation;
 4399
 4400        let query = Self::completion_query(&self.buffer.read(cx).read(cx), position);
 4401
 4402        let trigger_kind = match trigger {
 4403            Some(trigger) if buffer.read(cx).completion_triggers().contains(trigger) => {
 4404                CompletionTriggerKind::TRIGGER_CHARACTER
 4405            }
 4406            _ => CompletionTriggerKind::INVOKED,
 4407        };
 4408        let completion_context = CompletionContext {
 4409            trigger_character: trigger.and_then(|trigger| {
 4410                if trigger_kind == CompletionTriggerKind::TRIGGER_CHARACTER {
 4411                    Some(String::from(trigger))
 4412                } else {
 4413                    None
 4414                }
 4415            }),
 4416            trigger_kind,
 4417        };
 4418
 4419        let (old_range, word_kind) = buffer_snapshot.surrounding_word(buffer_position);
 4420        let (old_range, word_to_exclude) = if word_kind == Some(CharKind::Word) {
 4421            let word_to_exclude = buffer_snapshot
 4422                .text_for_range(old_range.clone())
 4423                .collect::<String>();
 4424            (
 4425                buffer_snapshot.anchor_before(old_range.start)
 4426                    ..buffer_snapshot.anchor_after(old_range.end),
 4427                Some(word_to_exclude),
 4428            )
 4429        } else {
 4430            (buffer_position..buffer_position, None)
 4431        };
 4432
 4433        let completion_settings = language_settings(
 4434            buffer_snapshot
 4435                .language_at(buffer_position)
 4436                .map(|language| language.name()),
 4437            buffer_snapshot.file(),
 4438            cx,
 4439        )
 4440        .completions;
 4441
 4442        // The document can be large, so stay in reasonable bounds when searching for words,
 4443        // otherwise completion pop-up might be slow to appear.
 4444        const WORD_LOOKUP_ROWS: u32 = 5_000;
 4445        let buffer_row = text::ToPoint::to_point(&buffer_position, &buffer_snapshot).row;
 4446        let min_word_search = buffer_snapshot.clip_point(
 4447            Point::new(buffer_row.saturating_sub(WORD_LOOKUP_ROWS), 0),
 4448            Bias::Left,
 4449        );
 4450        let max_word_search = buffer_snapshot.clip_point(
 4451            Point::new(buffer_row + WORD_LOOKUP_ROWS, 0).min(buffer_snapshot.max_point()),
 4452            Bias::Right,
 4453        );
 4454        let word_search_range = buffer_snapshot.point_to_offset(min_word_search)
 4455            ..buffer_snapshot.point_to_offset(max_word_search);
 4456
 4457        let provider = self
 4458            .completion_provider
 4459            .as_ref()
 4460            .filter(|_| !ignore_completion_provider);
 4461        let skip_digits = query
 4462            .as_ref()
 4463            .map_or(true, |query| !query.chars().any(|c| c.is_digit(10)));
 4464
 4465        let (mut words, provided_completions) = match provider {
 4466            Some(provider) => {
 4467                let completions = provider.completions(
 4468                    position.excerpt_id,
 4469                    &buffer,
 4470                    buffer_position,
 4471                    completion_context,
 4472                    window,
 4473                    cx,
 4474                );
 4475
 4476                let words = match completion_settings.words {
 4477                    WordsCompletionMode::Disabled => Task::ready(BTreeMap::default()),
 4478                    WordsCompletionMode::Enabled | WordsCompletionMode::Fallback => cx
 4479                        .background_spawn(async move {
 4480                            buffer_snapshot.words_in_range(WordsQuery {
 4481                                fuzzy_contents: None,
 4482                                range: word_search_range,
 4483                                skip_digits,
 4484                            })
 4485                        }),
 4486                };
 4487
 4488                (words, completions)
 4489            }
 4490            None => (
 4491                cx.background_spawn(async move {
 4492                    buffer_snapshot.words_in_range(WordsQuery {
 4493                        fuzzy_contents: None,
 4494                        range: word_search_range,
 4495                        skip_digits,
 4496                    })
 4497                }),
 4498                Task::ready(Ok(None)),
 4499            ),
 4500        };
 4501
 4502        let sort_completions = provider
 4503            .as_ref()
 4504            .map_or(false, |provider| provider.sort_completions());
 4505
 4506        let filter_completions = provider
 4507            .as_ref()
 4508            .map_or(true, |provider| provider.filter_completions());
 4509
 4510        let id = post_inc(&mut self.next_completion_id);
 4511        let task = cx.spawn_in(window, async move |editor, cx| {
 4512            async move {
 4513                editor.update(cx, |this, _| {
 4514                    this.completion_tasks.retain(|(task_id, _)| *task_id >= id);
 4515                })?;
 4516
 4517                let mut completions = Vec::new();
 4518                if let Some(provided_completions) = provided_completions.await.log_err().flatten() {
 4519                    completions.extend(provided_completions);
 4520                    if completion_settings.words == WordsCompletionMode::Fallback {
 4521                        words = Task::ready(BTreeMap::default());
 4522                    }
 4523                }
 4524
 4525                let mut words = words.await;
 4526                if let Some(word_to_exclude) = &word_to_exclude {
 4527                    words.remove(word_to_exclude);
 4528                }
 4529                for lsp_completion in &completions {
 4530                    words.remove(&lsp_completion.new_text);
 4531                }
 4532                completions.extend(words.into_iter().map(|(word, word_range)| Completion {
 4533                    replace_range: old_range.clone(),
 4534                    new_text: word.clone(),
 4535                    label: CodeLabel::plain(word, None),
 4536                    icon_path: None,
 4537                    documentation: None,
 4538                    source: CompletionSource::BufferWord {
 4539                        word_range,
 4540                        resolved: false,
 4541                    },
 4542                    insert_text_mode: Some(InsertTextMode::AS_IS),
 4543                    confirm: None,
 4544                }));
 4545
 4546                let menu = if completions.is_empty() {
 4547                    None
 4548                } else {
 4549                    let mut menu = CompletionsMenu::new(
 4550                        id,
 4551                        sort_completions,
 4552                        show_completion_documentation,
 4553                        ignore_completion_provider,
 4554                        position,
 4555                        buffer.clone(),
 4556                        completions.into(),
 4557                    );
 4558
 4559                    menu.filter(
 4560                        if filter_completions {
 4561                            query.as_deref()
 4562                        } else {
 4563                            None
 4564                        },
 4565                        cx.background_executor().clone(),
 4566                    )
 4567                    .await;
 4568
 4569                    menu.visible().then_some(menu)
 4570                };
 4571
 4572                editor.update_in(cx, |editor, window, cx| {
 4573                    match editor.context_menu.borrow().as_ref() {
 4574                        None => {}
 4575                        Some(CodeContextMenu::Completions(prev_menu)) => {
 4576                            if prev_menu.id > id {
 4577                                return;
 4578                            }
 4579                        }
 4580                        _ => return,
 4581                    }
 4582
 4583                    if editor.focus_handle.is_focused(window) && menu.is_some() {
 4584                        let mut menu = menu.unwrap();
 4585                        menu.resolve_visible_completions(editor.completion_provider.as_deref(), cx);
 4586
 4587                        *editor.context_menu.borrow_mut() =
 4588                            Some(CodeContextMenu::Completions(menu));
 4589
 4590                        if editor.show_edit_predictions_in_menu() {
 4591                            editor.update_visible_inline_completion(window, cx);
 4592                        } else {
 4593                            editor.discard_inline_completion(false, cx);
 4594                        }
 4595
 4596                        cx.notify();
 4597                    } else if editor.completion_tasks.len() <= 1 {
 4598                        // If there are no more completion tasks and the last menu was
 4599                        // empty, we should hide it.
 4600                        let was_hidden = editor.hide_context_menu(window, cx).is_none();
 4601                        // If it was already hidden and we don't show inline
 4602                        // completions in the menu, we should also show the
 4603                        // inline-completion when available.
 4604                        if was_hidden && editor.show_edit_predictions_in_menu() {
 4605                            editor.update_visible_inline_completion(window, cx);
 4606                        }
 4607                    }
 4608                })?;
 4609
 4610                anyhow::Ok(())
 4611            }
 4612            .log_err()
 4613            .await
 4614        });
 4615
 4616        self.completion_tasks.push((id, task));
 4617    }
 4618
 4619    #[cfg(feature = "test-support")]
 4620    pub fn current_completions(&self) -> Option<Vec<project::Completion>> {
 4621        let menu = self.context_menu.borrow();
 4622        if let CodeContextMenu::Completions(menu) = menu.as_ref()? {
 4623            let completions = menu.completions.borrow();
 4624            Some(completions.to_vec())
 4625        } else {
 4626            None
 4627        }
 4628    }
 4629
 4630    pub fn confirm_completion(
 4631        &mut self,
 4632        action: &ConfirmCompletion,
 4633        window: &mut Window,
 4634        cx: &mut Context<Self>,
 4635    ) -> Option<Task<Result<()>>> {
 4636        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
 4637        self.do_completion(action.item_ix, CompletionIntent::Complete, window, cx)
 4638    }
 4639
 4640    pub fn confirm_completion_insert(
 4641        &mut self,
 4642        _: &ConfirmCompletionInsert,
 4643        window: &mut Window,
 4644        cx: &mut Context<Self>,
 4645    ) -> Option<Task<Result<()>>> {
 4646        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
 4647        self.do_completion(None, CompletionIntent::CompleteWithInsert, window, cx)
 4648    }
 4649
 4650    pub fn confirm_completion_replace(
 4651        &mut self,
 4652        _: &ConfirmCompletionReplace,
 4653        window: &mut Window,
 4654        cx: &mut Context<Self>,
 4655    ) -> Option<Task<Result<()>>> {
 4656        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
 4657        self.do_completion(None, CompletionIntent::CompleteWithReplace, window, cx)
 4658    }
 4659
 4660    pub fn compose_completion(
 4661        &mut self,
 4662        action: &ComposeCompletion,
 4663        window: &mut Window,
 4664        cx: &mut Context<Self>,
 4665    ) -> Option<Task<Result<()>>> {
 4666        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
 4667        self.do_completion(action.item_ix, CompletionIntent::Compose, window, cx)
 4668    }
 4669
 4670    fn do_completion(
 4671        &mut self,
 4672        item_ix: Option<usize>,
 4673        intent: CompletionIntent,
 4674        window: &mut Window,
 4675        cx: &mut Context<Editor>,
 4676    ) -> Option<Task<Result<()>>> {
 4677        use language::ToOffset as _;
 4678
 4679        let CodeContextMenu::Completions(completions_menu) = self.hide_context_menu(window, cx)?
 4680        else {
 4681            return None;
 4682        };
 4683
 4684        let candidate_id = {
 4685            let entries = completions_menu.entries.borrow();
 4686            let mat = entries.get(item_ix.unwrap_or(completions_menu.selected_item))?;
 4687            if self.show_edit_predictions_in_menu() {
 4688                self.discard_inline_completion(true, cx);
 4689            }
 4690            mat.candidate_id
 4691        };
 4692
 4693        let buffer_handle = completions_menu.buffer;
 4694        let completion = completions_menu
 4695            .completions
 4696            .borrow()
 4697            .get(candidate_id)?
 4698            .clone();
 4699        cx.stop_propagation();
 4700
 4701        let snippet;
 4702        let new_text;
 4703        if completion.is_snippet() {
 4704            snippet = Some(Snippet::parse(&completion.new_text).log_err()?);
 4705            new_text = snippet.as_ref().unwrap().text.clone();
 4706        } else {
 4707            snippet = None;
 4708            new_text = completion.new_text.clone();
 4709        };
 4710
 4711        let replace_range = choose_completion_range(&completion, intent, &buffer_handle, cx);
 4712        let buffer = buffer_handle.read(cx);
 4713        let snapshot = self.buffer.read(cx).snapshot(cx);
 4714        let replace_range_multibuffer = {
 4715            let excerpt = snapshot
 4716                .excerpt_containing(self.selections.newest_anchor().range())
 4717                .unwrap();
 4718            let multibuffer_anchor = snapshot
 4719                .anchor_in_excerpt(excerpt.id(), buffer.anchor_before(replace_range.start))
 4720                .unwrap()
 4721                ..snapshot
 4722                    .anchor_in_excerpt(excerpt.id(), buffer.anchor_before(replace_range.end))
 4723                    .unwrap();
 4724            multibuffer_anchor.start.to_offset(&snapshot)
 4725                ..multibuffer_anchor.end.to_offset(&snapshot)
 4726        };
 4727        let newest_anchor = self.selections.newest_anchor();
 4728        if newest_anchor.head().buffer_id != Some(buffer.remote_id()) {
 4729            return None;
 4730        }
 4731
 4732        let old_text = buffer
 4733            .text_for_range(replace_range.clone())
 4734            .collect::<String>();
 4735        let lookbehind = newest_anchor
 4736            .start
 4737            .text_anchor
 4738            .to_offset(buffer)
 4739            .saturating_sub(replace_range.start);
 4740        let lookahead = replace_range
 4741            .end
 4742            .saturating_sub(newest_anchor.end.text_anchor.to_offset(buffer));
 4743        let prefix = &old_text[..old_text.len().saturating_sub(lookahead)];
 4744        let suffix = &old_text[lookbehind.min(old_text.len())..];
 4745
 4746        let selections = self.selections.all::<usize>(cx);
 4747        let mut ranges = Vec::new();
 4748        let mut linked_edits = HashMap::<_, Vec<_>>::default();
 4749
 4750        for selection in &selections {
 4751            let range = if selection.id == newest_anchor.id {
 4752                replace_range_multibuffer.clone()
 4753            } else {
 4754                let mut range = selection.range();
 4755
 4756                // if prefix is present, don't duplicate it
 4757                if snapshot.contains_str_at(range.start.saturating_sub(lookbehind), prefix) {
 4758                    range.start = range.start.saturating_sub(lookbehind);
 4759
 4760                    // if suffix is also present, mimic the newest cursor and replace it
 4761                    if selection.id != newest_anchor.id
 4762                        && snapshot.contains_str_at(range.end, suffix)
 4763                    {
 4764                        range.end += lookahead;
 4765                    }
 4766                }
 4767                range
 4768            };
 4769
 4770            ranges.push(range);
 4771
 4772            if !self.linked_edit_ranges.is_empty() {
 4773                let start_anchor = snapshot.anchor_before(selection.head());
 4774                let end_anchor = snapshot.anchor_after(selection.tail());
 4775                if let Some(ranges) = self
 4776                    .linked_editing_ranges_for(start_anchor.text_anchor..end_anchor.text_anchor, cx)
 4777                {
 4778                    for (buffer, edits) in ranges {
 4779                        linked_edits
 4780                            .entry(buffer.clone())
 4781                            .or_default()
 4782                            .extend(edits.into_iter().map(|range| (range, new_text.to_owned())));
 4783                    }
 4784                }
 4785            }
 4786        }
 4787
 4788        cx.emit(EditorEvent::InputHandled {
 4789            utf16_range_to_replace: None,
 4790            text: new_text.clone().into(),
 4791        });
 4792
 4793        self.transact(window, cx, |this, window, cx| {
 4794            if let Some(mut snippet) = snippet {
 4795                snippet.text = new_text.to_string();
 4796                this.insert_snippet(&ranges, snippet, window, cx).log_err();
 4797            } else {
 4798                this.buffer.update(cx, |buffer, cx| {
 4799                    let auto_indent = match completion.insert_text_mode {
 4800                        Some(InsertTextMode::AS_IS) => None,
 4801                        _ => this.autoindent_mode.clone(),
 4802                    };
 4803                    let edits = ranges.into_iter().map(|range| (range, new_text.as_str()));
 4804                    buffer.edit(edits, auto_indent, cx);
 4805                });
 4806            }
 4807            for (buffer, edits) in linked_edits {
 4808                buffer.update(cx, |buffer, cx| {
 4809                    let snapshot = buffer.snapshot();
 4810                    let edits = edits
 4811                        .into_iter()
 4812                        .map(|(range, text)| {
 4813                            use text::ToPoint as TP;
 4814                            let end_point = TP::to_point(&range.end, &snapshot);
 4815                            let start_point = TP::to_point(&range.start, &snapshot);
 4816                            (start_point..end_point, text)
 4817                        })
 4818                        .sorted_by_key(|(range, _)| range.start);
 4819                    buffer.edit(edits, None, cx);
 4820                })
 4821            }
 4822
 4823            this.refresh_inline_completion(true, false, window, cx);
 4824        });
 4825
 4826        let show_new_completions_on_confirm = completion
 4827            .confirm
 4828            .as_ref()
 4829            .map_or(false, |confirm| confirm(intent, window, cx));
 4830        if show_new_completions_on_confirm {
 4831            self.show_completions(&ShowCompletions { trigger: None }, window, cx);
 4832        }
 4833
 4834        let provider = self.completion_provider.as_ref()?;
 4835        drop(completion);
 4836        let apply_edits = provider.apply_additional_edits_for_completion(
 4837            buffer_handle,
 4838            completions_menu.completions.clone(),
 4839            candidate_id,
 4840            true,
 4841            cx,
 4842        );
 4843
 4844        let editor_settings = EditorSettings::get_global(cx);
 4845        if editor_settings.show_signature_help_after_edits || editor_settings.auto_signature_help {
 4846            // After the code completion is finished, users often want to know what signatures are needed.
 4847            // so we should automatically call signature_help
 4848            self.show_signature_help(&ShowSignatureHelp, window, cx);
 4849        }
 4850
 4851        Some(cx.foreground_executor().spawn(async move {
 4852            apply_edits.await?;
 4853            Ok(())
 4854        }))
 4855    }
 4856
 4857    fn prepare_code_actions_task(
 4858        &mut self,
 4859        action: &ToggleCodeActions,
 4860        window: &mut Window,
 4861        cx: &mut Context<Self>,
 4862    ) -> Task<Option<(Entity<Buffer>, CodeActionContents)>> {
 4863        let snapshot = self.snapshot(window, cx);
 4864        let multibuffer_point = action
 4865            .deployed_from_indicator
 4866            .map(|row| DisplayPoint::new(row, 0).to_point(&snapshot))
 4867            .unwrap_or_else(|| self.selections.newest::<Point>(cx).head());
 4868
 4869        let Some((buffer, buffer_row)) = snapshot
 4870            .buffer_snapshot
 4871            .buffer_line_for_row(MultiBufferRow(multibuffer_point.row))
 4872            .and_then(|(buffer_snapshot, range)| {
 4873                self.buffer
 4874                    .read(cx)
 4875                    .buffer(buffer_snapshot.remote_id())
 4876                    .map(|buffer| (buffer, range.start.row))
 4877            })
 4878        else {
 4879            return Task::ready(None);
 4880        };
 4881
 4882        let (_, code_actions) = self
 4883            .available_code_actions
 4884            .clone()
 4885            .and_then(|(location, code_actions)| {
 4886                let snapshot = location.buffer.read(cx).snapshot();
 4887                let point_range = location.range.to_point(&snapshot);
 4888                let point_range = point_range.start.row..=point_range.end.row;
 4889                if point_range.contains(&buffer_row) {
 4890                    Some((location, code_actions))
 4891                } else {
 4892                    None
 4893                }
 4894            })
 4895            .unzip();
 4896
 4897        let buffer_id = buffer.read(cx).remote_id();
 4898        let tasks = self
 4899            .tasks
 4900            .get(&(buffer_id, buffer_row))
 4901            .map(|t| Arc::new(t.to_owned()));
 4902
 4903        if tasks.is_none() && code_actions.is_none() {
 4904            return Task::ready(None);
 4905        }
 4906
 4907        self.completion_tasks.clear();
 4908        self.discard_inline_completion(false, cx);
 4909
 4910        let task_context = tasks
 4911            .as_ref()
 4912            .zip(self.project.clone())
 4913            .map(|(tasks, project)| {
 4914                Self::build_tasks_context(&project, &buffer, buffer_row, tasks, cx)
 4915            });
 4916
 4917        cx.spawn_in(window, async move |_, _| {
 4918            let task_context = match task_context {
 4919                Some(task_context) => task_context.await,
 4920                None => None,
 4921            };
 4922            let resolved_tasks = tasks.zip(task_context).map(|(tasks, task_context)| {
 4923                Rc::new(ResolvedTasks {
 4924                    templates: tasks.resolve(&task_context).collect(),
 4925                    position: snapshot
 4926                        .buffer_snapshot
 4927                        .anchor_before(Point::new(multibuffer_point.row, tasks.column)),
 4928                })
 4929            });
 4930            Some((
 4931                buffer,
 4932                CodeActionContents {
 4933                    actions: code_actions,
 4934                    tasks: resolved_tasks,
 4935                },
 4936            ))
 4937        })
 4938    }
 4939
 4940    pub fn toggle_code_actions(
 4941        &mut self,
 4942        action: &ToggleCodeActions,
 4943        window: &mut Window,
 4944        cx: &mut Context<Self>,
 4945    ) {
 4946        let mut context_menu = self.context_menu.borrow_mut();
 4947        if let Some(CodeContextMenu::CodeActions(code_actions)) = context_menu.as_ref() {
 4948            if code_actions.deployed_from_indicator == action.deployed_from_indicator {
 4949                // Toggle if we're selecting the same one
 4950                *context_menu = None;
 4951                cx.notify();
 4952                return;
 4953            } else {
 4954                // Otherwise, clear it and start a new one
 4955                *context_menu = None;
 4956                cx.notify();
 4957            }
 4958        }
 4959        drop(context_menu);
 4960
 4961        let deployed_from_indicator = action.deployed_from_indicator;
 4962        let mut task = self.code_actions_task.take();
 4963        let action = action.clone();
 4964
 4965        cx.spawn_in(window, async move |editor, cx| {
 4966            while let Some(prev_task) = task {
 4967                prev_task.await.log_err();
 4968                task = editor.update(cx, |this, _| this.code_actions_task.take())?;
 4969            }
 4970
 4971            let context_menu_task = editor.update_in(cx, |editor, window, cx| {
 4972                if !editor.focus_handle.is_focused(window) {
 4973                    return Some(Task::ready(Ok(())));
 4974                }
 4975                let debugger_flag = cx.has_flag::<Debugger>();
 4976                let code_actions_task = editor.prepare_code_actions_task(&action, window, cx);
 4977                Some(cx.spawn_in(window, async move |editor, cx| {
 4978                    if let Some((buffer, code_action_contents)) = code_actions_task.await {
 4979                        let spawn_straight_away =
 4980                            code_action_contents.tasks.as_ref().map_or(false, |tasks| {
 4981                                tasks
 4982                                    .templates
 4983                                    .iter()
 4984                                    .filter(|task| {
 4985                                        if matches!(task.1.task_type(), task::TaskType::Debug(_)) {
 4986                                            debugger_flag
 4987                                        } else {
 4988                                            true
 4989                                        }
 4990                                    })
 4991                                    .count()
 4992                                    == 1
 4993                            }) && code_action_contents
 4994                                .actions
 4995                                .as_ref()
 4996                                .map_or(true, |actions| actions.is_empty());
 4997                        if let Ok(task) = editor.update_in(cx, |editor, window, cx| {
 4998                            *editor.context_menu.borrow_mut() =
 4999                                Some(CodeContextMenu::CodeActions(CodeActionsMenu {
 5000                                    buffer,
 5001                                    actions: code_action_contents,
 5002                                    selected_item: Default::default(),
 5003                                    scroll_handle: UniformListScrollHandle::default(),
 5004                                    deployed_from_indicator,
 5005                                }));
 5006                            if spawn_straight_away {
 5007                                if let Some(task) = editor.confirm_code_action(
 5008                                    &ConfirmCodeAction {
 5009                                        item_ix: Some(0),
 5010                                        from_mouse_context_menu: false,
 5011                                    },
 5012                                    window,
 5013                                    cx,
 5014                                ) {
 5015                                    cx.notify();
 5016                                    return task;
 5017                                }
 5018                            }
 5019                            cx.notify();
 5020                            Task::ready(Ok(()))
 5021                        }) {
 5022                            task.await
 5023                        } else {
 5024                            Ok(())
 5025                        }
 5026                    } else {
 5027                        Ok(())
 5028                    }
 5029                }))
 5030            })?;
 5031            if let Some(task) = context_menu_task {
 5032                task.await?;
 5033            }
 5034
 5035            Ok::<_, anyhow::Error>(())
 5036        })
 5037        .detach_and_log_err(cx);
 5038    }
 5039
 5040    pub fn confirm_code_action(
 5041        &mut self,
 5042        action: &ConfirmCodeAction,
 5043        window: &mut Window,
 5044        cx: &mut Context<Self>,
 5045    ) -> Option<Task<Result<()>>> {
 5046        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
 5047
 5048        let (action, buffer) = if action.from_mouse_context_menu {
 5049            if let Some(menu) = self.mouse_context_menu.take() {
 5050                let code_action = menu.code_action?;
 5051                let index = action.item_ix?;
 5052                let action = code_action.actions.get(index)?;
 5053                (action, code_action.buffer)
 5054            } else {
 5055                return None;
 5056            }
 5057        } else {
 5058            if let CodeContextMenu::CodeActions(menu) = self.hide_context_menu(window, cx)? {
 5059                let action_ix = action.item_ix.unwrap_or(menu.selected_item);
 5060                let action = menu.actions.get(action_ix)?;
 5061                let buffer = menu.buffer;
 5062                (action, buffer)
 5063            } else {
 5064                return None;
 5065            }
 5066        };
 5067
 5068        let title = action.label();
 5069        let workspace = self.workspace()?;
 5070
 5071        match action {
 5072            CodeActionsItem::Task(task_source_kind, resolved_task) => {
 5073                match resolved_task.task_type() {
 5074                    task::TaskType::Script => workspace.update(cx, |workspace, cx| {
 5075                        workspace::tasks::schedule_resolved_task(
 5076                            workspace,
 5077                            task_source_kind,
 5078                            resolved_task,
 5079                            false,
 5080                            cx,
 5081                        );
 5082
 5083                        Some(Task::ready(Ok(())))
 5084                    }),
 5085                    task::TaskType::Debug(debug_args) => {
 5086                        if debug_args.locator.is_some() {
 5087                            workspace.update(cx, |workspace, cx| {
 5088                                workspace::tasks::schedule_resolved_task(
 5089                                    workspace,
 5090                                    task_source_kind,
 5091                                    resolved_task,
 5092                                    false,
 5093                                    cx,
 5094                                );
 5095                            });
 5096
 5097                            return Some(Task::ready(Ok(())));
 5098                        }
 5099
 5100                        if let Some(project) = self.project.as_ref() {
 5101                            project
 5102                                .update(cx, |project, cx| {
 5103                                    project.start_debug_session(
 5104                                        resolved_task.resolved_debug_adapter_config().unwrap(),
 5105                                        cx,
 5106                                    )
 5107                                })
 5108                                .detach_and_log_err(cx);
 5109                            Some(Task::ready(Ok(())))
 5110                        } else {
 5111                            Some(Task::ready(Ok(())))
 5112                        }
 5113                    }
 5114                }
 5115            }
 5116            CodeActionsItem::CodeAction {
 5117                excerpt_id,
 5118                action,
 5119                provider,
 5120            } => {
 5121                let apply_code_action =
 5122                    provider.apply_code_action(buffer, action, excerpt_id, true, window, cx);
 5123                let workspace = workspace.downgrade();
 5124                Some(cx.spawn_in(window, async move |editor, cx| {
 5125                    let project_transaction = apply_code_action.await?;
 5126                    Self::open_project_transaction(
 5127                        &editor,
 5128                        workspace,
 5129                        project_transaction,
 5130                        title,
 5131                        cx,
 5132                    )
 5133                    .await
 5134                }))
 5135            }
 5136        }
 5137    }
 5138
 5139    pub async fn open_project_transaction(
 5140        this: &WeakEntity<Editor>,
 5141        workspace: WeakEntity<Workspace>,
 5142        transaction: ProjectTransaction,
 5143        title: String,
 5144        cx: &mut AsyncWindowContext,
 5145    ) -> Result<()> {
 5146        let mut entries = transaction.0.into_iter().collect::<Vec<_>>();
 5147        cx.update(|_, cx| {
 5148            entries.sort_unstable_by_key(|(buffer, _)| {
 5149                buffer.read(cx).file().map(|f| f.path().clone())
 5150            });
 5151        })?;
 5152
 5153        // If the project transaction's edits are all contained within this editor, then
 5154        // avoid opening a new editor to display them.
 5155
 5156        if let Some((buffer, transaction)) = entries.first() {
 5157            if entries.len() == 1 {
 5158                let excerpt = this.update(cx, |editor, cx| {
 5159                    editor
 5160                        .buffer()
 5161                        .read(cx)
 5162                        .excerpt_containing(editor.selections.newest_anchor().head(), cx)
 5163                })?;
 5164                if let Some((_, excerpted_buffer, excerpt_range)) = excerpt {
 5165                    if excerpted_buffer == *buffer {
 5166                        let all_edits_within_excerpt = buffer.read_with(cx, |buffer, _| {
 5167                            let excerpt_range = excerpt_range.to_offset(buffer);
 5168                            buffer
 5169                                .edited_ranges_for_transaction::<usize>(transaction)
 5170                                .all(|range| {
 5171                                    excerpt_range.start <= range.start
 5172                                        && excerpt_range.end >= range.end
 5173                                })
 5174                        })?;
 5175
 5176                        if all_edits_within_excerpt {
 5177                            return Ok(());
 5178                        }
 5179                    }
 5180                }
 5181            }
 5182        } else {
 5183            return Ok(());
 5184        }
 5185
 5186        let mut ranges_to_highlight = Vec::new();
 5187        let excerpt_buffer = cx.new(|cx| {
 5188            let mut multibuffer = MultiBuffer::new(Capability::ReadWrite).with_title(title);
 5189            for (buffer_handle, transaction) in &entries {
 5190                let edited_ranges = buffer_handle
 5191                    .read(cx)
 5192                    .edited_ranges_for_transaction::<Point>(transaction)
 5193                    .collect::<Vec<_>>();
 5194                let (ranges, _) = multibuffer.set_excerpts_for_path(
 5195                    PathKey::for_buffer(buffer_handle, cx),
 5196                    buffer_handle.clone(),
 5197                    edited_ranges,
 5198                    DEFAULT_MULTIBUFFER_CONTEXT,
 5199                    cx,
 5200                );
 5201
 5202                ranges_to_highlight.extend(ranges);
 5203            }
 5204            multibuffer.push_transaction(entries.iter().map(|(b, t)| (b, t)), cx);
 5205            multibuffer
 5206        })?;
 5207
 5208        workspace.update_in(cx, |workspace, window, cx| {
 5209            let project = workspace.project().clone();
 5210            let editor =
 5211                cx.new(|cx| Editor::for_multibuffer(excerpt_buffer, Some(project), window, cx));
 5212            workspace.add_item_to_active_pane(Box::new(editor.clone()), None, true, window, cx);
 5213            editor.update(cx, |editor, cx| {
 5214                editor.highlight_background::<Self>(
 5215                    &ranges_to_highlight,
 5216                    |theme| theme.editor_highlighted_line_background,
 5217                    cx,
 5218                );
 5219            });
 5220        })?;
 5221
 5222        Ok(())
 5223    }
 5224
 5225    pub fn clear_code_action_providers(&mut self) {
 5226        self.code_action_providers.clear();
 5227        self.available_code_actions.take();
 5228    }
 5229
 5230    pub fn add_code_action_provider(
 5231        &mut self,
 5232        provider: Rc<dyn CodeActionProvider>,
 5233        window: &mut Window,
 5234        cx: &mut Context<Self>,
 5235    ) {
 5236        if self
 5237            .code_action_providers
 5238            .iter()
 5239            .any(|existing_provider| existing_provider.id() == provider.id())
 5240        {
 5241            return;
 5242        }
 5243
 5244        self.code_action_providers.push(provider);
 5245        self.refresh_code_actions(window, cx);
 5246    }
 5247
 5248    pub fn remove_code_action_provider(
 5249        &mut self,
 5250        id: Arc<str>,
 5251        window: &mut Window,
 5252        cx: &mut Context<Self>,
 5253    ) {
 5254        self.code_action_providers
 5255            .retain(|provider| provider.id() != id);
 5256        self.refresh_code_actions(window, cx);
 5257    }
 5258
 5259    fn refresh_code_actions(&mut self, window: &mut Window, cx: &mut Context<Self>) -> Option<()> {
 5260        let newest_selection = self.selections.newest_anchor().clone();
 5261        let newest_selection_adjusted = self.selections.newest_adjusted(cx).clone();
 5262        let buffer = self.buffer.read(cx);
 5263        if newest_selection.head().diff_base_anchor.is_some() {
 5264            return None;
 5265        }
 5266        let (start_buffer, start) =
 5267            buffer.text_anchor_for_position(newest_selection_adjusted.start, cx)?;
 5268        let (end_buffer, end) =
 5269            buffer.text_anchor_for_position(newest_selection_adjusted.end, cx)?;
 5270        if start_buffer != end_buffer {
 5271            return None;
 5272        }
 5273
 5274        self.code_actions_task = Some(cx.spawn_in(window, async move |this, cx| {
 5275            cx.background_executor()
 5276                .timer(CODE_ACTIONS_DEBOUNCE_TIMEOUT)
 5277                .await;
 5278
 5279            let (providers, tasks) = this.update_in(cx, |this, window, cx| {
 5280                let providers = this.code_action_providers.clone();
 5281                let tasks = this
 5282                    .code_action_providers
 5283                    .iter()
 5284                    .map(|provider| provider.code_actions(&start_buffer, start..end, window, cx))
 5285                    .collect::<Vec<_>>();
 5286                (providers, tasks)
 5287            })?;
 5288
 5289            let mut actions = Vec::new();
 5290            for (provider, provider_actions) in
 5291                providers.into_iter().zip(future::join_all(tasks).await)
 5292            {
 5293                if let Some(provider_actions) = provider_actions.log_err() {
 5294                    actions.extend(provider_actions.into_iter().map(|action| {
 5295                        AvailableCodeAction {
 5296                            excerpt_id: newest_selection.start.excerpt_id,
 5297                            action,
 5298                            provider: provider.clone(),
 5299                        }
 5300                    }));
 5301                }
 5302            }
 5303
 5304            this.update(cx, |this, cx| {
 5305                this.available_code_actions = if actions.is_empty() {
 5306                    None
 5307                } else {
 5308                    Some((
 5309                        Location {
 5310                            buffer: start_buffer,
 5311                            range: start..end,
 5312                        },
 5313                        actions.into(),
 5314                    ))
 5315                };
 5316                cx.notify();
 5317            })
 5318        }));
 5319        None
 5320    }
 5321
 5322    fn start_inline_blame_timer(&mut self, window: &mut Window, cx: &mut Context<Self>) {
 5323        if let Some(delay) = ProjectSettings::get_global(cx).git.inline_blame_delay() {
 5324            self.show_git_blame_inline = false;
 5325
 5326            self.show_git_blame_inline_delay_task =
 5327                Some(cx.spawn_in(window, async move |this, cx| {
 5328                    cx.background_executor().timer(delay).await;
 5329
 5330                    this.update(cx, |this, cx| {
 5331                        this.show_git_blame_inline = true;
 5332                        cx.notify();
 5333                    })
 5334                    .log_err();
 5335                }));
 5336        }
 5337    }
 5338
 5339    fn refresh_document_highlights(&mut self, cx: &mut Context<Self>) -> Option<()> {
 5340        if self.pending_rename.is_some() {
 5341            return None;
 5342        }
 5343
 5344        let provider = self.semantics_provider.clone()?;
 5345        let buffer = self.buffer.read(cx);
 5346        let newest_selection = self.selections.newest_anchor().clone();
 5347        let cursor_position = newest_selection.head();
 5348        let (cursor_buffer, cursor_buffer_position) =
 5349            buffer.text_anchor_for_position(cursor_position, cx)?;
 5350        let (tail_buffer, _) = buffer.text_anchor_for_position(newest_selection.tail(), cx)?;
 5351        if cursor_buffer != tail_buffer {
 5352            return None;
 5353        }
 5354        let debounce = EditorSettings::get_global(cx).lsp_highlight_debounce;
 5355        self.document_highlights_task = Some(cx.spawn(async move |this, cx| {
 5356            cx.background_executor()
 5357                .timer(Duration::from_millis(debounce))
 5358                .await;
 5359
 5360            let highlights = if let Some(highlights) = cx
 5361                .update(|cx| {
 5362                    provider.document_highlights(&cursor_buffer, cursor_buffer_position, cx)
 5363                })
 5364                .ok()
 5365                .flatten()
 5366            {
 5367                highlights.await.log_err()
 5368            } else {
 5369                None
 5370            };
 5371
 5372            if let Some(highlights) = highlights {
 5373                this.update(cx, |this, cx| {
 5374                    if this.pending_rename.is_some() {
 5375                        return;
 5376                    }
 5377
 5378                    let buffer_id = cursor_position.buffer_id;
 5379                    let buffer = this.buffer.read(cx);
 5380                    if !buffer
 5381                        .text_anchor_for_position(cursor_position, cx)
 5382                        .map_or(false, |(buffer, _)| buffer == cursor_buffer)
 5383                    {
 5384                        return;
 5385                    }
 5386
 5387                    let cursor_buffer_snapshot = cursor_buffer.read(cx);
 5388                    let mut write_ranges = Vec::new();
 5389                    let mut read_ranges = Vec::new();
 5390                    for highlight in highlights {
 5391                        for (excerpt_id, excerpt_range) in
 5392                            buffer.excerpts_for_buffer(cursor_buffer.read(cx).remote_id(), cx)
 5393                        {
 5394                            let start = highlight
 5395                                .range
 5396                                .start
 5397                                .max(&excerpt_range.context.start, cursor_buffer_snapshot);
 5398                            let end = highlight
 5399                                .range
 5400                                .end
 5401                                .min(&excerpt_range.context.end, cursor_buffer_snapshot);
 5402                            if start.cmp(&end, cursor_buffer_snapshot).is_ge() {
 5403                                continue;
 5404                            }
 5405
 5406                            let range = Anchor {
 5407                                buffer_id,
 5408                                excerpt_id,
 5409                                text_anchor: start,
 5410                                diff_base_anchor: None,
 5411                            }..Anchor {
 5412                                buffer_id,
 5413                                excerpt_id,
 5414                                text_anchor: end,
 5415                                diff_base_anchor: None,
 5416                            };
 5417                            if highlight.kind == lsp::DocumentHighlightKind::WRITE {
 5418                                write_ranges.push(range);
 5419                            } else {
 5420                                read_ranges.push(range);
 5421                            }
 5422                        }
 5423                    }
 5424
 5425                    this.highlight_background::<DocumentHighlightRead>(
 5426                        &read_ranges,
 5427                        |theme| theme.editor_document_highlight_read_background,
 5428                        cx,
 5429                    );
 5430                    this.highlight_background::<DocumentHighlightWrite>(
 5431                        &write_ranges,
 5432                        |theme| theme.editor_document_highlight_write_background,
 5433                        cx,
 5434                    );
 5435                    cx.notify();
 5436                })
 5437                .log_err();
 5438            }
 5439        }));
 5440        None
 5441    }
 5442
 5443    pub fn refresh_selected_text_highlights(
 5444        &mut self,
 5445        window: &mut Window,
 5446        cx: &mut Context<Editor>,
 5447    ) {
 5448        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 5449            return;
 5450        }
 5451        self.selection_highlight_task.take();
 5452        if !EditorSettings::get_global(cx).selection_highlight {
 5453            self.clear_background_highlights::<SelectedTextHighlight>(cx);
 5454            return;
 5455        }
 5456        if self.selections.count() != 1 || self.selections.line_mode {
 5457            self.clear_background_highlights::<SelectedTextHighlight>(cx);
 5458            return;
 5459        }
 5460        let selection = self.selections.newest::<Point>(cx);
 5461        if selection.is_empty() || selection.start.row != selection.end.row {
 5462            self.clear_background_highlights::<SelectedTextHighlight>(cx);
 5463            return;
 5464        }
 5465        let debounce = EditorSettings::get_global(cx).selection_highlight_debounce;
 5466        self.selection_highlight_task = Some(cx.spawn_in(window, async move |editor, cx| {
 5467            cx.background_executor()
 5468                .timer(Duration::from_millis(debounce))
 5469                .await;
 5470            let Some(Some(matches_task)) = editor
 5471                .update_in(cx, |editor, _, cx| {
 5472                    if editor.selections.count() != 1 || editor.selections.line_mode {
 5473                        editor.clear_background_highlights::<SelectedTextHighlight>(cx);
 5474                        return None;
 5475                    }
 5476                    let selection = editor.selections.newest::<Point>(cx);
 5477                    if selection.is_empty() || selection.start.row != selection.end.row {
 5478                        editor.clear_background_highlights::<SelectedTextHighlight>(cx);
 5479                        return None;
 5480                    }
 5481                    let buffer = editor.buffer().read(cx).snapshot(cx);
 5482                    let query = buffer.text_for_range(selection.range()).collect::<String>();
 5483                    if query.trim().is_empty() {
 5484                        editor.clear_background_highlights::<SelectedTextHighlight>(cx);
 5485                        return None;
 5486                    }
 5487                    Some(cx.background_spawn(async move {
 5488                        let mut ranges = Vec::new();
 5489                        let selection_anchors = selection.range().to_anchors(&buffer);
 5490                        for range in [buffer.anchor_before(0)..buffer.anchor_after(buffer.len())] {
 5491                            for (search_buffer, search_range, excerpt_id) in
 5492                                buffer.range_to_buffer_ranges(range)
 5493                            {
 5494                                ranges.extend(
 5495                                    project::search::SearchQuery::text(
 5496                                        query.clone(),
 5497                                        false,
 5498                                        false,
 5499                                        false,
 5500                                        Default::default(),
 5501                                        Default::default(),
 5502                                        None,
 5503                                    )
 5504                                    .unwrap()
 5505                                    .search(search_buffer, Some(search_range.clone()))
 5506                                    .await
 5507                                    .into_iter()
 5508                                    .filter_map(
 5509                                        |match_range| {
 5510                                            let start = search_buffer.anchor_after(
 5511                                                search_range.start + match_range.start,
 5512                                            );
 5513                                            let end = search_buffer.anchor_before(
 5514                                                search_range.start + match_range.end,
 5515                                            );
 5516                                            let range = Anchor::range_in_buffer(
 5517                                                excerpt_id,
 5518                                                search_buffer.remote_id(),
 5519                                                start..end,
 5520                                            );
 5521                                            (range != selection_anchors).then_some(range)
 5522                                        },
 5523                                    ),
 5524                                );
 5525                            }
 5526                        }
 5527                        ranges
 5528                    }))
 5529                })
 5530                .log_err()
 5531            else {
 5532                return;
 5533            };
 5534            let matches = matches_task.await;
 5535            editor
 5536                .update_in(cx, |editor, _, cx| {
 5537                    editor.clear_background_highlights::<SelectedTextHighlight>(cx);
 5538                    if !matches.is_empty() {
 5539                        editor.highlight_background::<SelectedTextHighlight>(
 5540                            &matches,
 5541                            |theme| theme.editor_document_highlight_bracket_background,
 5542                            cx,
 5543                        )
 5544                    }
 5545                })
 5546                .log_err();
 5547        }));
 5548    }
 5549
 5550    pub fn refresh_inline_completion(
 5551        &mut self,
 5552        debounce: bool,
 5553        user_requested: bool,
 5554        window: &mut Window,
 5555        cx: &mut Context<Self>,
 5556    ) -> Option<()> {
 5557        let provider = self.edit_prediction_provider()?;
 5558        let cursor = self.selections.newest_anchor().head();
 5559        let (buffer, cursor_buffer_position) =
 5560            self.buffer.read(cx).text_anchor_for_position(cursor, cx)?;
 5561
 5562        if !self.edit_predictions_enabled_in_buffer(&buffer, cursor_buffer_position, cx) {
 5563            self.discard_inline_completion(false, cx);
 5564            return None;
 5565        }
 5566
 5567        if !user_requested
 5568            && (!self.should_show_edit_predictions()
 5569                || !self.is_focused(window)
 5570                || buffer.read(cx).is_empty())
 5571        {
 5572            self.discard_inline_completion(false, cx);
 5573            return None;
 5574        }
 5575
 5576        self.update_visible_inline_completion(window, cx);
 5577        provider.refresh(
 5578            self.project.clone(),
 5579            buffer,
 5580            cursor_buffer_position,
 5581            debounce,
 5582            cx,
 5583        );
 5584        Some(())
 5585    }
 5586
 5587    fn show_edit_predictions_in_menu(&self) -> bool {
 5588        match self.edit_prediction_settings {
 5589            EditPredictionSettings::Disabled => false,
 5590            EditPredictionSettings::Enabled { show_in_menu, .. } => show_in_menu,
 5591        }
 5592    }
 5593
 5594    pub fn edit_predictions_enabled(&self) -> bool {
 5595        match self.edit_prediction_settings {
 5596            EditPredictionSettings::Disabled => false,
 5597            EditPredictionSettings::Enabled { .. } => true,
 5598        }
 5599    }
 5600
 5601    fn edit_prediction_requires_modifier(&self) -> bool {
 5602        match self.edit_prediction_settings {
 5603            EditPredictionSettings::Disabled => false,
 5604            EditPredictionSettings::Enabled {
 5605                preview_requires_modifier,
 5606                ..
 5607            } => preview_requires_modifier,
 5608        }
 5609    }
 5610
 5611    pub fn update_edit_prediction_settings(&mut self, cx: &mut Context<Self>) {
 5612        if self.edit_prediction_provider.is_none() {
 5613            self.edit_prediction_settings = EditPredictionSettings::Disabled;
 5614        } else {
 5615            let selection = self.selections.newest_anchor();
 5616            let cursor = selection.head();
 5617
 5618            if let Some((buffer, cursor_buffer_position)) =
 5619                self.buffer.read(cx).text_anchor_for_position(cursor, cx)
 5620            {
 5621                self.edit_prediction_settings =
 5622                    self.edit_prediction_settings_at_position(&buffer, cursor_buffer_position, cx);
 5623            }
 5624        }
 5625    }
 5626
 5627    fn edit_prediction_settings_at_position(
 5628        &self,
 5629        buffer: &Entity<Buffer>,
 5630        buffer_position: language::Anchor,
 5631        cx: &App,
 5632    ) -> EditPredictionSettings {
 5633        if !self.mode.is_full()
 5634            || !self.show_inline_completions_override.unwrap_or(true)
 5635            || self.inline_completions_disabled_in_scope(buffer, buffer_position, cx)
 5636        {
 5637            return EditPredictionSettings::Disabled;
 5638        }
 5639
 5640        let buffer = buffer.read(cx);
 5641
 5642        let file = buffer.file();
 5643
 5644        if !language_settings(buffer.language().map(|l| l.name()), file, cx).show_edit_predictions {
 5645            return EditPredictionSettings::Disabled;
 5646        };
 5647
 5648        let by_provider = matches!(
 5649            self.menu_inline_completions_policy,
 5650            MenuInlineCompletionsPolicy::ByProvider
 5651        );
 5652
 5653        let show_in_menu = by_provider
 5654            && self
 5655                .edit_prediction_provider
 5656                .as_ref()
 5657                .map_or(false, |provider| {
 5658                    provider.provider.show_completions_in_menu()
 5659                });
 5660
 5661        let preview_requires_modifier =
 5662            all_language_settings(file, cx).edit_predictions_mode() == EditPredictionsMode::Subtle;
 5663
 5664        EditPredictionSettings::Enabled {
 5665            show_in_menu,
 5666            preview_requires_modifier,
 5667        }
 5668    }
 5669
 5670    fn should_show_edit_predictions(&self) -> bool {
 5671        self.snippet_stack.is_empty() && self.edit_predictions_enabled()
 5672    }
 5673
 5674    pub fn edit_prediction_preview_is_active(&self) -> bool {
 5675        matches!(
 5676            self.edit_prediction_preview,
 5677            EditPredictionPreview::Active { .. }
 5678        )
 5679    }
 5680
 5681    pub fn edit_predictions_enabled_at_cursor(&self, cx: &App) -> bool {
 5682        let cursor = self.selections.newest_anchor().head();
 5683        if let Some((buffer, cursor_position)) =
 5684            self.buffer.read(cx).text_anchor_for_position(cursor, cx)
 5685        {
 5686            self.edit_predictions_enabled_in_buffer(&buffer, cursor_position, cx)
 5687        } else {
 5688            false
 5689        }
 5690    }
 5691
 5692    fn edit_predictions_enabled_in_buffer(
 5693        &self,
 5694        buffer: &Entity<Buffer>,
 5695        buffer_position: language::Anchor,
 5696        cx: &App,
 5697    ) -> bool {
 5698        maybe!({
 5699            if self.read_only(cx) {
 5700                return Some(false);
 5701            }
 5702            let provider = self.edit_prediction_provider()?;
 5703            if !provider.is_enabled(&buffer, buffer_position, cx) {
 5704                return Some(false);
 5705            }
 5706            let buffer = buffer.read(cx);
 5707            let Some(file) = buffer.file() else {
 5708                return Some(true);
 5709            };
 5710            let settings = all_language_settings(Some(file), cx);
 5711            Some(settings.edit_predictions_enabled_for_file(file, cx))
 5712        })
 5713        .unwrap_or(false)
 5714    }
 5715
 5716    fn cycle_inline_completion(
 5717        &mut self,
 5718        direction: Direction,
 5719        window: &mut Window,
 5720        cx: &mut Context<Self>,
 5721    ) -> Option<()> {
 5722        let provider = self.edit_prediction_provider()?;
 5723        let cursor = self.selections.newest_anchor().head();
 5724        let (buffer, cursor_buffer_position) =
 5725            self.buffer.read(cx).text_anchor_for_position(cursor, cx)?;
 5726        if self.inline_completions_hidden_for_vim_mode || !self.should_show_edit_predictions() {
 5727            return None;
 5728        }
 5729
 5730        provider.cycle(buffer, cursor_buffer_position, direction, cx);
 5731        self.update_visible_inline_completion(window, cx);
 5732
 5733        Some(())
 5734    }
 5735
 5736    pub fn show_inline_completion(
 5737        &mut self,
 5738        _: &ShowEditPrediction,
 5739        window: &mut Window,
 5740        cx: &mut Context<Self>,
 5741    ) {
 5742        if !self.has_active_inline_completion() {
 5743            self.refresh_inline_completion(false, true, window, cx);
 5744            return;
 5745        }
 5746
 5747        self.update_visible_inline_completion(window, cx);
 5748    }
 5749
 5750    pub fn display_cursor_names(
 5751        &mut self,
 5752        _: &DisplayCursorNames,
 5753        window: &mut Window,
 5754        cx: &mut Context<Self>,
 5755    ) {
 5756        self.show_cursor_names(window, cx);
 5757    }
 5758
 5759    fn show_cursor_names(&mut self, window: &mut Window, cx: &mut Context<Self>) {
 5760        self.show_cursor_names = true;
 5761        cx.notify();
 5762        cx.spawn_in(window, async move |this, cx| {
 5763            cx.background_executor().timer(CURSORS_VISIBLE_FOR).await;
 5764            this.update(cx, |this, cx| {
 5765                this.show_cursor_names = false;
 5766                cx.notify()
 5767            })
 5768            .ok()
 5769        })
 5770        .detach();
 5771    }
 5772
 5773    pub fn next_edit_prediction(
 5774        &mut self,
 5775        _: &NextEditPrediction,
 5776        window: &mut Window,
 5777        cx: &mut Context<Self>,
 5778    ) {
 5779        if self.has_active_inline_completion() {
 5780            self.cycle_inline_completion(Direction::Next, window, cx);
 5781        } else {
 5782            let is_copilot_disabled = self
 5783                .refresh_inline_completion(false, true, window, cx)
 5784                .is_none();
 5785            if is_copilot_disabled {
 5786                cx.propagate();
 5787            }
 5788        }
 5789    }
 5790
 5791    pub fn previous_edit_prediction(
 5792        &mut self,
 5793        _: &PreviousEditPrediction,
 5794        window: &mut Window,
 5795        cx: &mut Context<Self>,
 5796    ) {
 5797        if self.has_active_inline_completion() {
 5798            self.cycle_inline_completion(Direction::Prev, window, cx);
 5799        } else {
 5800            let is_copilot_disabled = self
 5801                .refresh_inline_completion(false, true, window, cx)
 5802                .is_none();
 5803            if is_copilot_disabled {
 5804                cx.propagate();
 5805            }
 5806        }
 5807    }
 5808
 5809    pub fn accept_edit_prediction(
 5810        &mut self,
 5811        _: &AcceptEditPrediction,
 5812        window: &mut Window,
 5813        cx: &mut Context<Self>,
 5814    ) {
 5815        if self.show_edit_predictions_in_menu() {
 5816            self.hide_context_menu(window, cx);
 5817        }
 5818
 5819        let Some(active_inline_completion) = self.active_inline_completion.as_ref() else {
 5820            return;
 5821        };
 5822
 5823        self.report_inline_completion_event(
 5824            active_inline_completion.completion_id.clone(),
 5825            true,
 5826            cx,
 5827        );
 5828
 5829        match &active_inline_completion.completion {
 5830            InlineCompletion::Move { target, .. } => {
 5831                let target = *target;
 5832
 5833                if let Some(position_map) = &self.last_position_map {
 5834                    if position_map
 5835                        .visible_row_range
 5836                        .contains(&target.to_display_point(&position_map.snapshot).row())
 5837                        || !self.edit_prediction_requires_modifier()
 5838                    {
 5839                        self.unfold_ranges(&[target..target], true, false, cx);
 5840                        // Note that this is also done in vim's handler of the Tab action.
 5841                        self.change_selections(
 5842                            Some(Autoscroll::newest()),
 5843                            window,
 5844                            cx,
 5845                            |selections| {
 5846                                selections.select_anchor_ranges([target..target]);
 5847                            },
 5848                        );
 5849                        self.clear_row_highlights::<EditPredictionPreview>();
 5850
 5851                        self.edit_prediction_preview
 5852                            .set_previous_scroll_position(None);
 5853                    } else {
 5854                        self.edit_prediction_preview
 5855                            .set_previous_scroll_position(Some(
 5856                                position_map.snapshot.scroll_anchor,
 5857                            ));
 5858
 5859                        self.highlight_rows::<EditPredictionPreview>(
 5860                            target..target,
 5861                            cx.theme().colors().editor_highlighted_line_background,
 5862                            true,
 5863                            cx,
 5864                        );
 5865                        self.request_autoscroll(Autoscroll::fit(), cx);
 5866                    }
 5867                }
 5868            }
 5869            InlineCompletion::Edit { edits, .. } => {
 5870                if let Some(provider) = self.edit_prediction_provider() {
 5871                    provider.accept(cx);
 5872                }
 5873
 5874                let snapshot = self.buffer.read(cx).snapshot(cx);
 5875                let last_edit_end = edits.last().unwrap().0.end.bias_right(&snapshot);
 5876
 5877                self.buffer.update(cx, |buffer, cx| {
 5878                    buffer.edit(edits.iter().cloned(), None, cx)
 5879                });
 5880
 5881                self.change_selections(None, window, cx, |s| {
 5882                    s.select_anchor_ranges([last_edit_end..last_edit_end])
 5883                });
 5884
 5885                self.update_visible_inline_completion(window, cx);
 5886                if self.active_inline_completion.is_none() {
 5887                    self.refresh_inline_completion(true, true, window, cx);
 5888                }
 5889
 5890                cx.notify();
 5891            }
 5892        }
 5893
 5894        self.edit_prediction_requires_modifier_in_indent_conflict = false;
 5895    }
 5896
 5897    pub fn accept_partial_inline_completion(
 5898        &mut self,
 5899        _: &AcceptPartialEditPrediction,
 5900        window: &mut Window,
 5901        cx: &mut Context<Self>,
 5902    ) {
 5903        let Some(active_inline_completion) = self.active_inline_completion.as_ref() else {
 5904            return;
 5905        };
 5906        if self.selections.count() != 1 {
 5907            return;
 5908        }
 5909
 5910        self.report_inline_completion_event(
 5911            active_inline_completion.completion_id.clone(),
 5912            true,
 5913            cx,
 5914        );
 5915
 5916        match &active_inline_completion.completion {
 5917            InlineCompletion::Move { target, .. } => {
 5918                let target = *target;
 5919                self.change_selections(Some(Autoscroll::newest()), window, cx, |selections| {
 5920                    selections.select_anchor_ranges([target..target]);
 5921                });
 5922            }
 5923            InlineCompletion::Edit { edits, .. } => {
 5924                // Find an insertion that starts at the cursor position.
 5925                let snapshot = self.buffer.read(cx).snapshot(cx);
 5926                let cursor_offset = self.selections.newest::<usize>(cx).head();
 5927                let insertion = edits.iter().find_map(|(range, text)| {
 5928                    let range = range.to_offset(&snapshot);
 5929                    if range.is_empty() && range.start == cursor_offset {
 5930                        Some(text)
 5931                    } else {
 5932                        None
 5933                    }
 5934                });
 5935
 5936                if let Some(text) = insertion {
 5937                    let mut partial_completion = text
 5938                        .chars()
 5939                        .by_ref()
 5940                        .take_while(|c| c.is_alphabetic())
 5941                        .collect::<String>();
 5942                    if partial_completion.is_empty() {
 5943                        partial_completion = text
 5944                            .chars()
 5945                            .by_ref()
 5946                            .take_while(|c| c.is_whitespace() || !c.is_alphabetic())
 5947                            .collect::<String>();
 5948                    }
 5949
 5950                    cx.emit(EditorEvent::InputHandled {
 5951                        utf16_range_to_replace: None,
 5952                        text: partial_completion.clone().into(),
 5953                    });
 5954
 5955                    self.insert_with_autoindent_mode(&partial_completion, None, window, cx);
 5956
 5957                    self.refresh_inline_completion(true, true, window, cx);
 5958                    cx.notify();
 5959                } else {
 5960                    self.accept_edit_prediction(&Default::default(), window, cx);
 5961                }
 5962            }
 5963        }
 5964    }
 5965
 5966    fn discard_inline_completion(
 5967        &mut self,
 5968        should_report_inline_completion_event: bool,
 5969        cx: &mut Context<Self>,
 5970    ) -> bool {
 5971        if should_report_inline_completion_event {
 5972            let completion_id = self
 5973                .active_inline_completion
 5974                .as_ref()
 5975                .and_then(|active_completion| active_completion.completion_id.clone());
 5976
 5977            self.report_inline_completion_event(completion_id, false, cx);
 5978        }
 5979
 5980        if let Some(provider) = self.edit_prediction_provider() {
 5981            provider.discard(cx);
 5982        }
 5983
 5984        self.take_active_inline_completion(cx)
 5985    }
 5986
 5987    fn report_inline_completion_event(&self, id: Option<SharedString>, accepted: bool, cx: &App) {
 5988        let Some(provider) = self.edit_prediction_provider() else {
 5989            return;
 5990        };
 5991
 5992        let Some((_, buffer, _)) = self
 5993            .buffer
 5994            .read(cx)
 5995            .excerpt_containing(self.selections.newest_anchor().head(), cx)
 5996        else {
 5997            return;
 5998        };
 5999
 6000        let extension = buffer
 6001            .read(cx)
 6002            .file()
 6003            .and_then(|file| Some(file.path().extension()?.to_string_lossy().to_string()));
 6004
 6005        let event_type = match accepted {
 6006            true => "Edit Prediction Accepted",
 6007            false => "Edit Prediction Discarded",
 6008        };
 6009        telemetry::event!(
 6010            event_type,
 6011            provider = provider.name(),
 6012            prediction_id = id,
 6013            suggestion_accepted = accepted,
 6014            file_extension = extension,
 6015        );
 6016    }
 6017
 6018    pub fn has_active_inline_completion(&self) -> bool {
 6019        self.active_inline_completion.is_some()
 6020    }
 6021
 6022    fn take_active_inline_completion(&mut self, cx: &mut Context<Self>) -> bool {
 6023        let Some(active_inline_completion) = self.active_inline_completion.take() else {
 6024            return false;
 6025        };
 6026
 6027        self.splice_inlays(&active_inline_completion.inlay_ids, Default::default(), cx);
 6028        self.clear_highlights::<InlineCompletionHighlight>(cx);
 6029        self.stale_inline_completion_in_menu = Some(active_inline_completion);
 6030        true
 6031    }
 6032
 6033    /// Returns true when we're displaying the edit prediction popover below the cursor
 6034    /// like we are not previewing and the LSP autocomplete menu is visible
 6035    /// or we are in `when_holding_modifier` mode.
 6036    pub fn edit_prediction_visible_in_cursor_popover(&self, has_completion: bool) -> bool {
 6037        if self.edit_prediction_preview_is_active()
 6038            || !self.show_edit_predictions_in_menu()
 6039            || !self.edit_predictions_enabled()
 6040        {
 6041            return false;
 6042        }
 6043
 6044        if self.has_visible_completions_menu() {
 6045            return true;
 6046        }
 6047
 6048        has_completion && self.edit_prediction_requires_modifier()
 6049    }
 6050
 6051    fn handle_modifiers_changed(
 6052        &mut self,
 6053        modifiers: Modifiers,
 6054        position_map: &PositionMap,
 6055        window: &mut Window,
 6056        cx: &mut Context<Self>,
 6057    ) {
 6058        if self.show_edit_predictions_in_menu() {
 6059            self.update_edit_prediction_preview(&modifiers, window, cx);
 6060        }
 6061
 6062        self.update_selection_mode(&modifiers, position_map, window, cx);
 6063
 6064        let mouse_position = window.mouse_position();
 6065        if !position_map.text_hitbox.is_hovered(window) {
 6066            return;
 6067        }
 6068
 6069        self.update_hovered_link(
 6070            position_map.point_for_position(mouse_position),
 6071            &position_map.snapshot,
 6072            modifiers,
 6073            window,
 6074            cx,
 6075        )
 6076    }
 6077
 6078    fn update_selection_mode(
 6079        &mut self,
 6080        modifiers: &Modifiers,
 6081        position_map: &PositionMap,
 6082        window: &mut Window,
 6083        cx: &mut Context<Self>,
 6084    ) {
 6085        if modifiers != &COLUMNAR_SELECTION_MODIFIERS || self.selections.pending.is_none() {
 6086            return;
 6087        }
 6088
 6089        let mouse_position = window.mouse_position();
 6090        let point_for_position = position_map.point_for_position(mouse_position);
 6091        let position = point_for_position.previous_valid;
 6092
 6093        self.select(
 6094            SelectPhase::BeginColumnar {
 6095                position,
 6096                reset: false,
 6097                goal_column: point_for_position.exact_unclipped.column(),
 6098            },
 6099            window,
 6100            cx,
 6101        );
 6102    }
 6103
 6104    fn update_edit_prediction_preview(
 6105        &mut self,
 6106        modifiers: &Modifiers,
 6107        window: &mut Window,
 6108        cx: &mut Context<Self>,
 6109    ) {
 6110        let accept_keybind = self.accept_edit_prediction_keybind(window, cx);
 6111        let Some(accept_keystroke) = accept_keybind.keystroke() else {
 6112            return;
 6113        };
 6114
 6115        if &accept_keystroke.modifiers == modifiers && accept_keystroke.modifiers.modified() {
 6116            if matches!(
 6117                self.edit_prediction_preview,
 6118                EditPredictionPreview::Inactive { .. }
 6119            ) {
 6120                self.edit_prediction_preview = EditPredictionPreview::Active {
 6121                    previous_scroll_position: None,
 6122                    since: Instant::now(),
 6123                };
 6124
 6125                self.update_visible_inline_completion(window, cx);
 6126                cx.notify();
 6127            }
 6128        } else if let EditPredictionPreview::Active {
 6129            previous_scroll_position,
 6130            since,
 6131        } = self.edit_prediction_preview
 6132        {
 6133            if let (Some(previous_scroll_position), Some(position_map)) =
 6134                (previous_scroll_position, self.last_position_map.as_ref())
 6135            {
 6136                self.set_scroll_position(
 6137                    previous_scroll_position
 6138                        .scroll_position(&position_map.snapshot.display_snapshot),
 6139                    window,
 6140                    cx,
 6141                );
 6142            }
 6143
 6144            self.edit_prediction_preview = EditPredictionPreview::Inactive {
 6145                released_too_fast: since.elapsed() < Duration::from_millis(200),
 6146            };
 6147            self.clear_row_highlights::<EditPredictionPreview>();
 6148            self.update_visible_inline_completion(window, cx);
 6149            cx.notify();
 6150        }
 6151    }
 6152
 6153    fn update_visible_inline_completion(
 6154        &mut self,
 6155        _window: &mut Window,
 6156        cx: &mut Context<Self>,
 6157    ) -> Option<()> {
 6158        let selection = self.selections.newest_anchor();
 6159        let cursor = selection.head();
 6160        let multibuffer = self.buffer.read(cx).snapshot(cx);
 6161        let offset_selection = selection.map(|endpoint| endpoint.to_offset(&multibuffer));
 6162        let excerpt_id = cursor.excerpt_id;
 6163
 6164        let show_in_menu = self.show_edit_predictions_in_menu();
 6165        let completions_menu_has_precedence = !show_in_menu
 6166            && (self.context_menu.borrow().is_some()
 6167                || (!self.completion_tasks.is_empty() && !self.has_active_inline_completion()));
 6168
 6169        if completions_menu_has_precedence
 6170            || !offset_selection.is_empty()
 6171            || self
 6172                .active_inline_completion
 6173                .as_ref()
 6174                .map_or(false, |completion| {
 6175                    let invalidation_range = completion.invalidation_range.to_offset(&multibuffer);
 6176                    let invalidation_range = invalidation_range.start..=invalidation_range.end;
 6177                    !invalidation_range.contains(&offset_selection.head())
 6178                })
 6179        {
 6180            self.discard_inline_completion(false, cx);
 6181            return None;
 6182        }
 6183
 6184        self.take_active_inline_completion(cx);
 6185        let Some(provider) = self.edit_prediction_provider() else {
 6186            self.edit_prediction_settings = EditPredictionSettings::Disabled;
 6187            return None;
 6188        };
 6189
 6190        let (buffer, cursor_buffer_position) =
 6191            self.buffer.read(cx).text_anchor_for_position(cursor, cx)?;
 6192
 6193        self.edit_prediction_settings =
 6194            self.edit_prediction_settings_at_position(&buffer, cursor_buffer_position, cx);
 6195
 6196        self.edit_prediction_indent_conflict = multibuffer.is_line_whitespace_upto(cursor);
 6197
 6198        if self.edit_prediction_indent_conflict {
 6199            let cursor_point = cursor.to_point(&multibuffer);
 6200
 6201            let indents = multibuffer.suggested_indents(cursor_point.row..cursor_point.row + 1, cx);
 6202
 6203            if let Some((_, indent)) = indents.iter().next() {
 6204                if indent.len == cursor_point.column {
 6205                    self.edit_prediction_indent_conflict = false;
 6206                }
 6207            }
 6208        }
 6209
 6210        let inline_completion = provider.suggest(&buffer, cursor_buffer_position, cx)?;
 6211        let edits = inline_completion
 6212            .edits
 6213            .into_iter()
 6214            .flat_map(|(range, new_text)| {
 6215                let start = multibuffer.anchor_in_excerpt(excerpt_id, range.start)?;
 6216                let end = multibuffer.anchor_in_excerpt(excerpt_id, range.end)?;
 6217                Some((start..end, new_text))
 6218            })
 6219            .collect::<Vec<_>>();
 6220        if edits.is_empty() {
 6221            return None;
 6222        }
 6223
 6224        let first_edit_start = edits.first().unwrap().0.start;
 6225        let first_edit_start_point = first_edit_start.to_point(&multibuffer);
 6226        let edit_start_row = first_edit_start_point.row.saturating_sub(2);
 6227
 6228        let last_edit_end = edits.last().unwrap().0.end;
 6229        let last_edit_end_point = last_edit_end.to_point(&multibuffer);
 6230        let edit_end_row = cmp::min(multibuffer.max_point().row, last_edit_end_point.row + 2);
 6231
 6232        let cursor_row = cursor.to_point(&multibuffer).row;
 6233
 6234        let snapshot = multibuffer.buffer_for_excerpt(excerpt_id).cloned()?;
 6235
 6236        let mut inlay_ids = Vec::new();
 6237        let invalidation_row_range;
 6238        let move_invalidation_row_range = if cursor_row < edit_start_row {
 6239            Some(cursor_row..edit_end_row)
 6240        } else if cursor_row > edit_end_row {
 6241            Some(edit_start_row..cursor_row)
 6242        } else {
 6243            None
 6244        };
 6245        let is_move =
 6246            move_invalidation_row_range.is_some() || self.inline_completions_hidden_for_vim_mode;
 6247        let completion = if is_move {
 6248            invalidation_row_range =
 6249                move_invalidation_row_range.unwrap_or(edit_start_row..edit_end_row);
 6250            let target = first_edit_start;
 6251            InlineCompletion::Move { target, snapshot }
 6252        } else {
 6253            let show_completions_in_buffer = !self.edit_prediction_visible_in_cursor_popover(true)
 6254                && !self.inline_completions_hidden_for_vim_mode;
 6255
 6256            if show_completions_in_buffer {
 6257                if edits
 6258                    .iter()
 6259                    .all(|(range, _)| range.to_offset(&multibuffer).is_empty())
 6260                {
 6261                    let mut inlays = Vec::new();
 6262                    for (range, new_text) in &edits {
 6263                        let inlay = Inlay::inline_completion(
 6264                            post_inc(&mut self.next_inlay_id),
 6265                            range.start,
 6266                            new_text.as_str(),
 6267                        );
 6268                        inlay_ids.push(inlay.id);
 6269                        inlays.push(inlay);
 6270                    }
 6271
 6272                    self.splice_inlays(&[], inlays, cx);
 6273                } else {
 6274                    let background_color = cx.theme().status().deleted_background;
 6275                    self.highlight_text::<InlineCompletionHighlight>(
 6276                        edits.iter().map(|(range, _)| range.clone()).collect(),
 6277                        HighlightStyle {
 6278                            background_color: Some(background_color),
 6279                            ..Default::default()
 6280                        },
 6281                        cx,
 6282                    );
 6283                }
 6284            }
 6285
 6286            invalidation_row_range = edit_start_row..edit_end_row;
 6287
 6288            let display_mode = if all_edits_insertions_or_deletions(&edits, &multibuffer) {
 6289                if provider.show_tab_accept_marker() {
 6290                    EditDisplayMode::TabAccept
 6291                } else {
 6292                    EditDisplayMode::Inline
 6293                }
 6294            } else {
 6295                EditDisplayMode::DiffPopover
 6296            };
 6297
 6298            InlineCompletion::Edit {
 6299                edits,
 6300                edit_preview: inline_completion.edit_preview,
 6301                display_mode,
 6302                snapshot,
 6303            }
 6304        };
 6305
 6306        let invalidation_range = multibuffer
 6307            .anchor_before(Point::new(invalidation_row_range.start, 0))
 6308            ..multibuffer.anchor_after(Point::new(
 6309                invalidation_row_range.end,
 6310                multibuffer.line_len(MultiBufferRow(invalidation_row_range.end)),
 6311            ));
 6312
 6313        self.stale_inline_completion_in_menu = None;
 6314        self.active_inline_completion = Some(InlineCompletionState {
 6315            inlay_ids,
 6316            completion,
 6317            completion_id: inline_completion.id,
 6318            invalidation_range,
 6319        });
 6320
 6321        cx.notify();
 6322
 6323        Some(())
 6324    }
 6325
 6326    pub fn edit_prediction_provider(&self) -> Option<Arc<dyn InlineCompletionProviderHandle>> {
 6327        Some(self.edit_prediction_provider.as_ref()?.provider.clone())
 6328    }
 6329
 6330    fn render_code_actions_indicator(
 6331        &self,
 6332        _style: &EditorStyle,
 6333        row: DisplayRow,
 6334        is_active: bool,
 6335        breakpoint: Option<&(Anchor, Breakpoint)>,
 6336        cx: &mut Context<Self>,
 6337    ) -> Option<IconButton> {
 6338        let color = Color::Muted;
 6339        let position = breakpoint.as_ref().map(|(anchor, _)| *anchor);
 6340        let show_tooltip = !self.context_menu_visible();
 6341
 6342        if self.available_code_actions.is_some() {
 6343            Some(
 6344                IconButton::new("code_actions_indicator", ui::IconName::Bolt)
 6345                    .shape(ui::IconButtonShape::Square)
 6346                    .icon_size(IconSize::XSmall)
 6347                    .icon_color(color)
 6348                    .toggle_state(is_active)
 6349                    .when(show_tooltip, |this| {
 6350                        this.tooltip({
 6351                            let focus_handle = self.focus_handle.clone();
 6352                            move |window, cx| {
 6353                                Tooltip::for_action_in(
 6354                                    "Toggle Code Actions",
 6355                                    &ToggleCodeActions {
 6356                                        deployed_from_indicator: None,
 6357                                    },
 6358                                    &focus_handle,
 6359                                    window,
 6360                                    cx,
 6361                                )
 6362                            }
 6363                        })
 6364                    })
 6365                    .on_click(cx.listener(move |editor, _e, window, cx| {
 6366                        window.focus(&editor.focus_handle(cx));
 6367                        editor.toggle_code_actions(
 6368                            &ToggleCodeActions {
 6369                                deployed_from_indicator: Some(row),
 6370                            },
 6371                            window,
 6372                            cx,
 6373                        );
 6374                    }))
 6375                    .on_right_click(cx.listener(move |editor, event: &ClickEvent, window, cx| {
 6376                        editor.set_breakpoint_context_menu(
 6377                            row,
 6378                            position,
 6379                            event.down.position,
 6380                            window,
 6381                            cx,
 6382                        );
 6383                    })),
 6384            )
 6385        } else {
 6386            None
 6387        }
 6388    }
 6389
 6390    fn clear_tasks(&mut self) {
 6391        self.tasks.clear()
 6392    }
 6393
 6394    fn insert_tasks(&mut self, key: (BufferId, BufferRow), value: RunnableTasks) {
 6395        if self.tasks.insert(key, value).is_some() {
 6396            // This case should hopefully be rare, but just in case...
 6397            log::error!(
 6398                "multiple different run targets found on a single line, only the last target will be rendered"
 6399            )
 6400        }
 6401    }
 6402
 6403    /// Get all display points of breakpoints that will be rendered within editor
 6404    ///
 6405    /// This function is used to handle overlaps between breakpoints and Code action/runner symbol.
 6406    /// It's also used to set the color of line numbers with breakpoints to the breakpoint color.
 6407    /// TODO debugger: Use this function to color toggle symbols that house nested breakpoints
 6408    fn active_breakpoints(
 6409        &self,
 6410        range: Range<DisplayRow>,
 6411        window: &mut Window,
 6412        cx: &mut Context<Self>,
 6413    ) -> HashMap<DisplayRow, (Anchor, Breakpoint)> {
 6414        let mut breakpoint_display_points = HashMap::default();
 6415
 6416        let Some(breakpoint_store) = self.breakpoint_store.clone() else {
 6417            return breakpoint_display_points;
 6418        };
 6419
 6420        let snapshot = self.snapshot(window, cx);
 6421
 6422        let multi_buffer_snapshot = &snapshot.display_snapshot.buffer_snapshot;
 6423        let Some(project) = self.project.as_ref() else {
 6424            return breakpoint_display_points;
 6425        };
 6426
 6427        let range = snapshot.display_point_to_point(DisplayPoint::new(range.start, 0), Bias::Left)
 6428            ..snapshot.display_point_to_point(DisplayPoint::new(range.end, 0), Bias::Right);
 6429
 6430        for (buffer_snapshot, range, excerpt_id) in
 6431            multi_buffer_snapshot.range_to_buffer_ranges(range)
 6432        {
 6433            let Some(buffer) = project.read_with(cx, |this, cx| {
 6434                this.buffer_for_id(buffer_snapshot.remote_id(), cx)
 6435            }) else {
 6436                continue;
 6437            };
 6438            let breakpoints = breakpoint_store.read(cx).breakpoints(
 6439                &buffer,
 6440                Some(
 6441                    buffer_snapshot.anchor_before(range.start)
 6442                        ..buffer_snapshot.anchor_after(range.end),
 6443                ),
 6444                buffer_snapshot,
 6445                cx,
 6446            );
 6447            for (anchor, breakpoint) in breakpoints {
 6448                let multi_buffer_anchor =
 6449                    Anchor::in_buffer(excerpt_id, buffer_snapshot.remote_id(), *anchor);
 6450                let position = multi_buffer_anchor
 6451                    .to_point(&multi_buffer_snapshot)
 6452                    .to_display_point(&snapshot);
 6453
 6454                breakpoint_display_points
 6455                    .insert(position.row(), (multi_buffer_anchor, breakpoint.clone()));
 6456            }
 6457        }
 6458
 6459        breakpoint_display_points
 6460    }
 6461
 6462    fn breakpoint_context_menu(
 6463        &self,
 6464        anchor: Anchor,
 6465        window: &mut Window,
 6466        cx: &mut Context<Self>,
 6467    ) -> Entity<ui::ContextMenu> {
 6468        let weak_editor = cx.weak_entity();
 6469        let focus_handle = self.focus_handle(cx);
 6470
 6471        let row = self
 6472            .buffer
 6473            .read(cx)
 6474            .snapshot(cx)
 6475            .summary_for_anchor::<Point>(&anchor)
 6476            .row;
 6477
 6478        let breakpoint = self
 6479            .breakpoint_at_row(row, window, cx)
 6480            .map(|(anchor, bp)| (anchor, Arc::from(bp)));
 6481
 6482        let log_breakpoint_msg = if breakpoint.as_ref().is_some_and(|bp| bp.1.message.is_some()) {
 6483            "Edit Log Breakpoint"
 6484        } else {
 6485            "Set Log Breakpoint"
 6486        };
 6487
 6488        let condition_breakpoint_msg = if breakpoint
 6489            .as_ref()
 6490            .is_some_and(|bp| bp.1.condition.is_some())
 6491        {
 6492            "Edit Condition Breakpoint"
 6493        } else {
 6494            "Set Condition Breakpoint"
 6495        };
 6496
 6497        let hit_condition_breakpoint_msg = if breakpoint
 6498            .as_ref()
 6499            .is_some_and(|bp| bp.1.hit_condition.is_some())
 6500        {
 6501            "Edit Hit Condition Breakpoint"
 6502        } else {
 6503            "Set Hit Condition Breakpoint"
 6504        };
 6505
 6506        let set_breakpoint_msg = if breakpoint.as_ref().is_some() {
 6507            "Unset Breakpoint"
 6508        } else {
 6509            "Set Breakpoint"
 6510        };
 6511
 6512        let run_to_cursor = command_palette_hooks::CommandPaletteFilter::try_global(cx)
 6513            .map_or(false, |filter| !filter.is_hidden(&DebuggerRunToCursor));
 6514
 6515        let toggle_state_msg = breakpoint.as_ref().map_or(None, |bp| match bp.1.state {
 6516            BreakpointState::Enabled => Some("Disable"),
 6517            BreakpointState::Disabled => Some("Enable"),
 6518        });
 6519
 6520        let (anchor, breakpoint) =
 6521            breakpoint.unwrap_or_else(|| (anchor, Arc::new(Breakpoint::new_standard())));
 6522
 6523        ui::ContextMenu::build(window, cx, |menu, _, _cx| {
 6524            menu.on_blur_subscription(Subscription::new(|| {}))
 6525                .context(focus_handle)
 6526                .when(run_to_cursor, |this| {
 6527                    let weak_editor = weak_editor.clone();
 6528                    this.entry("Run to cursor", None, move |window, cx| {
 6529                        weak_editor
 6530                            .update(cx, |editor, cx| {
 6531                                editor.change_selections(None, window, cx, |s| {
 6532                                    s.select_ranges([Point::new(row, 0)..Point::new(row, 0)])
 6533                                });
 6534                            })
 6535                            .ok();
 6536
 6537                        window.dispatch_action(Box::new(DebuggerRunToCursor), cx);
 6538                    })
 6539                    .separator()
 6540                })
 6541                .when_some(toggle_state_msg, |this, msg| {
 6542                    this.entry(msg, None, {
 6543                        let weak_editor = weak_editor.clone();
 6544                        let breakpoint = breakpoint.clone();
 6545                        move |_window, cx| {
 6546                            weak_editor
 6547                                .update(cx, |this, cx| {
 6548                                    this.edit_breakpoint_at_anchor(
 6549                                        anchor,
 6550                                        breakpoint.as_ref().clone(),
 6551                                        BreakpointEditAction::InvertState,
 6552                                        cx,
 6553                                    );
 6554                                })
 6555                                .log_err();
 6556                        }
 6557                    })
 6558                })
 6559                .entry(set_breakpoint_msg, None, {
 6560                    let weak_editor = weak_editor.clone();
 6561                    let breakpoint = breakpoint.clone();
 6562                    move |_window, cx| {
 6563                        weak_editor
 6564                            .update(cx, |this, cx| {
 6565                                this.edit_breakpoint_at_anchor(
 6566                                    anchor,
 6567                                    breakpoint.as_ref().clone(),
 6568                                    BreakpointEditAction::Toggle,
 6569                                    cx,
 6570                                );
 6571                            })
 6572                            .log_err();
 6573                    }
 6574                })
 6575                .entry(log_breakpoint_msg, None, {
 6576                    let breakpoint = breakpoint.clone();
 6577                    let weak_editor = weak_editor.clone();
 6578                    move |window, cx| {
 6579                        weak_editor
 6580                            .update(cx, |this, cx| {
 6581                                this.add_edit_breakpoint_block(
 6582                                    anchor,
 6583                                    breakpoint.as_ref(),
 6584                                    BreakpointPromptEditAction::Log,
 6585                                    window,
 6586                                    cx,
 6587                                );
 6588                            })
 6589                            .log_err();
 6590                    }
 6591                })
 6592                .entry(condition_breakpoint_msg, None, {
 6593                    let breakpoint = breakpoint.clone();
 6594                    let weak_editor = weak_editor.clone();
 6595                    move |window, cx| {
 6596                        weak_editor
 6597                            .update(cx, |this, cx| {
 6598                                this.add_edit_breakpoint_block(
 6599                                    anchor,
 6600                                    breakpoint.as_ref(),
 6601                                    BreakpointPromptEditAction::Condition,
 6602                                    window,
 6603                                    cx,
 6604                                );
 6605                            })
 6606                            .log_err();
 6607                    }
 6608                })
 6609                .entry(hit_condition_breakpoint_msg, None, move |window, cx| {
 6610                    weak_editor
 6611                        .update(cx, |this, cx| {
 6612                            this.add_edit_breakpoint_block(
 6613                                anchor,
 6614                                breakpoint.as_ref(),
 6615                                BreakpointPromptEditAction::HitCondition,
 6616                                window,
 6617                                cx,
 6618                            );
 6619                        })
 6620                        .log_err();
 6621                })
 6622        })
 6623    }
 6624
 6625    fn render_breakpoint(
 6626        &self,
 6627        position: Anchor,
 6628        row: DisplayRow,
 6629        breakpoint: &Breakpoint,
 6630        cx: &mut Context<Self>,
 6631    ) -> IconButton {
 6632        let (color, icon) = {
 6633            let icon = match (&breakpoint.message.is_some(), breakpoint.is_disabled()) {
 6634                (false, false) => ui::IconName::DebugBreakpoint,
 6635                (true, false) => ui::IconName::DebugLogBreakpoint,
 6636                (false, true) => ui::IconName::DebugDisabledBreakpoint,
 6637                (true, true) => ui::IconName::DebugDisabledLogBreakpoint,
 6638            };
 6639
 6640            let color = if self
 6641                .gutter_breakpoint_indicator
 6642                .0
 6643                .is_some_and(|(point, is_visible)| is_visible && point.row() == row)
 6644            {
 6645                Color::Hint
 6646            } else {
 6647                Color::Debugger
 6648            };
 6649
 6650            (color, icon)
 6651        };
 6652
 6653        let breakpoint = Arc::from(breakpoint.clone());
 6654
 6655        IconButton::new(("breakpoint_indicator", row.0 as usize), icon)
 6656            .icon_size(IconSize::XSmall)
 6657            .size(ui::ButtonSize::None)
 6658            .icon_color(color)
 6659            .style(ButtonStyle::Transparent)
 6660            .on_click(cx.listener({
 6661                let breakpoint = breakpoint.clone();
 6662
 6663                move |editor, event: &ClickEvent, window, cx| {
 6664                    let edit_action = if event.modifiers().platform || breakpoint.is_disabled() {
 6665                        BreakpointEditAction::InvertState
 6666                    } else {
 6667                        BreakpointEditAction::Toggle
 6668                    };
 6669
 6670                    window.focus(&editor.focus_handle(cx));
 6671                    editor.edit_breakpoint_at_anchor(
 6672                        position,
 6673                        breakpoint.as_ref().clone(),
 6674                        edit_action,
 6675                        cx,
 6676                    );
 6677                }
 6678            }))
 6679            .on_right_click(cx.listener(move |editor, event: &ClickEvent, window, cx| {
 6680                editor.set_breakpoint_context_menu(
 6681                    row,
 6682                    Some(position),
 6683                    event.down.position,
 6684                    window,
 6685                    cx,
 6686                );
 6687            }))
 6688    }
 6689
 6690    fn build_tasks_context(
 6691        project: &Entity<Project>,
 6692        buffer: &Entity<Buffer>,
 6693        buffer_row: u32,
 6694        tasks: &Arc<RunnableTasks>,
 6695        cx: &mut Context<Self>,
 6696    ) -> Task<Option<task::TaskContext>> {
 6697        let position = Point::new(buffer_row, tasks.column);
 6698        let range_start = buffer.read(cx).anchor_at(position, Bias::Right);
 6699        let location = Location {
 6700            buffer: buffer.clone(),
 6701            range: range_start..range_start,
 6702        };
 6703        // Fill in the environmental variables from the tree-sitter captures
 6704        let mut captured_task_variables = TaskVariables::default();
 6705        for (capture_name, value) in tasks.extra_variables.clone() {
 6706            captured_task_variables.insert(
 6707                task::VariableName::Custom(capture_name.into()),
 6708                value.clone(),
 6709            );
 6710        }
 6711        project.update(cx, |project, cx| {
 6712            project.task_store().update(cx, |task_store, cx| {
 6713                task_store.task_context_for_location(captured_task_variables, location, cx)
 6714            })
 6715        })
 6716    }
 6717
 6718    pub fn spawn_nearest_task(
 6719        &mut self,
 6720        action: &SpawnNearestTask,
 6721        window: &mut Window,
 6722        cx: &mut Context<Self>,
 6723    ) {
 6724        let Some((workspace, _)) = self.workspace.clone() else {
 6725            return;
 6726        };
 6727        let Some(project) = self.project.clone() else {
 6728            return;
 6729        };
 6730
 6731        // Try to find a closest, enclosing node using tree-sitter that has a
 6732        // task
 6733        let Some((buffer, buffer_row, tasks)) = self
 6734            .find_enclosing_node_task(cx)
 6735            // Or find the task that's closest in row-distance.
 6736            .or_else(|| self.find_closest_task(cx))
 6737        else {
 6738            return;
 6739        };
 6740
 6741        let reveal_strategy = action.reveal;
 6742        let task_context = Self::build_tasks_context(&project, &buffer, buffer_row, &tasks, cx);
 6743        cx.spawn_in(window, async move |_, cx| {
 6744            let context = task_context.await?;
 6745            let (task_source_kind, mut resolved_task) = tasks.resolve(&context).next()?;
 6746
 6747            let resolved = resolved_task.resolved.as_mut()?;
 6748            resolved.reveal = reveal_strategy;
 6749
 6750            workspace
 6751                .update(cx, |workspace, cx| {
 6752                    workspace::tasks::schedule_resolved_task(
 6753                        workspace,
 6754                        task_source_kind,
 6755                        resolved_task,
 6756                        false,
 6757                        cx,
 6758                    );
 6759                })
 6760                .ok()
 6761        })
 6762        .detach();
 6763    }
 6764
 6765    fn find_closest_task(
 6766        &mut self,
 6767        cx: &mut Context<Self>,
 6768    ) -> Option<(Entity<Buffer>, u32, Arc<RunnableTasks>)> {
 6769        let cursor_row = self.selections.newest_adjusted(cx).head().row;
 6770
 6771        let ((buffer_id, row), tasks) = self
 6772            .tasks
 6773            .iter()
 6774            .min_by_key(|((_, row), _)| cursor_row.abs_diff(*row))?;
 6775
 6776        let buffer = self.buffer.read(cx).buffer(*buffer_id)?;
 6777        let tasks = Arc::new(tasks.to_owned());
 6778        Some((buffer, *row, tasks))
 6779    }
 6780
 6781    fn find_enclosing_node_task(
 6782        &mut self,
 6783        cx: &mut Context<Self>,
 6784    ) -> Option<(Entity<Buffer>, u32, Arc<RunnableTasks>)> {
 6785        let snapshot = self.buffer.read(cx).snapshot(cx);
 6786        let offset = self.selections.newest::<usize>(cx).head();
 6787        let excerpt = snapshot.excerpt_containing(offset..offset)?;
 6788        let buffer_id = excerpt.buffer().remote_id();
 6789
 6790        let layer = excerpt.buffer().syntax_layer_at(offset)?;
 6791        let mut cursor = layer.node().walk();
 6792
 6793        while cursor.goto_first_child_for_byte(offset).is_some() {
 6794            if cursor.node().end_byte() == offset {
 6795                cursor.goto_next_sibling();
 6796            }
 6797        }
 6798
 6799        // Ascend to the smallest ancestor that contains the range and has a task.
 6800        loop {
 6801            let node = cursor.node();
 6802            let node_range = node.byte_range();
 6803            let symbol_start_row = excerpt.buffer().offset_to_point(node.start_byte()).row;
 6804
 6805            // Check if this node contains our offset
 6806            if node_range.start <= offset && node_range.end >= offset {
 6807                // If it contains offset, check for task
 6808                if let Some(tasks) = self.tasks.get(&(buffer_id, symbol_start_row)) {
 6809                    let buffer = self.buffer.read(cx).buffer(buffer_id)?;
 6810                    return Some((buffer, symbol_start_row, Arc::new(tasks.to_owned())));
 6811                }
 6812            }
 6813
 6814            if !cursor.goto_parent() {
 6815                break;
 6816            }
 6817        }
 6818        None
 6819    }
 6820
 6821    fn render_run_indicator(
 6822        &self,
 6823        _style: &EditorStyle,
 6824        is_active: bool,
 6825        row: DisplayRow,
 6826        breakpoint: Option<(Anchor, Breakpoint)>,
 6827        cx: &mut Context<Self>,
 6828    ) -> IconButton {
 6829        let color = Color::Muted;
 6830        let position = breakpoint.as_ref().map(|(anchor, _)| *anchor);
 6831
 6832        IconButton::new(("run_indicator", row.0 as usize), ui::IconName::Play)
 6833            .shape(ui::IconButtonShape::Square)
 6834            .icon_size(IconSize::XSmall)
 6835            .icon_color(color)
 6836            .toggle_state(is_active)
 6837            .on_click(cx.listener(move |editor, _e, window, cx| {
 6838                window.focus(&editor.focus_handle(cx));
 6839                editor.toggle_code_actions(
 6840                    &ToggleCodeActions {
 6841                        deployed_from_indicator: Some(row),
 6842                    },
 6843                    window,
 6844                    cx,
 6845                );
 6846            }))
 6847            .on_right_click(cx.listener(move |editor, event: &ClickEvent, window, cx| {
 6848                editor.set_breakpoint_context_menu(row, position, event.down.position, window, cx);
 6849            }))
 6850    }
 6851
 6852    pub fn context_menu_visible(&self) -> bool {
 6853        !self.edit_prediction_preview_is_active()
 6854            && self
 6855                .context_menu
 6856                .borrow()
 6857                .as_ref()
 6858                .map_or(false, |menu| menu.visible())
 6859    }
 6860
 6861    fn context_menu_origin(&self) -> Option<ContextMenuOrigin> {
 6862        self.context_menu
 6863            .borrow()
 6864            .as_ref()
 6865            .map(|menu| menu.origin())
 6866    }
 6867
 6868    pub fn set_context_menu_options(&mut self, options: ContextMenuOptions) {
 6869        self.context_menu_options = Some(options);
 6870    }
 6871
 6872    const EDIT_PREDICTION_POPOVER_PADDING_X: Pixels = Pixels(24.);
 6873    const EDIT_PREDICTION_POPOVER_PADDING_Y: Pixels = Pixels(2.);
 6874
 6875    fn render_edit_prediction_popover(
 6876        &mut self,
 6877        text_bounds: &Bounds<Pixels>,
 6878        content_origin: gpui::Point<Pixels>,
 6879        editor_snapshot: &EditorSnapshot,
 6880        visible_row_range: Range<DisplayRow>,
 6881        scroll_top: f32,
 6882        scroll_bottom: f32,
 6883        line_layouts: &[LineWithInvisibles],
 6884        line_height: Pixels,
 6885        scroll_pixel_position: gpui::Point<Pixels>,
 6886        newest_selection_head: Option<DisplayPoint>,
 6887        editor_width: Pixels,
 6888        style: &EditorStyle,
 6889        window: &mut Window,
 6890        cx: &mut App,
 6891    ) -> Option<(AnyElement, gpui::Point<Pixels>)> {
 6892        let active_inline_completion = self.active_inline_completion.as_ref()?;
 6893
 6894        if self.edit_prediction_visible_in_cursor_popover(true) {
 6895            return None;
 6896        }
 6897
 6898        match &active_inline_completion.completion {
 6899            InlineCompletion::Move { target, .. } => {
 6900                let target_display_point = target.to_display_point(editor_snapshot);
 6901
 6902                if self.edit_prediction_requires_modifier() {
 6903                    if !self.edit_prediction_preview_is_active() {
 6904                        return None;
 6905                    }
 6906
 6907                    self.render_edit_prediction_modifier_jump_popover(
 6908                        text_bounds,
 6909                        content_origin,
 6910                        visible_row_range,
 6911                        line_layouts,
 6912                        line_height,
 6913                        scroll_pixel_position,
 6914                        newest_selection_head,
 6915                        target_display_point,
 6916                        window,
 6917                        cx,
 6918                    )
 6919                } else {
 6920                    self.render_edit_prediction_eager_jump_popover(
 6921                        text_bounds,
 6922                        content_origin,
 6923                        editor_snapshot,
 6924                        visible_row_range,
 6925                        scroll_top,
 6926                        scroll_bottom,
 6927                        line_height,
 6928                        scroll_pixel_position,
 6929                        target_display_point,
 6930                        editor_width,
 6931                        window,
 6932                        cx,
 6933                    )
 6934                }
 6935            }
 6936            InlineCompletion::Edit {
 6937                display_mode: EditDisplayMode::Inline,
 6938                ..
 6939            } => None,
 6940            InlineCompletion::Edit {
 6941                display_mode: EditDisplayMode::TabAccept,
 6942                edits,
 6943                ..
 6944            } => {
 6945                let range = &edits.first()?.0;
 6946                let target_display_point = range.end.to_display_point(editor_snapshot);
 6947
 6948                self.render_edit_prediction_end_of_line_popover(
 6949                    "Accept",
 6950                    editor_snapshot,
 6951                    visible_row_range,
 6952                    target_display_point,
 6953                    line_height,
 6954                    scroll_pixel_position,
 6955                    content_origin,
 6956                    editor_width,
 6957                    window,
 6958                    cx,
 6959                )
 6960            }
 6961            InlineCompletion::Edit {
 6962                edits,
 6963                edit_preview,
 6964                display_mode: EditDisplayMode::DiffPopover,
 6965                snapshot,
 6966            } => self.render_edit_prediction_diff_popover(
 6967                text_bounds,
 6968                content_origin,
 6969                editor_snapshot,
 6970                visible_row_range,
 6971                line_layouts,
 6972                line_height,
 6973                scroll_pixel_position,
 6974                newest_selection_head,
 6975                editor_width,
 6976                style,
 6977                edits,
 6978                edit_preview,
 6979                snapshot,
 6980                window,
 6981                cx,
 6982            ),
 6983        }
 6984    }
 6985
 6986    fn render_edit_prediction_modifier_jump_popover(
 6987        &mut self,
 6988        text_bounds: &Bounds<Pixels>,
 6989        content_origin: gpui::Point<Pixels>,
 6990        visible_row_range: Range<DisplayRow>,
 6991        line_layouts: &[LineWithInvisibles],
 6992        line_height: Pixels,
 6993        scroll_pixel_position: gpui::Point<Pixels>,
 6994        newest_selection_head: Option<DisplayPoint>,
 6995        target_display_point: DisplayPoint,
 6996        window: &mut Window,
 6997        cx: &mut App,
 6998    ) -> Option<(AnyElement, gpui::Point<Pixels>)> {
 6999        let scrolled_content_origin =
 7000            content_origin - gpui::Point::new(scroll_pixel_position.x, Pixels(0.0));
 7001
 7002        const SCROLL_PADDING_Y: Pixels = px(12.);
 7003
 7004        if target_display_point.row() < visible_row_range.start {
 7005            return self.render_edit_prediction_scroll_popover(
 7006                |_| SCROLL_PADDING_Y,
 7007                IconName::ArrowUp,
 7008                visible_row_range,
 7009                line_layouts,
 7010                newest_selection_head,
 7011                scrolled_content_origin,
 7012                window,
 7013                cx,
 7014            );
 7015        } else if target_display_point.row() >= visible_row_range.end {
 7016            return self.render_edit_prediction_scroll_popover(
 7017                |size| text_bounds.size.height - size.height - SCROLL_PADDING_Y,
 7018                IconName::ArrowDown,
 7019                visible_row_range,
 7020                line_layouts,
 7021                newest_selection_head,
 7022                scrolled_content_origin,
 7023                window,
 7024                cx,
 7025            );
 7026        }
 7027
 7028        const POLE_WIDTH: Pixels = px(2.);
 7029
 7030        let line_layout =
 7031            line_layouts.get(target_display_point.row().minus(visible_row_range.start) as usize)?;
 7032        let target_column = target_display_point.column() as usize;
 7033
 7034        let target_x = line_layout.x_for_index(target_column);
 7035        let target_y =
 7036            (target_display_point.row().as_f32() * line_height) - scroll_pixel_position.y;
 7037
 7038        let flag_on_right = target_x < text_bounds.size.width / 2.;
 7039
 7040        let mut border_color = Self::edit_prediction_callout_popover_border_color(cx);
 7041        border_color.l += 0.001;
 7042
 7043        let mut element = v_flex()
 7044            .items_end()
 7045            .when(flag_on_right, |el| el.items_start())
 7046            .child(if flag_on_right {
 7047                self.render_edit_prediction_line_popover("Jump", None, window, cx)?
 7048                    .rounded_bl(px(0.))
 7049                    .rounded_tl(px(0.))
 7050                    .border_l_2()
 7051                    .border_color(border_color)
 7052            } else {
 7053                self.render_edit_prediction_line_popover("Jump", None, window, cx)?
 7054                    .rounded_br(px(0.))
 7055                    .rounded_tr(px(0.))
 7056                    .border_r_2()
 7057                    .border_color(border_color)
 7058            })
 7059            .child(div().w(POLE_WIDTH).bg(border_color).h(line_height))
 7060            .into_any();
 7061
 7062        let size = element.layout_as_root(AvailableSpace::min_size(), window, cx);
 7063
 7064        let mut origin = scrolled_content_origin + point(target_x, target_y)
 7065            - point(
 7066                if flag_on_right {
 7067                    POLE_WIDTH
 7068                } else {
 7069                    size.width - POLE_WIDTH
 7070                },
 7071                size.height - line_height,
 7072            );
 7073
 7074        origin.x = origin.x.max(content_origin.x);
 7075
 7076        element.prepaint_at(origin, window, cx);
 7077
 7078        Some((element, origin))
 7079    }
 7080
 7081    fn render_edit_prediction_scroll_popover(
 7082        &mut self,
 7083        to_y: impl Fn(Size<Pixels>) -> Pixels,
 7084        scroll_icon: IconName,
 7085        visible_row_range: Range<DisplayRow>,
 7086        line_layouts: &[LineWithInvisibles],
 7087        newest_selection_head: Option<DisplayPoint>,
 7088        scrolled_content_origin: gpui::Point<Pixels>,
 7089        window: &mut Window,
 7090        cx: &mut App,
 7091    ) -> Option<(AnyElement, gpui::Point<Pixels>)> {
 7092        let mut element = self
 7093            .render_edit_prediction_line_popover("Scroll", Some(scroll_icon), window, cx)?
 7094            .into_any();
 7095
 7096        let size = element.layout_as_root(AvailableSpace::min_size(), window, cx);
 7097
 7098        let cursor = newest_selection_head?;
 7099        let cursor_row_layout =
 7100            line_layouts.get(cursor.row().minus(visible_row_range.start) as usize)?;
 7101        let cursor_column = cursor.column() as usize;
 7102
 7103        let cursor_character_x = cursor_row_layout.x_for_index(cursor_column);
 7104
 7105        let origin = scrolled_content_origin + point(cursor_character_x, to_y(size));
 7106
 7107        element.prepaint_at(origin, window, cx);
 7108        Some((element, origin))
 7109    }
 7110
 7111    fn render_edit_prediction_eager_jump_popover(
 7112        &mut self,
 7113        text_bounds: &Bounds<Pixels>,
 7114        content_origin: gpui::Point<Pixels>,
 7115        editor_snapshot: &EditorSnapshot,
 7116        visible_row_range: Range<DisplayRow>,
 7117        scroll_top: f32,
 7118        scroll_bottom: f32,
 7119        line_height: Pixels,
 7120        scroll_pixel_position: gpui::Point<Pixels>,
 7121        target_display_point: DisplayPoint,
 7122        editor_width: Pixels,
 7123        window: &mut Window,
 7124        cx: &mut App,
 7125    ) -> Option<(AnyElement, gpui::Point<Pixels>)> {
 7126        if target_display_point.row().as_f32() < scroll_top {
 7127            let mut element = self
 7128                .render_edit_prediction_line_popover(
 7129                    "Jump to Edit",
 7130                    Some(IconName::ArrowUp),
 7131                    window,
 7132                    cx,
 7133                )?
 7134                .into_any();
 7135
 7136            let size = element.layout_as_root(AvailableSpace::min_size(), window, cx);
 7137            let offset = point(
 7138                (text_bounds.size.width - size.width) / 2.,
 7139                Self::EDIT_PREDICTION_POPOVER_PADDING_Y,
 7140            );
 7141
 7142            let origin = text_bounds.origin + offset;
 7143            element.prepaint_at(origin, window, cx);
 7144            Some((element, origin))
 7145        } else if (target_display_point.row().as_f32() + 1.) > scroll_bottom {
 7146            let mut element = self
 7147                .render_edit_prediction_line_popover(
 7148                    "Jump to Edit",
 7149                    Some(IconName::ArrowDown),
 7150                    window,
 7151                    cx,
 7152                )?
 7153                .into_any();
 7154
 7155            let size = element.layout_as_root(AvailableSpace::min_size(), window, cx);
 7156            let offset = point(
 7157                (text_bounds.size.width - size.width) / 2.,
 7158                text_bounds.size.height - size.height - Self::EDIT_PREDICTION_POPOVER_PADDING_Y,
 7159            );
 7160
 7161            let origin = text_bounds.origin + offset;
 7162            element.prepaint_at(origin, window, cx);
 7163            Some((element, origin))
 7164        } else {
 7165            self.render_edit_prediction_end_of_line_popover(
 7166                "Jump to Edit",
 7167                editor_snapshot,
 7168                visible_row_range,
 7169                target_display_point,
 7170                line_height,
 7171                scroll_pixel_position,
 7172                content_origin,
 7173                editor_width,
 7174                window,
 7175                cx,
 7176            )
 7177        }
 7178    }
 7179
 7180    fn render_edit_prediction_end_of_line_popover(
 7181        self: &mut Editor,
 7182        label: &'static str,
 7183        editor_snapshot: &EditorSnapshot,
 7184        visible_row_range: Range<DisplayRow>,
 7185        target_display_point: DisplayPoint,
 7186        line_height: Pixels,
 7187        scroll_pixel_position: gpui::Point<Pixels>,
 7188        content_origin: gpui::Point<Pixels>,
 7189        editor_width: Pixels,
 7190        window: &mut Window,
 7191        cx: &mut App,
 7192    ) -> Option<(AnyElement, gpui::Point<Pixels>)> {
 7193        let target_line_end = DisplayPoint::new(
 7194            target_display_point.row(),
 7195            editor_snapshot.line_len(target_display_point.row()),
 7196        );
 7197
 7198        let mut element = self
 7199            .render_edit_prediction_line_popover(label, None, window, cx)?
 7200            .into_any();
 7201
 7202        let size = element.layout_as_root(AvailableSpace::min_size(), window, cx);
 7203
 7204        let line_origin = self.display_to_pixel_point(target_line_end, editor_snapshot, window)?;
 7205
 7206        let start_point = content_origin - point(scroll_pixel_position.x, Pixels::ZERO);
 7207        let mut origin = start_point
 7208            + line_origin
 7209            + point(Self::EDIT_PREDICTION_POPOVER_PADDING_X, Pixels::ZERO);
 7210        origin.x = origin.x.max(content_origin.x);
 7211
 7212        let max_x = content_origin.x + editor_width - size.width;
 7213
 7214        if origin.x > max_x {
 7215            let offset = line_height + Self::EDIT_PREDICTION_POPOVER_PADDING_Y;
 7216
 7217            let icon = if visible_row_range.contains(&(target_display_point.row() + 2)) {
 7218                origin.y += offset;
 7219                IconName::ArrowUp
 7220            } else {
 7221                origin.y -= offset;
 7222                IconName::ArrowDown
 7223            };
 7224
 7225            element = self
 7226                .render_edit_prediction_line_popover(label, Some(icon), window, cx)?
 7227                .into_any();
 7228
 7229            let size = element.layout_as_root(AvailableSpace::min_size(), window, cx);
 7230
 7231            origin.x = content_origin.x + editor_width - size.width - px(2.);
 7232        }
 7233
 7234        element.prepaint_at(origin, window, cx);
 7235        Some((element, origin))
 7236    }
 7237
 7238    fn render_edit_prediction_diff_popover(
 7239        self: &Editor,
 7240        text_bounds: &Bounds<Pixels>,
 7241        content_origin: gpui::Point<Pixels>,
 7242        editor_snapshot: &EditorSnapshot,
 7243        visible_row_range: Range<DisplayRow>,
 7244        line_layouts: &[LineWithInvisibles],
 7245        line_height: Pixels,
 7246        scroll_pixel_position: gpui::Point<Pixels>,
 7247        newest_selection_head: Option<DisplayPoint>,
 7248        editor_width: Pixels,
 7249        style: &EditorStyle,
 7250        edits: &Vec<(Range<Anchor>, String)>,
 7251        edit_preview: &Option<language::EditPreview>,
 7252        snapshot: &language::BufferSnapshot,
 7253        window: &mut Window,
 7254        cx: &mut App,
 7255    ) -> Option<(AnyElement, gpui::Point<Pixels>)> {
 7256        let edit_start = edits
 7257            .first()
 7258            .unwrap()
 7259            .0
 7260            .start
 7261            .to_display_point(editor_snapshot);
 7262        let edit_end = edits
 7263            .last()
 7264            .unwrap()
 7265            .0
 7266            .end
 7267            .to_display_point(editor_snapshot);
 7268
 7269        let is_visible = visible_row_range.contains(&edit_start.row())
 7270            || visible_row_range.contains(&edit_end.row());
 7271        if !is_visible {
 7272            return None;
 7273        }
 7274
 7275        let highlighted_edits =
 7276            crate::inline_completion_edit_text(&snapshot, edits, edit_preview.as_ref()?, false, cx);
 7277
 7278        let styled_text = highlighted_edits.to_styled_text(&style.text);
 7279        let line_count = highlighted_edits.text.lines().count();
 7280
 7281        const BORDER_WIDTH: Pixels = px(1.);
 7282
 7283        let keybind = self.render_edit_prediction_accept_keybind(window, cx);
 7284        let has_keybind = keybind.is_some();
 7285
 7286        let mut element = h_flex()
 7287            .items_start()
 7288            .child(
 7289                h_flex()
 7290                    .bg(cx.theme().colors().editor_background)
 7291                    .border(BORDER_WIDTH)
 7292                    .shadow_sm()
 7293                    .border_color(cx.theme().colors().border)
 7294                    .rounded_l_lg()
 7295                    .when(line_count > 1, |el| el.rounded_br_lg())
 7296                    .pr_1()
 7297                    .child(styled_text),
 7298            )
 7299            .child(
 7300                h_flex()
 7301                    .h(line_height + BORDER_WIDTH * 2.)
 7302                    .px_1p5()
 7303                    .gap_1()
 7304                    // Workaround: For some reason, there's a gap if we don't do this
 7305                    .ml(-BORDER_WIDTH)
 7306                    .shadow(smallvec![gpui::BoxShadow {
 7307                        color: gpui::black().opacity(0.05),
 7308                        offset: point(px(1.), px(1.)),
 7309                        blur_radius: px(2.),
 7310                        spread_radius: px(0.),
 7311                    }])
 7312                    .bg(Editor::edit_prediction_line_popover_bg_color(cx))
 7313                    .border(BORDER_WIDTH)
 7314                    .border_color(cx.theme().colors().border)
 7315                    .rounded_r_lg()
 7316                    .id("edit_prediction_diff_popover_keybind")
 7317                    .when(!has_keybind, |el| {
 7318                        let status_colors = cx.theme().status();
 7319
 7320                        el.bg(status_colors.error_background)
 7321                            .border_color(status_colors.error.opacity(0.6))
 7322                            .child(Icon::new(IconName::Info).color(Color::Error))
 7323                            .cursor_default()
 7324                            .hoverable_tooltip(move |_window, cx| {
 7325                                cx.new(|_| MissingEditPredictionKeybindingTooltip).into()
 7326                            })
 7327                    })
 7328                    .children(keybind),
 7329            )
 7330            .into_any();
 7331
 7332        let longest_row =
 7333            editor_snapshot.longest_row_in_range(edit_start.row()..edit_end.row() + 1);
 7334        let longest_line_width = if visible_row_range.contains(&longest_row) {
 7335            line_layouts[(longest_row.0 - visible_row_range.start.0) as usize].width
 7336        } else {
 7337            layout_line(
 7338                longest_row,
 7339                editor_snapshot,
 7340                style,
 7341                editor_width,
 7342                |_| false,
 7343                window,
 7344                cx,
 7345            )
 7346            .width
 7347        };
 7348
 7349        let viewport_bounds =
 7350            Bounds::new(Default::default(), window.viewport_size()).extend(Edges {
 7351                right: -EditorElement::SCROLLBAR_WIDTH,
 7352                ..Default::default()
 7353            });
 7354
 7355        let x_after_longest =
 7356            text_bounds.origin.x + longest_line_width + Self::EDIT_PREDICTION_POPOVER_PADDING_X
 7357                - scroll_pixel_position.x;
 7358
 7359        let element_bounds = element.layout_as_root(AvailableSpace::min_size(), window, cx);
 7360
 7361        // Fully visible if it can be displayed within the window (allow overlapping other
 7362        // panes). However, this is only allowed if the popover starts within text_bounds.
 7363        let can_position_to_the_right = x_after_longest < text_bounds.right()
 7364            && x_after_longest + element_bounds.width < viewport_bounds.right();
 7365
 7366        let mut origin = if can_position_to_the_right {
 7367            point(
 7368                x_after_longest,
 7369                text_bounds.origin.y + edit_start.row().as_f32() * line_height
 7370                    - scroll_pixel_position.y,
 7371            )
 7372        } else {
 7373            let cursor_row = newest_selection_head.map(|head| head.row());
 7374            let above_edit = edit_start
 7375                .row()
 7376                .0
 7377                .checked_sub(line_count as u32)
 7378                .map(DisplayRow);
 7379            let below_edit = Some(edit_end.row() + 1);
 7380            let above_cursor =
 7381                cursor_row.and_then(|row| row.0.checked_sub(line_count as u32).map(DisplayRow));
 7382            let below_cursor = cursor_row.map(|cursor_row| cursor_row + 1);
 7383
 7384            // Place the edit popover adjacent to the edit if there is a location
 7385            // available that is onscreen and does not obscure the cursor. Otherwise,
 7386            // place it adjacent to the cursor.
 7387            let row_target = [above_edit, below_edit, above_cursor, below_cursor]
 7388                .into_iter()
 7389                .flatten()
 7390                .find(|&start_row| {
 7391                    let end_row = start_row + line_count as u32;
 7392                    visible_row_range.contains(&start_row)
 7393                        && visible_row_range.contains(&end_row)
 7394                        && cursor_row.map_or(true, |cursor_row| {
 7395                            !((start_row..end_row).contains(&cursor_row))
 7396                        })
 7397                })?;
 7398
 7399            content_origin
 7400                + point(
 7401                    -scroll_pixel_position.x,
 7402                    row_target.as_f32() * line_height - scroll_pixel_position.y,
 7403                )
 7404        };
 7405
 7406        origin.x -= BORDER_WIDTH;
 7407
 7408        window.defer_draw(element, origin, 1);
 7409
 7410        // Do not return an element, since it will already be drawn due to defer_draw.
 7411        None
 7412    }
 7413
 7414    fn edit_prediction_cursor_popover_height(&self) -> Pixels {
 7415        px(30.)
 7416    }
 7417
 7418    fn current_user_player_color(&self, cx: &mut App) -> PlayerColor {
 7419        if self.read_only(cx) {
 7420            cx.theme().players().read_only()
 7421        } else {
 7422            self.style.as_ref().unwrap().local_player
 7423        }
 7424    }
 7425
 7426    fn render_edit_prediction_accept_keybind(
 7427        &self,
 7428        window: &mut Window,
 7429        cx: &App,
 7430    ) -> Option<AnyElement> {
 7431        let accept_binding = self.accept_edit_prediction_keybind(window, cx);
 7432        let accept_keystroke = accept_binding.keystroke()?;
 7433
 7434        let is_platform_style_mac = PlatformStyle::platform() == PlatformStyle::Mac;
 7435
 7436        let modifiers_color = if accept_keystroke.modifiers == window.modifiers() {
 7437            Color::Accent
 7438        } else {
 7439            Color::Muted
 7440        };
 7441
 7442        h_flex()
 7443            .px_0p5()
 7444            .when(is_platform_style_mac, |parent| parent.gap_0p5())
 7445            .font(theme::ThemeSettings::get_global(cx).buffer_font.clone())
 7446            .text_size(TextSize::XSmall.rems(cx))
 7447            .child(h_flex().children(ui::render_modifiers(
 7448                &accept_keystroke.modifiers,
 7449                PlatformStyle::platform(),
 7450                Some(modifiers_color),
 7451                Some(IconSize::XSmall.rems().into()),
 7452                true,
 7453            )))
 7454            .when(is_platform_style_mac, |parent| {
 7455                parent.child(accept_keystroke.key.clone())
 7456            })
 7457            .when(!is_platform_style_mac, |parent| {
 7458                parent.child(
 7459                    Key::new(
 7460                        util::capitalize(&accept_keystroke.key),
 7461                        Some(Color::Default),
 7462                    )
 7463                    .size(Some(IconSize::XSmall.rems().into())),
 7464                )
 7465            })
 7466            .into_any()
 7467            .into()
 7468    }
 7469
 7470    fn render_edit_prediction_line_popover(
 7471        &self,
 7472        label: impl Into<SharedString>,
 7473        icon: Option<IconName>,
 7474        window: &mut Window,
 7475        cx: &App,
 7476    ) -> Option<Stateful<Div>> {
 7477        let padding_right = if icon.is_some() { px(4.) } else { px(8.) };
 7478
 7479        let keybind = self.render_edit_prediction_accept_keybind(window, cx);
 7480        let has_keybind = keybind.is_some();
 7481
 7482        let result = h_flex()
 7483            .id("ep-line-popover")
 7484            .py_0p5()
 7485            .pl_1()
 7486            .pr(padding_right)
 7487            .gap_1()
 7488            .rounded_md()
 7489            .border_1()
 7490            .bg(Self::edit_prediction_line_popover_bg_color(cx))
 7491            .border_color(Self::edit_prediction_callout_popover_border_color(cx))
 7492            .shadow_sm()
 7493            .when(!has_keybind, |el| {
 7494                let status_colors = cx.theme().status();
 7495
 7496                el.bg(status_colors.error_background)
 7497                    .border_color(status_colors.error.opacity(0.6))
 7498                    .pl_2()
 7499                    .child(Icon::new(IconName::ZedPredictError).color(Color::Error))
 7500                    .cursor_default()
 7501                    .hoverable_tooltip(move |_window, cx| {
 7502                        cx.new(|_| MissingEditPredictionKeybindingTooltip).into()
 7503                    })
 7504            })
 7505            .children(keybind)
 7506            .child(
 7507                Label::new(label)
 7508                    .size(LabelSize::Small)
 7509                    .when(!has_keybind, |el| {
 7510                        el.color(cx.theme().status().error.into()).strikethrough()
 7511                    }),
 7512            )
 7513            .when(!has_keybind, |el| {
 7514                el.child(
 7515                    h_flex().ml_1().child(
 7516                        Icon::new(IconName::Info)
 7517                            .size(IconSize::Small)
 7518                            .color(cx.theme().status().error.into()),
 7519                    ),
 7520                )
 7521            })
 7522            .when_some(icon, |element, icon| {
 7523                element.child(
 7524                    div()
 7525                        .mt(px(1.5))
 7526                        .child(Icon::new(icon).size(IconSize::Small)),
 7527                )
 7528            });
 7529
 7530        Some(result)
 7531    }
 7532
 7533    fn edit_prediction_line_popover_bg_color(cx: &App) -> Hsla {
 7534        let accent_color = cx.theme().colors().text_accent;
 7535        let editor_bg_color = cx.theme().colors().editor_background;
 7536        editor_bg_color.blend(accent_color.opacity(0.1))
 7537    }
 7538
 7539    fn edit_prediction_callout_popover_border_color(cx: &App) -> Hsla {
 7540        let accent_color = cx.theme().colors().text_accent;
 7541        let editor_bg_color = cx.theme().colors().editor_background;
 7542        editor_bg_color.blend(accent_color.opacity(0.6))
 7543    }
 7544
 7545    fn render_edit_prediction_cursor_popover(
 7546        &self,
 7547        min_width: Pixels,
 7548        max_width: Pixels,
 7549        cursor_point: Point,
 7550        style: &EditorStyle,
 7551        accept_keystroke: Option<&gpui::Keystroke>,
 7552        _window: &Window,
 7553        cx: &mut Context<Editor>,
 7554    ) -> Option<AnyElement> {
 7555        let provider = self.edit_prediction_provider.as_ref()?;
 7556
 7557        if provider.provider.needs_terms_acceptance(cx) {
 7558            return Some(
 7559                h_flex()
 7560                    .min_w(min_width)
 7561                    .flex_1()
 7562                    .px_2()
 7563                    .py_1()
 7564                    .gap_3()
 7565                    .elevation_2(cx)
 7566                    .hover(|style| style.bg(cx.theme().colors().element_hover))
 7567                    .id("accept-terms")
 7568                    .cursor_pointer()
 7569                    .on_mouse_down(MouseButton::Left, |_, window, _| window.prevent_default())
 7570                    .on_click(cx.listener(|this, _event, window, cx| {
 7571                        cx.stop_propagation();
 7572                        this.report_editor_event("Edit Prediction Provider ToS Clicked", None, cx);
 7573                        window.dispatch_action(
 7574                            zed_actions::OpenZedPredictOnboarding.boxed_clone(),
 7575                            cx,
 7576                        );
 7577                    }))
 7578                    .child(
 7579                        h_flex()
 7580                            .flex_1()
 7581                            .gap_2()
 7582                            .child(Icon::new(IconName::ZedPredict))
 7583                            .child(Label::new("Accept Terms of Service"))
 7584                            .child(div().w_full())
 7585                            .child(
 7586                                Icon::new(IconName::ArrowUpRight)
 7587                                    .color(Color::Muted)
 7588                                    .size(IconSize::Small),
 7589                            )
 7590                            .into_any_element(),
 7591                    )
 7592                    .into_any(),
 7593            );
 7594        }
 7595
 7596        let is_refreshing = provider.provider.is_refreshing(cx);
 7597
 7598        fn pending_completion_container() -> Div {
 7599            h_flex()
 7600                .h_full()
 7601                .flex_1()
 7602                .gap_2()
 7603                .child(Icon::new(IconName::ZedPredict))
 7604        }
 7605
 7606        let completion = match &self.active_inline_completion {
 7607            Some(prediction) => {
 7608                if !self.has_visible_completions_menu() {
 7609                    const RADIUS: Pixels = px(6.);
 7610                    const BORDER_WIDTH: Pixels = px(1.);
 7611
 7612                    return Some(
 7613                        h_flex()
 7614                            .elevation_2(cx)
 7615                            .border(BORDER_WIDTH)
 7616                            .border_color(cx.theme().colors().border)
 7617                            .when(accept_keystroke.is_none(), |el| {
 7618                                el.border_color(cx.theme().status().error)
 7619                            })
 7620                            .rounded(RADIUS)
 7621                            .rounded_tl(px(0.))
 7622                            .overflow_hidden()
 7623                            .child(div().px_1p5().child(match &prediction.completion {
 7624                                InlineCompletion::Move { target, snapshot } => {
 7625                                    use text::ToPoint as _;
 7626                                    if target.text_anchor.to_point(&snapshot).row > cursor_point.row
 7627                                    {
 7628                                        Icon::new(IconName::ZedPredictDown)
 7629                                    } else {
 7630                                        Icon::new(IconName::ZedPredictUp)
 7631                                    }
 7632                                }
 7633                                InlineCompletion::Edit { .. } => Icon::new(IconName::ZedPredict),
 7634                            }))
 7635                            .child(
 7636                                h_flex()
 7637                                    .gap_1()
 7638                                    .py_1()
 7639                                    .px_2()
 7640                                    .rounded_r(RADIUS - BORDER_WIDTH)
 7641                                    .border_l_1()
 7642                                    .border_color(cx.theme().colors().border)
 7643                                    .bg(Self::edit_prediction_line_popover_bg_color(cx))
 7644                                    .when(self.edit_prediction_preview.released_too_fast(), |el| {
 7645                                        el.child(
 7646                                            Label::new("Hold")
 7647                                                .size(LabelSize::Small)
 7648                                                .when(accept_keystroke.is_none(), |el| {
 7649                                                    el.strikethrough()
 7650                                                })
 7651                                                .line_height_style(LineHeightStyle::UiLabel),
 7652                                        )
 7653                                    })
 7654                                    .id("edit_prediction_cursor_popover_keybind")
 7655                                    .when(accept_keystroke.is_none(), |el| {
 7656                                        let status_colors = cx.theme().status();
 7657
 7658                                        el.bg(status_colors.error_background)
 7659                                            .border_color(status_colors.error.opacity(0.6))
 7660                                            .child(Icon::new(IconName::Info).color(Color::Error))
 7661                                            .cursor_default()
 7662                                            .hoverable_tooltip(move |_window, cx| {
 7663                                                cx.new(|_| MissingEditPredictionKeybindingTooltip)
 7664                                                    .into()
 7665                                            })
 7666                                    })
 7667                                    .when_some(
 7668                                        accept_keystroke.as_ref(),
 7669                                        |el, accept_keystroke| {
 7670                                            el.child(h_flex().children(ui::render_modifiers(
 7671                                                &accept_keystroke.modifiers,
 7672                                                PlatformStyle::platform(),
 7673                                                Some(Color::Default),
 7674                                                Some(IconSize::XSmall.rems().into()),
 7675                                                false,
 7676                                            )))
 7677                                        },
 7678                                    ),
 7679                            )
 7680                            .into_any(),
 7681                    );
 7682                }
 7683
 7684                self.render_edit_prediction_cursor_popover_preview(
 7685                    prediction,
 7686                    cursor_point,
 7687                    style,
 7688                    cx,
 7689                )?
 7690            }
 7691
 7692            None if is_refreshing => match &self.stale_inline_completion_in_menu {
 7693                Some(stale_completion) => self.render_edit_prediction_cursor_popover_preview(
 7694                    stale_completion,
 7695                    cursor_point,
 7696                    style,
 7697                    cx,
 7698                )?,
 7699
 7700                None => {
 7701                    pending_completion_container().child(Label::new("...").size(LabelSize::Small))
 7702                }
 7703            },
 7704
 7705            None => pending_completion_container().child(Label::new("No Prediction")),
 7706        };
 7707
 7708        let completion = if is_refreshing {
 7709            completion
 7710                .with_animation(
 7711                    "loading-completion",
 7712                    Animation::new(Duration::from_secs(2))
 7713                        .repeat()
 7714                        .with_easing(pulsating_between(0.4, 0.8)),
 7715                    |label, delta| label.opacity(delta),
 7716                )
 7717                .into_any_element()
 7718        } else {
 7719            completion.into_any_element()
 7720        };
 7721
 7722        let has_completion = self.active_inline_completion.is_some();
 7723
 7724        let is_platform_style_mac = PlatformStyle::platform() == PlatformStyle::Mac;
 7725        Some(
 7726            h_flex()
 7727                .min_w(min_width)
 7728                .max_w(max_width)
 7729                .flex_1()
 7730                .elevation_2(cx)
 7731                .border_color(cx.theme().colors().border)
 7732                .child(
 7733                    div()
 7734                        .flex_1()
 7735                        .py_1()
 7736                        .px_2()
 7737                        .overflow_hidden()
 7738                        .child(completion),
 7739                )
 7740                .when_some(accept_keystroke, |el, accept_keystroke| {
 7741                    if !accept_keystroke.modifiers.modified() {
 7742                        return el;
 7743                    }
 7744
 7745                    el.child(
 7746                        h_flex()
 7747                            .h_full()
 7748                            .border_l_1()
 7749                            .rounded_r_lg()
 7750                            .border_color(cx.theme().colors().border)
 7751                            .bg(Self::edit_prediction_line_popover_bg_color(cx))
 7752                            .gap_1()
 7753                            .py_1()
 7754                            .px_2()
 7755                            .child(
 7756                                h_flex()
 7757                                    .font(theme::ThemeSettings::get_global(cx).buffer_font.clone())
 7758                                    .when(is_platform_style_mac, |parent| parent.gap_1())
 7759                                    .child(h_flex().children(ui::render_modifiers(
 7760                                        &accept_keystroke.modifiers,
 7761                                        PlatformStyle::platform(),
 7762                                        Some(if !has_completion {
 7763                                            Color::Muted
 7764                                        } else {
 7765                                            Color::Default
 7766                                        }),
 7767                                        None,
 7768                                        false,
 7769                                    ))),
 7770                            )
 7771                            .child(Label::new("Preview").into_any_element())
 7772                            .opacity(if has_completion { 1.0 } else { 0.4 }),
 7773                    )
 7774                })
 7775                .into_any(),
 7776        )
 7777    }
 7778
 7779    fn render_edit_prediction_cursor_popover_preview(
 7780        &self,
 7781        completion: &InlineCompletionState,
 7782        cursor_point: Point,
 7783        style: &EditorStyle,
 7784        cx: &mut Context<Editor>,
 7785    ) -> Option<Div> {
 7786        use text::ToPoint as _;
 7787
 7788        fn render_relative_row_jump(
 7789            prefix: impl Into<String>,
 7790            current_row: u32,
 7791            target_row: u32,
 7792        ) -> Div {
 7793            let (row_diff, arrow) = if target_row < current_row {
 7794                (current_row - target_row, IconName::ArrowUp)
 7795            } else {
 7796                (target_row - current_row, IconName::ArrowDown)
 7797            };
 7798
 7799            h_flex()
 7800                .child(
 7801                    Label::new(format!("{}{}", prefix.into(), row_diff))
 7802                        .color(Color::Muted)
 7803                        .size(LabelSize::Small),
 7804                )
 7805                .child(Icon::new(arrow).color(Color::Muted).size(IconSize::Small))
 7806        }
 7807
 7808        match &completion.completion {
 7809            InlineCompletion::Move {
 7810                target, snapshot, ..
 7811            } => Some(
 7812                h_flex()
 7813                    .px_2()
 7814                    .gap_2()
 7815                    .flex_1()
 7816                    .child(
 7817                        if target.text_anchor.to_point(&snapshot).row > cursor_point.row {
 7818                            Icon::new(IconName::ZedPredictDown)
 7819                        } else {
 7820                            Icon::new(IconName::ZedPredictUp)
 7821                        },
 7822                    )
 7823                    .child(Label::new("Jump to Edit")),
 7824            ),
 7825
 7826            InlineCompletion::Edit {
 7827                edits,
 7828                edit_preview,
 7829                snapshot,
 7830                display_mode: _,
 7831            } => {
 7832                let first_edit_row = edits.first()?.0.start.text_anchor.to_point(&snapshot).row;
 7833
 7834                let (highlighted_edits, has_more_lines) = crate::inline_completion_edit_text(
 7835                    &snapshot,
 7836                    &edits,
 7837                    edit_preview.as_ref()?,
 7838                    true,
 7839                    cx,
 7840                )
 7841                .first_line_preview();
 7842
 7843                let styled_text = gpui::StyledText::new(highlighted_edits.text)
 7844                    .with_default_highlights(&style.text, highlighted_edits.highlights);
 7845
 7846                let preview = h_flex()
 7847                    .gap_1()
 7848                    .min_w_16()
 7849                    .child(styled_text)
 7850                    .when(has_more_lines, |parent| parent.child(""));
 7851
 7852                let left = if first_edit_row != cursor_point.row {
 7853                    render_relative_row_jump("", cursor_point.row, first_edit_row)
 7854                        .into_any_element()
 7855                } else {
 7856                    Icon::new(IconName::ZedPredict).into_any_element()
 7857                };
 7858
 7859                Some(
 7860                    h_flex()
 7861                        .h_full()
 7862                        .flex_1()
 7863                        .gap_2()
 7864                        .pr_1()
 7865                        .overflow_x_hidden()
 7866                        .font(theme::ThemeSettings::get_global(cx).buffer_font.clone())
 7867                        .child(left)
 7868                        .child(preview),
 7869                )
 7870            }
 7871        }
 7872    }
 7873
 7874    fn render_context_menu(
 7875        &self,
 7876        style: &EditorStyle,
 7877        max_height_in_lines: u32,
 7878        window: &mut Window,
 7879        cx: &mut Context<Editor>,
 7880    ) -> Option<AnyElement> {
 7881        let menu = self.context_menu.borrow();
 7882        let menu = menu.as_ref()?;
 7883        if !menu.visible() {
 7884            return None;
 7885        };
 7886        Some(menu.render(style, max_height_in_lines, window, cx))
 7887    }
 7888
 7889    fn render_context_menu_aside(
 7890        &mut self,
 7891        max_size: Size<Pixels>,
 7892        window: &mut Window,
 7893        cx: &mut Context<Editor>,
 7894    ) -> Option<AnyElement> {
 7895        self.context_menu.borrow_mut().as_mut().and_then(|menu| {
 7896            if menu.visible() {
 7897                menu.render_aside(self, max_size, window, cx)
 7898            } else {
 7899                None
 7900            }
 7901        })
 7902    }
 7903
 7904    fn hide_context_menu(
 7905        &mut self,
 7906        window: &mut Window,
 7907        cx: &mut Context<Self>,
 7908    ) -> Option<CodeContextMenu> {
 7909        cx.notify();
 7910        self.completion_tasks.clear();
 7911        let context_menu = self.context_menu.borrow_mut().take();
 7912        self.stale_inline_completion_in_menu.take();
 7913        self.update_visible_inline_completion(window, cx);
 7914        context_menu
 7915    }
 7916
 7917    fn show_snippet_choices(
 7918        &mut self,
 7919        choices: &Vec<String>,
 7920        selection: Range<Anchor>,
 7921        cx: &mut Context<Self>,
 7922    ) {
 7923        if selection.start.buffer_id.is_none() {
 7924            return;
 7925        }
 7926        let buffer_id = selection.start.buffer_id.unwrap();
 7927        let buffer = self.buffer().read(cx).buffer(buffer_id);
 7928        let id = post_inc(&mut self.next_completion_id);
 7929
 7930        if let Some(buffer) = buffer {
 7931            *self.context_menu.borrow_mut() = Some(CodeContextMenu::Completions(
 7932                CompletionsMenu::new_snippet_choices(id, true, choices, selection, buffer),
 7933            ));
 7934        }
 7935    }
 7936
 7937    pub fn insert_snippet(
 7938        &mut self,
 7939        insertion_ranges: &[Range<usize>],
 7940        snippet: Snippet,
 7941        window: &mut Window,
 7942        cx: &mut Context<Self>,
 7943    ) -> Result<()> {
 7944        struct Tabstop<T> {
 7945            is_end_tabstop: bool,
 7946            ranges: Vec<Range<T>>,
 7947            choices: Option<Vec<String>>,
 7948        }
 7949
 7950        let tabstops = self.buffer.update(cx, |buffer, cx| {
 7951            let snippet_text: Arc<str> = snippet.text.clone().into();
 7952            let edits = insertion_ranges
 7953                .iter()
 7954                .cloned()
 7955                .map(|range| (range, snippet_text.clone()));
 7956            buffer.edit(edits, Some(AutoindentMode::EachLine), cx);
 7957
 7958            let snapshot = &*buffer.read(cx);
 7959            let snippet = &snippet;
 7960            snippet
 7961                .tabstops
 7962                .iter()
 7963                .map(|tabstop| {
 7964                    let is_end_tabstop = tabstop.ranges.first().map_or(false, |tabstop| {
 7965                        tabstop.is_empty() && tabstop.start == snippet.text.len() as isize
 7966                    });
 7967                    let mut tabstop_ranges = tabstop
 7968                        .ranges
 7969                        .iter()
 7970                        .flat_map(|tabstop_range| {
 7971                            let mut delta = 0_isize;
 7972                            insertion_ranges.iter().map(move |insertion_range| {
 7973                                let insertion_start = insertion_range.start as isize + delta;
 7974                                delta +=
 7975                                    snippet.text.len() as isize - insertion_range.len() as isize;
 7976
 7977                                let start = ((insertion_start + tabstop_range.start) as usize)
 7978                                    .min(snapshot.len());
 7979                                let end = ((insertion_start + tabstop_range.end) as usize)
 7980                                    .min(snapshot.len());
 7981                                snapshot.anchor_before(start)..snapshot.anchor_after(end)
 7982                            })
 7983                        })
 7984                        .collect::<Vec<_>>();
 7985                    tabstop_ranges.sort_unstable_by(|a, b| a.start.cmp(&b.start, snapshot));
 7986
 7987                    Tabstop {
 7988                        is_end_tabstop,
 7989                        ranges: tabstop_ranges,
 7990                        choices: tabstop.choices.clone(),
 7991                    }
 7992                })
 7993                .collect::<Vec<_>>()
 7994        });
 7995        if let Some(tabstop) = tabstops.first() {
 7996            self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 7997                s.select_ranges(tabstop.ranges.iter().cloned());
 7998            });
 7999
 8000            if let Some(choices) = &tabstop.choices {
 8001                if let Some(selection) = tabstop.ranges.first() {
 8002                    self.show_snippet_choices(choices, selection.clone(), cx)
 8003                }
 8004            }
 8005
 8006            // If we're already at the last tabstop and it's at the end of the snippet,
 8007            // we're done, we don't need to keep the state around.
 8008            if !tabstop.is_end_tabstop {
 8009                let choices = tabstops
 8010                    .iter()
 8011                    .map(|tabstop| tabstop.choices.clone())
 8012                    .collect();
 8013
 8014                let ranges = tabstops
 8015                    .into_iter()
 8016                    .map(|tabstop| tabstop.ranges)
 8017                    .collect::<Vec<_>>();
 8018
 8019                self.snippet_stack.push(SnippetState {
 8020                    active_index: 0,
 8021                    ranges,
 8022                    choices,
 8023                });
 8024            }
 8025
 8026            // Check whether the just-entered snippet ends with an auto-closable bracket.
 8027            if self.autoclose_regions.is_empty() {
 8028                let snapshot = self.buffer.read(cx).snapshot(cx);
 8029                for selection in &mut self.selections.all::<Point>(cx) {
 8030                    let selection_head = selection.head();
 8031                    let Some(scope) = snapshot.language_scope_at(selection_head) else {
 8032                        continue;
 8033                    };
 8034
 8035                    let mut bracket_pair = None;
 8036                    let next_chars = snapshot.chars_at(selection_head).collect::<String>();
 8037                    let prev_chars = snapshot
 8038                        .reversed_chars_at(selection_head)
 8039                        .collect::<String>();
 8040                    for (pair, enabled) in scope.brackets() {
 8041                        if enabled
 8042                            && pair.close
 8043                            && prev_chars.starts_with(pair.start.as_str())
 8044                            && next_chars.starts_with(pair.end.as_str())
 8045                        {
 8046                            bracket_pair = Some(pair.clone());
 8047                            break;
 8048                        }
 8049                    }
 8050                    if let Some(pair) = bracket_pair {
 8051                        let snapshot_settings = snapshot.language_settings_at(selection_head, cx);
 8052                        let autoclose_enabled =
 8053                            self.use_autoclose && snapshot_settings.use_autoclose;
 8054                        if autoclose_enabled {
 8055                            let start = snapshot.anchor_after(selection_head);
 8056                            let end = snapshot.anchor_after(selection_head);
 8057                            self.autoclose_regions.push(AutocloseRegion {
 8058                                selection_id: selection.id,
 8059                                range: start..end,
 8060                                pair,
 8061                            });
 8062                        }
 8063                    }
 8064                }
 8065            }
 8066        }
 8067        Ok(())
 8068    }
 8069
 8070    pub fn move_to_next_snippet_tabstop(
 8071        &mut self,
 8072        window: &mut Window,
 8073        cx: &mut Context<Self>,
 8074    ) -> bool {
 8075        self.move_to_snippet_tabstop(Bias::Right, window, cx)
 8076    }
 8077
 8078    pub fn move_to_prev_snippet_tabstop(
 8079        &mut self,
 8080        window: &mut Window,
 8081        cx: &mut Context<Self>,
 8082    ) -> bool {
 8083        self.move_to_snippet_tabstop(Bias::Left, window, cx)
 8084    }
 8085
 8086    pub fn move_to_snippet_tabstop(
 8087        &mut self,
 8088        bias: Bias,
 8089        window: &mut Window,
 8090        cx: &mut Context<Self>,
 8091    ) -> bool {
 8092        if let Some(mut snippet) = self.snippet_stack.pop() {
 8093            match bias {
 8094                Bias::Left => {
 8095                    if snippet.active_index > 0 {
 8096                        snippet.active_index -= 1;
 8097                    } else {
 8098                        self.snippet_stack.push(snippet);
 8099                        return false;
 8100                    }
 8101                }
 8102                Bias::Right => {
 8103                    if snippet.active_index + 1 < snippet.ranges.len() {
 8104                        snippet.active_index += 1;
 8105                    } else {
 8106                        self.snippet_stack.push(snippet);
 8107                        return false;
 8108                    }
 8109                }
 8110            }
 8111            if let Some(current_ranges) = snippet.ranges.get(snippet.active_index) {
 8112                self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8113                    s.select_anchor_ranges(current_ranges.iter().cloned())
 8114                });
 8115
 8116                if let Some(choices) = &snippet.choices[snippet.active_index] {
 8117                    if let Some(selection) = current_ranges.first() {
 8118                        self.show_snippet_choices(&choices, selection.clone(), cx);
 8119                    }
 8120                }
 8121
 8122                // If snippet state is not at the last tabstop, push it back on the stack
 8123                if snippet.active_index + 1 < snippet.ranges.len() {
 8124                    self.snippet_stack.push(snippet);
 8125                }
 8126                return true;
 8127            }
 8128        }
 8129
 8130        false
 8131    }
 8132
 8133    pub fn clear(&mut self, window: &mut Window, cx: &mut Context<Self>) {
 8134        self.transact(window, cx, |this, window, cx| {
 8135            this.select_all(&SelectAll, window, cx);
 8136            this.insert("", window, cx);
 8137        });
 8138    }
 8139
 8140    pub fn backspace(&mut self, _: &Backspace, window: &mut Window, cx: &mut Context<Self>) {
 8141        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
 8142        self.transact(window, cx, |this, window, cx| {
 8143            this.select_autoclose_pair(window, cx);
 8144            let mut linked_ranges = HashMap::<_, Vec<_>>::default();
 8145            if !this.linked_edit_ranges.is_empty() {
 8146                let selections = this.selections.all::<MultiBufferPoint>(cx);
 8147                let snapshot = this.buffer.read(cx).snapshot(cx);
 8148
 8149                for selection in selections.iter() {
 8150                    let selection_start = snapshot.anchor_before(selection.start).text_anchor;
 8151                    let selection_end = snapshot.anchor_after(selection.end).text_anchor;
 8152                    if selection_start.buffer_id != selection_end.buffer_id {
 8153                        continue;
 8154                    }
 8155                    if let Some(ranges) =
 8156                        this.linked_editing_ranges_for(selection_start..selection_end, cx)
 8157                    {
 8158                        for (buffer, entries) in ranges {
 8159                            linked_ranges.entry(buffer).or_default().extend(entries);
 8160                        }
 8161                    }
 8162                }
 8163            }
 8164
 8165            let mut selections = this.selections.all::<MultiBufferPoint>(cx);
 8166            let display_map = this.display_map.update(cx, |map, cx| map.snapshot(cx));
 8167            for selection in &mut selections {
 8168                if selection.is_empty() {
 8169                    let old_head = selection.head();
 8170                    let mut new_head =
 8171                        movement::left(&display_map, old_head.to_display_point(&display_map))
 8172                            .to_point(&display_map);
 8173                    if let Some((buffer, line_buffer_range)) = display_map
 8174                        .buffer_snapshot
 8175                        .buffer_line_for_row(MultiBufferRow(old_head.row))
 8176                    {
 8177                        let indent_size = buffer.indent_size_for_line(line_buffer_range.start.row);
 8178                        let indent_len = match indent_size.kind {
 8179                            IndentKind::Space => {
 8180                                buffer.settings_at(line_buffer_range.start, cx).tab_size
 8181                            }
 8182                            IndentKind::Tab => NonZeroU32::new(1).unwrap(),
 8183                        };
 8184                        if old_head.column <= indent_size.len && old_head.column > 0 {
 8185                            let indent_len = indent_len.get();
 8186                            new_head = cmp::min(
 8187                                new_head,
 8188                                MultiBufferPoint::new(
 8189                                    old_head.row,
 8190                                    ((old_head.column - 1) / indent_len) * indent_len,
 8191                                ),
 8192                            );
 8193                        }
 8194                    }
 8195
 8196                    selection.set_head(new_head, SelectionGoal::None);
 8197                }
 8198            }
 8199
 8200            this.signature_help_state.set_backspace_pressed(true);
 8201            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8202                s.select(selections)
 8203            });
 8204            this.insert("", window, cx);
 8205            let empty_str: Arc<str> = Arc::from("");
 8206            for (buffer, edits) in linked_ranges {
 8207                let snapshot = buffer.read(cx).snapshot();
 8208                use text::ToPoint as TP;
 8209
 8210                let edits = edits
 8211                    .into_iter()
 8212                    .map(|range| {
 8213                        let end_point = TP::to_point(&range.end, &snapshot);
 8214                        let mut start_point = TP::to_point(&range.start, &snapshot);
 8215
 8216                        if end_point == start_point {
 8217                            let offset = text::ToOffset::to_offset(&range.start, &snapshot)
 8218                                .saturating_sub(1);
 8219                            start_point =
 8220                                snapshot.clip_point(TP::to_point(&offset, &snapshot), Bias::Left);
 8221                        };
 8222
 8223                        (start_point..end_point, empty_str.clone())
 8224                    })
 8225                    .sorted_by_key(|(range, _)| range.start)
 8226                    .collect::<Vec<_>>();
 8227                buffer.update(cx, |this, cx| {
 8228                    this.edit(edits, None, cx);
 8229                })
 8230            }
 8231            this.refresh_inline_completion(true, false, window, cx);
 8232            linked_editing_ranges::refresh_linked_ranges(this, window, cx);
 8233        });
 8234    }
 8235
 8236    pub fn delete(&mut self, _: &Delete, window: &mut Window, cx: &mut Context<Self>) {
 8237        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
 8238        self.transact(window, cx, |this, window, cx| {
 8239            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8240                s.move_with(|map, selection| {
 8241                    if selection.is_empty() {
 8242                        let cursor = movement::right(map, selection.head());
 8243                        selection.end = cursor;
 8244                        selection.reversed = true;
 8245                        selection.goal = SelectionGoal::None;
 8246                    }
 8247                })
 8248            });
 8249            this.insert("", window, cx);
 8250            this.refresh_inline_completion(true, false, window, cx);
 8251        });
 8252    }
 8253
 8254    pub fn backtab(&mut self, _: &Backtab, window: &mut Window, cx: &mut Context<Self>) {
 8255        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
 8256        if self.move_to_prev_snippet_tabstop(window, cx) {
 8257            return;
 8258        }
 8259        self.outdent(&Outdent, window, cx);
 8260    }
 8261
 8262    pub fn tab(&mut self, _: &Tab, window: &mut Window, cx: &mut Context<Self>) {
 8263        if self.move_to_next_snippet_tabstop(window, cx) {
 8264            self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
 8265            return;
 8266        }
 8267        if self.read_only(cx) {
 8268            return;
 8269        }
 8270        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
 8271        let mut selections = self.selections.all_adjusted(cx);
 8272        let buffer = self.buffer.read(cx);
 8273        let snapshot = buffer.snapshot(cx);
 8274        let rows_iter = selections.iter().map(|s| s.head().row);
 8275        let suggested_indents = snapshot.suggested_indents(rows_iter, cx);
 8276
 8277        let mut edits = Vec::new();
 8278        let mut prev_edited_row = 0;
 8279        let mut row_delta = 0;
 8280        for selection in &mut selections {
 8281            if selection.start.row != prev_edited_row {
 8282                row_delta = 0;
 8283            }
 8284            prev_edited_row = selection.end.row;
 8285
 8286            // If the selection is non-empty, then increase the indentation of the selected lines.
 8287            if !selection.is_empty() {
 8288                row_delta =
 8289                    Self::indent_selection(buffer, &snapshot, selection, &mut edits, row_delta, cx);
 8290                continue;
 8291            }
 8292
 8293            // If the selection is empty and the cursor is in the leading whitespace before the
 8294            // suggested indentation, then auto-indent the line.
 8295            let cursor = selection.head();
 8296            let current_indent = snapshot.indent_size_for_line(MultiBufferRow(cursor.row));
 8297            if let Some(suggested_indent) =
 8298                suggested_indents.get(&MultiBufferRow(cursor.row)).copied()
 8299            {
 8300                if cursor.column < suggested_indent.len
 8301                    && cursor.column <= current_indent.len
 8302                    && current_indent.len <= suggested_indent.len
 8303                {
 8304                    selection.start = Point::new(cursor.row, suggested_indent.len);
 8305                    selection.end = selection.start;
 8306                    if row_delta == 0 {
 8307                        edits.extend(Buffer::edit_for_indent_size_adjustment(
 8308                            cursor.row,
 8309                            current_indent,
 8310                            suggested_indent,
 8311                        ));
 8312                        row_delta = suggested_indent.len - current_indent.len;
 8313                    }
 8314                    continue;
 8315                }
 8316            }
 8317
 8318            // Otherwise, insert a hard or soft tab.
 8319            let settings = buffer.language_settings_at(cursor, cx);
 8320            let tab_size = if settings.hard_tabs {
 8321                IndentSize::tab()
 8322            } else {
 8323                let tab_size = settings.tab_size.get();
 8324                let indent_remainder = snapshot
 8325                    .text_for_range(Point::new(cursor.row, 0)..cursor)
 8326                    .flat_map(str::chars)
 8327                    .fold(row_delta % tab_size, |counter: u32, c| {
 8328                        if c == '\t' {
 8329                            0
 8330                        } else {
 8331                            (counter + 1) % tab_size
 8332                        }
 8333                    });
 8334
 8335                let chars_to_next_tab_stop = tab_size - indent_remainder;
 8336                IndentSize::spaces(chars_to_next_tab_stop)
 8337            };
 8338            selection.start = Point::new(cursor.row, cursor.column + row_delta + tab_size.len);
 8339            selection.end = selection.start;
 8340            edits.push((cursor..cursor, tab_size.chars().collect::<String>()));
 8341            row_delta += tab_size.len;
 8342        }
 8343
 8344        self.transact(window, cx, |this, window, cx| {
 8345            this.buffer.update(cx, |b, cx| b.edit(edits, None, cx));
 8346            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8347                s.select(selections)
 8348            });
 8349            this.refresh_inline_completion(true, false, window, cx);
 8350        });
 8351    }
 8352
 8353    pub fn indent(&mut self, _: &Indent, window: &mut Window, cx: &mut Context<Self>) {
 8354        if self.read_only(cx) {
 8355            return;
 8356        }
 8357        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
 8358        let mut selections = self.selections.all::<Point>(cx);
 8359        let mut prev_edited_row = 0;
 8360        let mut row_delta = 0;
 8361        let mut edits = Vec::new();
 8362        let buffer = self.buffer.read(cx);
 8363        let snapshot = buffer.snapshot(cx);
 8364        for selection in &mut selections {
 8365            if selection.start.row != prev_edited_row {
 8366                row_delta = 0;
 8367            }
 8368            prev_edited_row = selection.end.row;
 8369
 8370            row_delta =
 8371                Self::indent_selection(buffer, &snapshot, selection, &mut edits, row_delta, cx);
 8372        }
 8373
 8374        self.transact(window, cx, |this, window, cx| {
 8375            this.buffer.update(cx, |b, cx| b.edit(edits, None, cx));
 8376            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8377                s.select(selections)
 8378            });
 8379        });
 8380    }
 8381
 8382    fn indent_selection(
 8383        buffer: &MultiBuffer,
 8384        snapshot: &MultiBufferSnapshot,
 8385        selection: &mut Selection<Point>,
 8386        edits: &mut Vec<(Range<Point>, String)>,
 8387        delta_for_start_row: u32,
 8388        cx: &App,
 8389    ) -> u32 {
 8390        let settings = buffer.language_settings_at(selection.start, cx);
 8391        let tab_size = settings.tab_size.get();
 8392        let indent_kind = if settings.hard_tabs {
 8393            IndentKind::Tab
 8394        } else {
 8395            IndentKind::Space
 8396        };
 8397        let mut start_row = selection.start.row;
 8398        let mut end_row = selection.end.row + 1;
 8399
 8400        // If a selection ends at the beginning of a line, don't indent
 8401        // that last line.
 8402        if selection.end.column == 0 && selection.end.row > selection.start.row {
 8403            end_row -= 1;
 8404        }
 8405
 8406        // Avoid re-indenting a row that has already been indented by a
 8407        // previous selection, but still update this selection's column
 8408        // to reflect that indentation.
 8409        if delta_for_start_row > 0 {
 8410            start_row += 1;
 8411            selection.start.column += delta_for_start_row;
 8412            if selection.end.row == selection.start.row {
 8413                selection.end.column += delta_for_start_row;
 8414            }
 8415        }
 8416
 8417        let mut delta_for_end_row = 0;
 8418        let has_multiple_rows = start_row + 1 != end_row;
 8419        for row in start_row..end_row {
 8420            let current_indent = snapshot.indent_size_for_line(MultiBufferRow(row));
 8421            let indent_delta = match (current_indent.kind, indent_kind) {
 8422                (IndentKind::Space, IndentKind::Space) => {
 8423                    let columns_to_next_tab_stop = tab_size - (current_indent.len % tab_size);
 8424                    IndentSize::spaces(columns_to_next_tab_stop)
 8425                }
 8426                (IndentKind::Tab, IndentKind::Space) => IndentSize::spaces(tab_size),
 8427                (_, IndentKind::Tab) => IndentSize::tab(),
 8428            };
 8429
 8430            let start = if has_multiple_rows || current_indent.len < selection.start.column {
 8431                0
 8432            } else {
 8433                selection.start.column
 8434            };
 8435            let row_start = Point::new(row, start);
 8436            edits.push((
 8437                row_start..row_start,
 8438                indent_delta.chars().collect::<String>(),
 8439            ));
 8440
 8441            // Update this selection's endpoints to reflect the indentation.
 8442            if row == selection.start.row {
 8443                selection.start.column += indent_delta.len;
 8444            }
 8445            if row == selection.end.row {
 8446                selection.end.column += indent_delta.len;
 8447                delta_for_end_row = indent_delta.len;
 8448            }
 8449        }
 8450
 8451        if selection.start.row == selection.end.row {
 8452            delta_for_start_row + delta_for_end_row
 8453        } else {
 8454            delta_for_end_row
 8455        }
 8456    }
 8457
 8458    pub fn outdent(&mut self, _: &Outdent, window: &mut Window, cx: &mut Context<Self>) {
 8459        if self.read_only(cx) {
 8460            return;
 8461        }
 8462        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
 8463        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 8464        let selections = self.selections.all::<Point>(cx);
 8465        let mut deletion_ranges = Vec::new();
 8466        let mut last_outdent = None;
 8467        {
 8468            let buffer = self.buffer.read(cx);
 8469            let snapshot = buffer.snapshot(cx);
 8470            for selection in &selections {
 8471                let settings = buffer.language_settings_at(selection.start, cx);
 8472                let tab_size = settings.tab_size.get();
 8473                let mut rows = selection.spanned_rows(false, &display_map);
 8474
 8475                // Avoid re-outdenting a row that has already been outdented by a
 8476                // previous selection.
 8477                if let Some(last_row) = last_outdent {
 8478                    if last_row == rows.start {
 8479                        rows.start = rows.start.next_row();
 8480                    }
 8481                }
 8482                let has_multiple_rows = rows.len() > 1;
 8483                for row in rows.iter_rows() {
 8484                    let indent_size = snapshot.indent_size_for_line(row);
 8485                    if indent_size.len > 0 {
 8486                        let deletion_len = match indent_size.kind {
 8487                            IndentKind::Space => {
 8488                                let columns_to_prev_tab_stop = indent_size.len % tab_size;
 8489                                if columns_to_prev_tab_stop == 0 {
 8490                                    tab_size
 8491                                } else {
 8492                                    columns_to_prev_tab_stop
 8493                                }
 8494                            }
 8495                            IndentKind::Tab => 1,
 8496                        };
 8497                        let start = if has_multiple_rows
 8498                            || deletion_len > selection.start.column
 8499                            || indent_size.len < selection.start.column
 8500                        {
 8501                            0
 8502                        } else {
 8503                            selection.start.column - deletion_len
 8504                        };
 8505                        deletion_ranges.push(
 8506                            Point::new(row.0, start)..Point::new(row.0, start + deletion_len),
 8507                        );
 8508                        last_outdent = Some(row);
 8509                    }
 8510                }
 8511            }
 8512        }
 8513
 8514        self.transact(window, cx, |this, window, cx| {
 8515            this.buffer.update(cx, |buffer, cx| {
 8516                let empty_str: Arc<str> = Arc::default();
 8517                buffer.edit(
 8518                    deletion_ranges
 8519                        .into_iter()
 8520                        .map(|range| (range, empty_str.clone())),
 8521                    None,
 8522                    cx,
 8523                );
 8524            });
 8525            let selections = this.selections.all::<usize>(cx);
 8526            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8527                s.select(selections)
 8528            });
 8529        });
 8530    }
 8531
 8532    pub fn autoindent(&mut self, _: &AutoIndent, window: &mut Window, cx: &mut Context<Self>) {
 8533        if self.read_only(cx) {
 8534            return;
 8535        }
 8536        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
 8537        let selections = self
 8538            .selections
 8539            .all::<usize>(cx)
 8540            .into_iter()
 8541            .map(|s| s.range());
 8542
 8543        self.transact(window, cx, |this, window, cx| {
 8544            this.buffer.update(cx, |buffer, cx| {
 8545                buffer.autoindent_ranges(selections, cx);
 8546            });
 8547            let selections = this.selections.all::<usize>(cx);
 8548            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8549                s.select(selections)
 8550            });
 8551        });
 8552    }
 8553
 8554    pub fn delete_line(&mut self, _: &DeleteLine, window: &mut Window, cx: &mut Context<Self>) {
 8555        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
 8556        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 8557        let selections = self.selections.all::<Point>(cx);
 8558
 8559        let mut new_cursors = Vec::new();
 8560        let mut edit_ranges = Vec::new();
 8561        let mut selections = selections.iter().peekable();
 8562        while let Some(selection) = selections.next() {
 8563            let mut rows = selection.spanned_rows(false, &display_map);
 8564            let goal_display_column = selection.head().to_display_point(&display_map).column();
 8565
 8566            // Accumulate contiguous regions of rows that we want to delete.
 8567            while let Some(next_selection) = selections.peek() {
 8568                let next_rows = next_selection.spanned_rows(false, &display_map);
 8569                if next_rows.start <= rows.end {
 8570                    rows.end = next_rows.end;
 8571                    selections.next().unwrap();
 8572                } else {
 8573                    break;
 8574                }
 8575            }
 8576
 8577            let buffer = &display_map.buffer_snapshot;
 8578            let mut edit_start = Point::new(rows.start.0, 0).to_offset(buffer);
 8579            let edit_end;
 8580            let cursor_buffer_row;
 8581            if buffer.max_point().row >= rows.end.0 {
 8582                // If there's a line after the range, delete the \n from the end of the row range
 8583                // and position the cursor on the next line.
 8584                edit_end = Point::new(rows.end.0, 0).to_offset(buffer);
 8585                cursor_buffer_row = rows.end;
 8586            } else {
 8587                // If there isn't a line after the range, delete the \n from the line before the
 8588                // start of the row range and position the cursor there.
 8589                edit_start = edit_start.saturating_sub(1);
 8590                edit_end = buffer.len();
 8591                cursor_buffer_row = rows.start.previous_row();
 8592            }
 8593
 8594            let mut cursor = Point::new(cursor_buffer_row.0, 0).to_display_point(&display_map);
 8595            *cursor.column_mut() =
 8596                cmp::min(goal_display_column, display_map.line_len(cursor.row()));
 8597
 8598            new_cursors.push((
 8599                selection.id,
 8600                buffer.anchor_after(cursor.to_point(&display_map)),
 8601            ));
 8602            edit_ranges.push(edit_start..edit_end);
 8603        }
 8604
 8605        self.transact(window, cx, |this, window, cx| {
 8606            let buffer = this.buffer.update(cx, |buffer, cx| {
 8607                let empty_str: Arc<str> = Arc::default();
 8608                buffer.edit(
 8609                    edit_ranges
 8610                        .into_iter()
 8611                        .map(|range| (range, empty_str.clone())),
 8612                    None,
 8613                    cx,
 8614                );
 8615                buffer.snapshot(cx)
 8616            });
 8617            let new_selections = new_cursors
 8618                .into_iter()
 8619                .map(|(id, cursor)| {
 8620                    let cursor = cursor.to_point(&buffer);
 8621                    Selection {
 8622                        id,
 8623                        start: cursor,
 8624                        end: cursor,
 8625                        reversed: false,
 8626                        goal: SelectionGoal::None,
 8627                    }
 8628                })
 8629                .collect();
 8630
 8631            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8632                s.select(new_selections);
 8633            });
 8634        });
 8635    }
 8636
 8637    pub fn join_lines_impl(
 8638        &mut self,
 8639        insert_whitespace: bool,
 8640        window: &mut Window,
 8641        cx: &mut Context<Self>,
 8642    ) {
 8643        if self.read_only(cx) {
 8644            return;
 8645        }
 8646        let mut row_ranges = Vec::<Range<MultiBufferRow>>::new();
 8647        for selection in self.selections.all::<Point>(cx) {
 8648            let start = MultiBufferRow(selection.start.row);
 8649            // Treat single line selections as if they include the next line. Otherwise this action
 8650            // would do nothing for single line selections individual cursors.
 8651            let end = if selection.start.row == selection.end.row {
 8652                MultiBufferRow(selection.start.row + 1)
 8653            } else {
 8654                MultiBufferRow(selection.end.row)
 8655            };
 8656
 8657            if let Some(last_row_range) = row_ranges.last_mut() {
 8658                if start <= last_row_range.end {
 8659                    last_row_range.end = end;
 8660                    continue;
 8661                }
 8662            }
 8663            row_ranges.push(start..end);
 8664        }
 8665
 8666        let snapshot = self.buffer.read(cx).snapshot(cx);
 8667        let mut cursor_positions = Vec::new();
 8668        for row_range in &row_ranges {
 8669            let anchor = snapshot.anchor_before(Point::new(
 8670                row_range.end.previous_row().0,
 8671                snapshot.line_len(row_range.end.previous_row()),
 8672            ));
 8673            cursor_positions.push(anchor..anchor);
 8674        }
 8675
 8676        self.transact(window, cx, |this, window, cx| {
 8677            for row_range in row_ranges.into_iter().rev() {
 8678                for row in row_range.iter_rows().rev() {
 8679                    let end_of_line = Point::new(row.0, snapshot.line_len(row));
 8680                    let next_line_row = row.next_row();
 8681                    let indent = snapshot.indent_size_for_line(next_line_row);
 8682                    let start_of_next_line = Point::new(next_line_row.0, indent.len);
 8683
 8684                    let replace =
 8685                        if snapshot.line_len(next_line_row) > indent.len && insert_whitespace {
 8686                            " "
 8687                        } else {
 8688                            ""
 8689                        };
 8690
 8691                    this.buffer.update(cx, |buffer, cx| {
 8692                        buffer.edit([(end_of_line..start_of_next_line, replace)], None, cx)
 8693                    });
 8694                }
 8695            }
 8696
 8697            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8698                s.select_anchor_ranges(cursor_positions)
 8699            });
 8700        });
 8701    }
 8702
 8703    pub fn join_lines(&mut self, _: &JoinLines, window: &mut Window, cx: &mut Context<Self>) {
 8704        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
 8705        self.join_lines_impl(true, window, cx);
 8706    }
 8707
 8708    pub fn sort_lines_case_sensitive(
 8709        &mut self,
 8710        _: &SortLinesCaseSensitive,
 8711        window: &mut Window,
 8712        cx: &mut Context<Self>,
 8713    ) {
 8714        self.manipulate_lines(window, cx, |lines| lines.sort())
 8715    }
 8716
 8717    pub fn sort_lines_case_insensitive(
 8718        &mut self,
 8719        _: &SortLinesCaseInsensitive,
 8720        window: &mut Window,
 8721        cx: &mut Context<Self>,
 8722    ) {
 8723        self.manipulate_lines(window, cx, |lines| {
 8724            lines.sort_by_key(|line| line.to_lowercase())
 8725        })
 8726    }
 8727
 8728    pub fn unique_lines_case_insensitive(
 8729        &mut self,
 8730        _: &UniqueLinesCaseInsensitive,
 8731        window: &mut Window,
 8732        cx: &mut Context<Self>,
 8733    ) {
 8734        self.manipulate_lines(window, cx, |lines| {
 8735            let mut seen = HashSet::default();
 8736            lines.retain(|line| seen.insert(line.to_lowercase()));
 8737        })
 8738    }
 8739
 8740    pub fn unique_lines_case_sensitive(
 8741        &mut self,
 8742        _: &UniqueLinesCaseSensitive,
 8743        window: &mut Window,
 8744        cx: &mut Context<Self>,
 8745    ) {
 8746        self.manipulate_lines(window, cx, |lines| {
 8747            let mut seen = HashSet::default();
 8748            lines.retain(|line| seen.insert(*line));
 8749        })
 8750    }
 8751
 8752    pub fn reload_file(&mut self, _: &ReloadFile, window: &mut Window, cx: &mut Context<Self>) {
 8753        let Some(project) = self.project.clone() else {
 8754            return;
 8755        };
 8756        self.reload(project, window, cx)
 8757            .detach_and_notify_err(window, cx);
 8758    }
 8759
 8760    pub fn restore_file(
 8761        &mut self,
 8762        _: &::git::RestoreFile,
 8763        window: &mut Window,
 8764        cx: &mut Context<Self>,
 8765    ) {
 8766        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
 8767        let mut buffer_ids = HashSet::default();
 8768        let snapshot = self.buffer().read(cx).snapshot(cx);
 8769        for selection in self.selections.all::<usize>(cx) {
 8770            buffer_ids.extend(snapshot.buffer_ids_for_range(selection.range()))
 8771        }
 8772
 8773        let buffer = self.buffer().read(cx);
 8774        let ranges = buffer_ids
 8775            .into_iter()
 8776            .flat_map(|buffer_id| buffer.excerpt_ranges_for_buffer(buffer_id, cx))
 8777            .collect::<Vec<_>>();
 8778
 8779        self.restore_hunks_in_ranges(ranges, window, cx);
 8780    }
 8781
 8782    pub fn git_restore(&mut self, _: &Restore, window: &mut Window, cx: &mut Context<Self>) {
 8783        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
 8784        let selections = self
 8785            .selections
 8786            .all(cx)
 8787            .into_iter()
 8788            .map(|s| s.range())
 8789            .collect();
 8790        self.restore_hunks_in_ranges(selections, window, cx);
 8791    }
 8792
 8793    pub fn restore_hunks_in_ranges(
 8794        &mut self,
 8795        ranges: Vec<Range<Point>>,
 8796        window: &mut Window,
 8797        cx: &mut Context<Editor>,
 8798    ) {
 8799        let mut revert_changes = HashMap::default();
 8800        let chunk_by = self
 8801            .snapshot(window, cx)
 8802            .hunks_for_ranges(ranges)
 8803            .into_iter()
 8804            .chunk_by(|hunk| hunk.buffer_id);
 8805        for (buffer_id, hunks) in &chunk_by {
 8806            let hunks = hunks.collect::<Vec<_>>();
 8807            for hunk in &hunks {
 8808                self.prepare_restore_change(&mut revert_changes, hunk, cx);
 8809            }
 8810            self.do_stage_or_unstage(false, buffer_id, hunks.into_iter(), cx);
 8811        }
 8812        drop(chunk_by);
 8813        if !revert_changes.is_empty() {
 8814            self.transact(window, cx, |editor, window, cx| {
 8815                editor.restore(revert_changes, window, cx);
 8816            });
 8817        }
 8818    }
 8819
 8820    pub fn open_active_item_in_terminal(
 8821        &mut self,
 8822        _: &OpenInTerminal,
 8823        window: &mut Window,
 8824        cx: &mut Context<Self>,
 8825    ) {
 8826        if let Some(working_directory) = self.active_excerpt(cx).and_then(|(_, buffer, _)| {
 8827            let project_path = buffer.read(cx).project_path(cx)?;
 8828            let project = self.project.as_ref()?.read(cx);
 8829            let entry = project.entry_for_path(&project_path, cx)?;
 8830            let parent = match &entry.canonical_path {
 8831                Some(canonical_path) => canonical_path.to_path_buf(),
 8832                None => project.absolute_path(&project_path, cx)?,
 8833            }
 8834            .parent()?
 8835            .to_path_buf();
 8836            Some(parent)
 8837        }) {
 8838            window.dispatch_action(OpenTerminal { working_directory }.boxed_clone(), cx);
 8839        }
 8840    }
 8841
 8842    fn set_breakpoint_context_menu(
 8843        &mut self,
 8844        display_row: DisplayRow,
 8845        position: Option<Anchor>,
 8846        clicked_point: gpui::Point<Pixels>,
 8847        window: &mut Window,
 8848        cx: &mut Context<Self>,
 8849    ) {
 8850        if !cx.has_flag::<Debugger>() {
 8851            return;
 8852        }
 8853        let source = self
 8854            .buffer
 8855            .read(cx)
 8856            .snapshot(cx)
 8857            .anchor_before(Point::new(display_row.0, 0u32));
 8858
 8859        let context_menu = self.breakpoint_context_menu(position.unwrap_or(source), window, cx);
 8860
 8861        self.mouse_context_menu = MouseContextMenu::pinned_to_editor(
 8862            self,
 8863            source,
 8864            clicked_point,
 8865            None,
 8866            context_menu,
 8867            window,
 8868            cx,
 8869        );
 8870    }
 8871
 8872    fn add_edit_breakpoint_block(
 8873        &mut self,
 8874        anchor: Anchor,
 8875        breakpoint: &Breakpoint,
 8876        edit_action: BreakpointPromptEditAction,
 8877        window: &mut Window,
 8878        cx: &mut Context<Self>,
 8879    ) {
 8880        let weak_editor = cx.weak_entity();
 8881        let bp_prompt = cx.new(|cx| {
 8882            BreakpointPromptEditor::new(
 8883                weak_editor,
 8884                anchor,
 8885                breakpoint.clone(),
 8886                edit_action,
 8887                window,
 8888                cx,
 8889            )
 8890        });
 8891
 8892        let height = bp_prompt.update(cx, |this, cx| {
 8893            this.prompt
 8894                .update(cx, |prompt, cx| prompt.max_point(cx).row().0 + 1 + 2)
 8895        });
 8896        let cloned_prompt = bp_prompt.clone();
 8897        let blocks = vec![BlockProperties {
 8898            style: BlockStyle::Sticky,
 8899            placement: BlockPlacement::Above(anchor),
 8900            height: Some(height),
 8901            render: Arc::new(move |cx| {
 8902                *cloned_prompt.read(cx).gutter_dimensions.lock() = *cx.gutter_dimensions;
 8903                cloned_prompt.clone().into_any_element()
 8904            }),
 8905            priority: 0,
 8906        }];
 8907
 8908        let focus_handle = bp_prompt.focus_handle(cx);
 8909        window.focus(&focus_handle);
 8910
 8911        let block_ids = self.insert_blocks(blocks, None, cx);
 8912        bp_prompt.update(cx, |prompt, _| {
 8913            prompt.add_block_ids(block_ids);
 8914        });
 8915    }
 8916
 8917    pub(crate) fn breakpoint_at_row(
 8918        &self,
 8919        row: u32,
 8920        window: &mut Window,
 8921        cx: &mut Context<Self>,
 8922    ) -> Option<(Anchor, Breakpoint)> {
 8923        let snapshot = self.snapshot(window, cx);
 8924        let breakpoint_position = snapshot.buffer_snapshot.anchor_before(Point::new(row, 0));
 8925
 8926        self.breakpoint_at_anchor(breakpoint_position, &snapshot, cx)
 8927    }
 8928
 8929    pub(crate) fn breakpoint_at_anchor(
 8930        &self,
 8931        breakpoint_position: Anchor,
 8932        snapshot: &EditorSnapshot,
 8933        cx: &mut Context<Self>,
 8934    ) -> Option<(Anchor, Breakpoint)> {
 8935        let project = self.project.clone()?;
 8936
 8937        let buffer_id = breakpoint_position.buffer_id.or_else(|| {
 8938            snapshot
 8939                .buffer_snapshot
 8940                .buffer_id_for_excerpt(breakpoint_position.excerpt_id)
 8941        })?;
 8942
 8943        let enclosing_excerpt = breakpoint_position.excerpt_id;
 8944        let buffer = project.read_with(cx, |project, cx| project.buffer_for_id(buffer_id, cx))?;
 8945        let buffer_snapshot = buffer.read(cx).snapshot();
 8946
 8947        let row = buffer_snapshot
 8948            .summary_for_anchor::<text::PointUtf16>(&breakpoint_position.text_anchor)
 8949            .row;
 8950
 8951        let line_len = snapshot.buffer_snapshot.line_len(MultiBufferRow(row));
 8952        let anchor_end = snapshot
 8953            .buffer_snapshot
 8954            .anchor_after(Point::new(row, line_len));
 8955
 8956        let bp = self
 8957            .breakpoint_store
 8958            .as_ref()?
 8959            .read_with(cx, |breakpoint_store, cx| {
 8960                breakpoint_store
 8961                    .breakpoints(
 8962                        &buffer,
 8963                        Some(breakpoint_position.text_anchor..anchor_end.text_anchor),
 8964                        &buffer_snapshot,
 8965                        cx,
 8966                    )
 8967                    .next()
 8968                    .and_then(|(anchor, bp)| {
 8969                        let breakpoint_row = buffer_snapshot
 8970                            .summary_for_anchor::<text::PointUtf16>(anchor)
 8971                            .row;
 8972
 8973                        if breakpoint_row == row {
 8974                            snapshot
 8975                                .buffer_snapshot
 8976                                .anchor_in_excerpt(enclosing_excerpt, *anchor)
 8977                                .map(|anchor| (anchor, bp.clone()))
 8978                        } else {
 8979                            None
 8980                        }
 8981                    })
 8982            });
 8983        bp
 8984    }
 8985
 8986    pub fn edit_log_breakpoint(
 8987        &mut self,
 8988        _: &EditLogBreakpoint,
 8989        window: &mut Window,
 8990        cx: &mut Context<Self>,
 8991    ) {
 8992        for (anchor, breakpoint) in self.breakpoints_at_cursors(window, cx) {
 8993            let breakpoint = breakpoint.unwrap_or_else(|| Breakpoint {
 8994                message: None,
 8995                state: BreakpointState::Enabled,
 8996                condition: None,
 8997                hit_condition: None,
 8998            });
 8999
 9000            self.add_edit_breakpoint_block(
 9001                anchor,
 9002                &breakpoint,
 9003                BreakpointPromptEditAction::Log,
 9004                window,
 9005                cx,
 9006            );
 9007        }
 9008    }
 9009
 9010    fn breakpoints_at_cursors(
 9011        &self,
 9012        window: &mut Window,
 9013        cx: &mut Context<Self>,
 9014    ) -> Vec<(Anchor, Option<Breakpoint>)> {
 9015        let snapshot = self.snapshot(window, cx);
 9016        let cursors = self
 9017            .selections
 9018            .disjoint_anchors()
 9019            .into_iter()
 9020            .map(|selection| {
 9021                let cursor_position: Point = selection.head().to_point(&snapshot.buffer_snapshot);
 9022
 9023                let breakpoint_position = self
 9024                    .breakpoint_at_row(cursor_position.row, window, cx)
 9025                    .map(|bp| bp.0)
 9026                    .unwrap_or_else(|| {
 9027                        snapshot
 9028                            .display_snapshot
 9029                            .buffer_snapshot
 9030                            .anchor_after(Point::new(cursor_position.row, 0))
 9031                    });
 9032
 9033                let breakpoint = self
 9034                    .breakpoint_at_anchor(breakpoint_position, &snapshot, cx)
 9035                    .map(|(anchor, breakpoint)| (anchor, Some(breakpoint)));
 9036
 9037                breakpoint.unwrap_or_else(|| (breakpoint_position, None))
 9038            })
 9039            // 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.
 9040            .collect::<HashMap<Anchor, _>>();
 9041
 9042        cursors.into_iter().collect()
 9043    }
 9044
 9045    pub fn enable_breakpoint(
 9046        &mut self,
 9047        _: &crate::actions::EnableBreakpoint,
 9048        window: &mut Window,
 9049        cx: &mut Context<Self>,
 9050    ) {
 9051        for (anchor, breakpoint) in self.breakpoints_at_cursors(window, cx) {
 9052            let Some(breakpoint) = breakpoint.filter(|breakpoint| breakpoint.is_disabled()) else {
 9053                continue;
 9054            };
 9055            self.edit_breakpoint_at_anchor(
 9056                anchor,
 9057                breakpoint,
 9058                BreakpointEditAction::InvertState,
 9059                cx,
 9060            );
 9061        }
 9062    }
 9063
 9064    pub fn disable_breakpoint(
 9065        &mut self,
 9066        _: &crate::actions::DisableBreakpoint,
 9067        window: &mut Window,
 9068        cx: &mut Context<Self>,
 9069    ) {
 9070        for (anchor, breakpoint) in self.breakpoints_at_cursors(window, cx) {
 9071            let Some(breakpoint) = breakpoint.filter(|breakpoint| breakpoint.is_enabled()) else {
 9072                continue;
 9073            };
 9074            self.edit_breakpoint_at_anchor(
 9075                anchor,
 9076                breakpoint,
 9077                BreakpointEditAction::InvertState,
 9078                cx,
 9079            );
 9080        }
 9081    }
 9082
 9083    pub fn toggle_breakpoint(
 9084        &mut self,
 9085        _: &crate::actions::ToggleBreakpoint,
 9086        window: &mut Window,
 9087        cx: &mut Context<Self>,
 9088    ) {
 9089        for (anchor, breakpoint) in self.breakpoints_at_cursors(window, cx) {
 9090            if let Some(breakpoint) = breakpoint {
 9091                self.edit_breakpoint_at_anchor(
 9092                    anchor,
 9093                    breakpoint,
 9094                    BreakpointEditAction::Toggle,
 9095                    cx,
 9096                );
 9097            } else {
 9098                self.edit_breakpoint_at_anchor(
 9099                    anchor,
 9100                    Breakpoint::new_standard(),
 9101                    BreakpointEditAction::Toggle,
 9102                    cx,
 9103                );
 9104            }
 9105        }
 9106    }
 9107
 9108    pub fn edit_breakpoint_at_anchor(
 9109        &mut self,
 9110        breakpoint_position: Anchor,
 9111        breakpoint: Breakpoint,
 9112        edit_action: BreakpointEditAction,
 9113        cx: &mut Context<Self>,
 9114    ) {
 9115        let Some(breakpoint_store) = &self.breakpoint_store else {
 9116            return;
 9117        };
 9118
 9119        let Some(buffer_id) = breakpoint_position.buffer_id.or_else(|| {
 9120            if breakpoint_position == Anchor::min() {
 9121                self.buffer()
 9122                    .read(cx)
 9123                    .excerpt_buffer_ids()
 9124                    .into_iter()
 9125                    .next()
 9126            } else {
 9127                None
 9128            }
 9129        }) else {
 9130            return;
 9131        };
 9132
 9133        let Some(buffer) = self.buffer().read(cx).buffer(buffer_id) else {
 9134            return;
 9135        };
 9136
 9137        breakpoint_store.update(cx, |breakpoint_store, cx| {
 9138            breakpoint_store.toggle_breakpoint(
 9139                buffer,
 9140                (breakpoint_position.text_anchor, breakpoint),
 9141                edit_action,
 9142                cx,
 9143            );
 9144        });
 9145
 9146        cx.notify();
 9147    }
 9148
 9149    #[cfg(any(test, feature = "test-support"))]
 9150    pub fn breakpoint_store(&self) -> Option<Entity<BreakpointStore>> {
 9151        self.breakpoint_store.clone()
 9152    }
 9153
 9154    pub fn prepare_restore_change(
 9155        &self,
 9156        revert_changes: &mut HashMap<BufferId, Vec<(Range<text::Anchor>, Rope)>>,
 9157        hunk: &MultiBufferDiffHunk,
 9158        cx: &mut App,
 9159    ) -> Option<()> {
 9160        if hunk.is_created_file() {
 9161            return None;
 9162        }
 9163        let buffer = self.buffer.read(cx);
 9164        let diff = buffer.diff_for(hunk.buffer_id)?;
 9165        let buffer = buffer.buffer(hunk.buffer_id)?;
 9166        let buffer = buffer.read(cx);
 9167        let original_text = diff
 9168            .read(cx)
 9169            .base_text()
 9170            .as_rope()
 9171            .slice(hunk.diff_base_byte_range.clone());
 9172        let buffer_snapshot = buffer.snapshot();
 9173        let buffer_revert_changes = revert_changes.entry(buffer.remote_id()).or_default();
 9174        if let Err(i) = buffer_revert_changes.binary_search_by(|probe| {
 9175            probe
 9176                .0
 9177                .start
 9178                .cmp(&hunk.buffer_range.start, &buffer_snapshot)
 9179                .then(probe.0.end.cmp(&hunk.buffer_range.end, &buffer_snapshot))
 9180        }) {
 9181            buffer_revert_changes.insert(i, (hunk.buffer_range.clone(), original_text));
 9182            Some(())
 9183        } else {
 9184            None
 9185        }
 9186    }
 9187
 9188    pub fn reverse_lines(&mut self, _: &ReverseLines, window: &mut Window, cx: &mut Context<Self>) {
 9189        self.manipulate_lines(window, cx, |lines| lines.reverse())
 9190    }
 9191
 9192    pub fn shuffle_lines(&mut self, _: &ShuffleLines, window: &mut Window, cx: &mut Context<Self>) {
 9193        self.manipulate_lines(window, cx, |lines| lines.shuffle(&mut thread_rng()))
 9194    }
 9195
 9196    fn manipulate_lines<Fn>(
 9197        &mut self,
 9198        window: &mut Window,
 9199        cx: &mut Context<Self>,
 9200        mut callback: Fn,
 9201    ) where
 9202        Fn: FnMut(&mut Vec<&str>),
 9203    {
 9204        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
 9205
 9206        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 9207        let buffer = self.buffer.read(cx).snapshot(cx);
 9208
 9209        let mut edits = Vec::new();
 9210
 9211        let selections = self.selections.all::<Point>(cx);
 9212        let mut selections = selections.iter().peekable();
 9213        let mut contiguous_row_selections = Vec::new();
 9214        let mut new_selections = Vec::new();
 9215        let mut added_lines = 0;
 9216        let mut removed_lines = 0;
 9217
 9218        while let Some(selection) = selections.next() {
 9219            let (start_row, end_row) = consume_contiguous_rows(
 9220                &mut contiguous_row_selections,
 9221                selection,
 9222                &display_map,
 9223                &mut selections,
 9224            );
 9225
 9226            let start_point = Point::new(start_row.0, 0);
 9227            let end_point = Point::new(
 9228                end_row.previous_row().0,
 9229                buffer.line_len(end_row.previous_row()),
 9230            );
 9231            let text = buffer
 9232                .text_for_range(start_point..end_point)
 9233                .collect::<String>();
 9234
 9235            let mut lines = text.split('\n').collect_vec();
 9236
 9237            let lines_before = lines.len();
 9238            callback(&mut lines);
 9239            let lines_after = lines.len();
 9240
 9241            edits.push((start_point..end_point, lines.join("\n")));
 9242
 9243            // Selections must change based on added and removed line count
 9244            let start_row =
 9245                MultiBufferRow(start_point.row + added_lines as u32 - removed_lines as u32);
 9246            let end_row = MultiBufferRow(start_row.0 + lines_after.saturating_sub(1) as u32);
 9247            new_selections.push(Selection {
 9248                id: selection.id,
 9249                start: start_row,
 9250                end: end_row,
 9251                goal: SelectionGoal::None,
 9252                reversed: selection.reversed,
 9253            });
 9254
 9255            if lines_after > lines_before {
 9256                added_lines += lines_after - lines_before;
 9257            } else if lines_before > lines_after {
 9258                removed_lines += lines_before - lines_after;
 9259            }
 9260        }
 9261
 9262        self.transact(window, cx, |this, window, cx| {
 9263            let buffer = this.buffer.update(cx, |buffer, cx| {
 9264                buffer.edit(edits, None, cx);
 9265                buffer.snapshot(cx)
 9266            });
 9267
 9268            // Recalculate offsets on newly edited buffer
 9269            let new_selections = new_selections
 9270                .iter()
 9271                .map(|s| {
 9272                    let start_point = Point::new(s.start.0, 0);
 9273                    let end_point = Point::new(s.end.0, buffer.line_len(s.end));
 9274                    Selection {
 9275                        id: s.id,
 9276                        start: buffer.point_to_offset(start_point),
 9277                        end: buffer.point_to_offset(end_point),
 9278                        goal: s.goal,
 9279                        reversed: s.reversed,
 9280                    }
 9281                })
 9282                .collect();
 9283
 9284            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9285                s.select(new_selections);
 9286            });
 9287
 9288            this.request_autoscroll(Autoscroll::fit(), cx);
 9289        });
 9290    }
 9291
 9292    pub fn toggle_case(&mut self, _: &ToggleCase, window: &mut Window, cx: &mut Context<Self>) {
 9293        self.manipulate_text(window, cx, |text| {
 9294            let has_upper_case_characters = text.chars().any(|c| c.is_uppercase());
 9295            if has_upper_case_characters {
 9296                text.to_lowercase()
 9297            } else {
 9298                text.to_uppercase()
 9299            }
 9300        })
 9301    }
 9302
 9303    pub fn convert_to_upper_case(
 9304        &mut self,
 9305        _: &ConvertToUpperCase,
 9306        window: &mut Window,
 9307        cx: &mut Context<Self>,
 9308    ) {
 9309        self.manipulate_text(window, cx, |text| text.to_uppercase())
 9310    }
 9311
 9312    pub fn convert_to_lower_case(
 9313        &mut self,
 9314        _: &ConvertToLowerCase,
 9315        window: &mut Window,
 9316        cx: &mut Context<Self>,
 9317    ) {
 9318        self.manipulate_text(window, cx, |text| text.to_lowercase())
 9319    }
 9320
 9321    pub fn convert_to_title_case(
 9322        &mut self,
 9323        _: &ConvertToTitleCase,
 9324        window: &mut Window,
 9325        cx: &mut Context<Self>,
 9326    ) {
 9327        self.manipulate_text(window, cx, |text| {
 9328            text.split('\n')
 9329                .map(|line| line.to_case(Case::Title))
 9330                .join("\n")
 9331        })
 9332    }
 9333
 9334    pub fn convert_to_snake_case(
 9335        &mut self,
 9336        _: &ConvertToSnakeCase,
 9337        window: &mut Window,
 9338        cx: &mut Context<Self>,
 9339    ) {
 9340        self.manipulate_text(window, cx, |text| text.to_case(Case::Snake))
 9341    }
 9342
 9343    pub fn convert_to_kebab_case(
 9344        &mut self,
 9345        _: &ConvertToKebabCase,
 9346        window: &mut Window,
 9347        cx: &mut Context<Self>,
 9348    ) {
 9349        self.manipulate_text(window, cx, |text| text.to_case(Case::Kebab))
 9350    }
 9351
 9352    pub fn convert_to_upper_camel_case(
 9353        &mut self,
 9354        _: &ConvertToUpperCamelCase,
 9355        window: &mut Window,
 9356        cx: &mut Context<Self>,
 9357    ) {
 9358        self.manipulate_text(window, cx, |text| {
 9359            text.split('\n')
 9360                .map(|line| line.to_case(Case::UpperCamel))
 9361                .join("\n")
 9362        })
 9363    }
 9364
 9365    pub fn convert_to_lower_camel_case(
 9366        &mut self,
 9367        _: &ConvertToLowerCamelCase,
 9368        window: &mut Window,
 9369        cx: &mut Context<Self>,
 9370    ) {
 9371        self.manipulate_text(window, cx, |text| text.to_case(Case::Camel))
 9372    }
 9373
 9374    pub fn convert_to_opposite_case(
 9375        &mut self,
 9376        _: &ConvertToOppositeCase,
 9377        window: &mut Window,
 9378        cx: &mut Context<Self>,
 9379    ) {
 9380        self.manipulate_text(window, cx, |text| {
 9381            text.chars()
 9382                .fold(String::with_capacity(text.len()), |mut t, c| {
 9383                    if c.is_uppercase() {
 9384                        t.extend(c.to_lowercase());
 9385                    } else {
 9386                        t.extend(c.to_uppercase());
 9387                    }
 9388                    t
 9389                })
 9390        })
 9391    }
 9392
 9393    pub fn convert_to_rot13(
 9394        &mut self,
 9395        _: &ConvertToRot13,
 9396        window: &mut Window,
 9397        cx: &mut Context<Self>,
 9398    ) {
 9399        self.manipulate_text(window, cx, |text| {
 9400            text.chars()
 9401                .map(|c| match c {
 9402                    'A'..='M' | 'a'..='m' => ((c as u8) + 13) as char,
 9403                    'N'..='Z' | 'n'..='z' => ((c as u8) - 13) as char,
 9404                    _ => c,
 9405                })
 9406                .collect()
 9407        })
 9408    }
 9409
 9410    pub fn convert_to_rot47(
 9411        &mut self,
 9412        _: &ConvertToRot47,
 9413        window: &mut Window,
 9414        cx: &mut Context<Self>,
 9415    ) {
 9416        self.manipulate_text(window, cx, |text| {
 9417            text.chars()
 9418                .map(|c| {
 9419                    let code_point = c as u32;
 9420                    if code_point >= 33 && code_point <= 126 {
 9421                        return char::from_u32(33 + ((code_point + 14) % 94)).unwrap();
 9422                    }
 9423                    c
 9424                })
 9425                .collect()
 9426        })
 9427    }
 9428
 9429    fn manipulate_text<Fn>(&mut self, window: &mut Window, cx: &mut Context<Self>, mut callback: Fn)
 9430    where
 9431        Fn: FnMut(&str) -> String,
 9432    {
 9433        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 9434        let buffer = self.buffer.read(cx).snapshot(cx);
 9435
 9436        let mut new_selections = Vec::new();
 9437        let mut edits = Vec::new();
 9438        let mut selection_adjustment = 0i32;
 9439
 9440        for selection in self.selections.all::<usize>(cx) {
 9441            let selection_is_empty = selection.is_empty();
 9442
 9443            let (start, end) = if selection_is_empty {
 9444                let word_range = movement::surrounding_word(
 9445                    &display_map,
 9446                    selection.start.to_display_point(&display_map),
 9447                );
 9448                let start = word_range.start.to_offset(&display_map, Bias::Left);
 9449                let end = word_range.end.to_offset(&display_map, Bias::Left);
 9450                (start, end)
 9451            } else {
 9452                (selection.start, selection.end)
 9453            };
 9454
 9455            let text = buffer.text_for_range(start..end).collect::<String>();
 9456            let old_length = text.len() as i32;
 9457            let text = callback(&text);
 9458
 9459            new_selections.push(Selection {
 9460                start: (start as i32 - selection_adjustment) as usize,
 9461                end: ((start + text.len()) as i32 - selection_adjustment) as usize,
 9462                goal: SelectionGoal::None,
 9463                ..selection
 9464            });
 9465
 9466            selection_adjustment += old_length - text.len() as i32;
 9467
 9468            edits.push((start..end, text));
 9469        }
 9470
 9471        self.transact(window, cx, |this, window, cx| {
 9472            this.buffer.update(cx, |buffer, cx| {
 9473                buffer.edit(edits, None, cx);
 9474            });
 9475
 9476            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9477                s.select(new_selections);
 9478            });
 9479
 9480            this.request_autoscroll(Autoscroll::fit(), cx);
 9481        });
 9482    }
 9483
 9484    pub fn duplicate(
 9485        &mut self,
 9486        upwards: bool,
 9487        whole_lines: bool,
 9488        window: &mut Window,
 9489        cx: &mut Context<Self>,
 9490    ) {
 9491        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
 9492
 9493        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 9494        let buffer = &display_map.buffer_snapshot;
 9495        let selections = self.selections.all::<Point>(cx);
 9496
 9497        let mut edits = Vec::new();
 9498        let mut selections_iter = selections.iter().peekable();
 9499        while let Some(selection) = selections_iter.next() {
 9500            let mut rows = selection.spanned_rows(false, &display_map);
 9501            // duplicate line-wise
 9502            if whole_lines || selection.start == selection.end {
 9503                // Avoid duplicating the same lines twice.
 9504                while let Some(next_selection) = selections_iter.peek() {
 9505                    let next_rows = next_selection.spanned_rows(false, &display_map);
 9506                    if next_rows.start < rows.end {
 9507                        rows.end = next_rows.end;
 9508                        selections_iter.next().unwrap();
 9509                    } else {
 9510                        break;
 9511                    }
 9512                }
 9513
 9514                // Copy the text from the selected row region and splice it either at the start
 9515                // or end of the region.
 9516                let start = Point::new(rows.start.0, 0);
 9517                let end = Point::new(
 9518                    rows.end.previous_row().0,
 9519                    buffer.line_len(rows.end.previous_row()),
 9520                );
 9521                let text = buffer
 9522                    .text_for_range(start..end)
 9523                    .chain(Some("\n"))
 9524                    .collect::<String>();
 9525                let insert_location = if upwards {
 9526                    Point::new(rows.end.0, 0)
 9527                } else {
 9528                    start
 9529                };
 9530                edits.push((insert_location..insert_location, text));
 9531            } else {
 9532                // duplicate character-wise
 9533                let start = selection.start;
 9534                let end = selection.end;
 9535                let text = buffer.text_for_range(start..end).collect::<String>();
 9536                edits.push((selection.end..selection.end, text));
 9537            }
 9538        }
 9539
 9540        self.transact(window, cx, |this, _, cx| {
 9541            this.buffer.update(cx, |buffer, cx| {
 9542                buffer.edit(edits, None, cx);
 9543            });
 9544
 9545            this.request_autoscroll(Autoscroll::fit(), cx);
 9546        });
 9547    }
 9548
 9549    pub fn duplicate_line_up(
 9550        &mut self,
 9551        _: &DuplicateLineUp,
 9552        window: &mut Window,
 9553        cx: &mut Context<Self>,
 9554    ) {
 9555        self.duplicate(true, true, window, cx);
 9556    }
 9557
 9558    pub fn duplicate_line_down(
 9559        &mut self,
 9560        _: &DuplicateLineDown,
 9561        window: &mut Window,
 9562        cx: &mut Context<Self>,
 9563    ) {
 9564        self.duplicate(false, true, window, cx);
 9565    }
 9566
 9567    pub fn duplicate_selection(
 9568        &mut self,
 9569        _: &DuplicateSelection,
 9570        window: &mut Window,
 9571        cx: &mut Context<Self>,
 9572    ) {
 9573        self.duplicate(false, false, window, cx);
 9574    }
 9575
 9576    pub fn move_line_up(&mut self, _: &MoveLineUp, window: &mut Window, cx: &mut Context<Self>) {
 9577        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
 9578
 9579        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 9580        let buffer = self.buffer.read(cx).snapshot(cx);
 9581
 9582        let mut edits = Vec::new();
 9583        let mut unfold_ranges = Vec::new();
 9584        let mut refold_creases = Vec::new();
 9585
 9586        let selections = self.selections.all::<Point>(cx);
 9587        let mut selections = selections.iter().peekable();
 9588        let mut contiguous_row_selections = Vec::new();
 9589        let mut new_selections = Vec::new();
 9590
 9591        while let Some(selection) = selections.next() {
 9592            // Find all the selections that span a contiguous row range
 9593            let (start_row, end_row) = consume_contiguous_rows(
 9594                &mut contiguous_row_selections,
 9595                selection,
 9596                &display_map,
 9597                &mut selections,
 9598            );
 9599
 9600            // Move the text spanned by the row range to be before the line preceding the row range
 9601            if start_row.0 > 0 {
 9602                let range_to_move = Point::new(
 9603                    start_row.previous_row().0,
 9604                    buffer.line_len(start_row.previous_row()),
 9605                )
 9606                    ..Point::new(
 9607                        end_row.previous_row().0,
 9608                        buffer.line_len(end_row.previous_row()),
 9609                    );
 9610                let insertion_point = display_map
 9611                    .prev_line_boundary(Point::new(start_row.previous_row().0, 0))
 9612                    .0;
 9613
 9614                // Don't move lines across excerpts
 9615                if buffer
 9616                    .excerpt_containing(insertion_point..range_to_move.end)
 9617                    .is_some()
 9618                {
 9619                    let text = buffer
 9620                        .text_for_range(range_to_move.clone())
 9621                        .flat_map(|s| s.chars())
 9622                        .skip(1)
 9623                        .chain(['\n'])
 9624                        .collect::<String>();
 9625
 9626                    edits.push((
 9627                        buffer.anchor_after(range_to_move.start)
 9628                            ..buffer.anchor_before(range_to_move.end),
 9629                        String::new(),
 9630                    ));
 9631                    let insertion_anchor = buffer.anchor_after(insertion_point);
 9632                    edits.push((insertion_anchor..insertion_anchor, text));
 9633
 9634                    let row_delta = range_to_move.start.row - insertion_point.row + 1;
 9635
 9636                    // Move selections up
 9637                    new_selections.extend(contiguous_row_selections.drain(..).map(
 9638                        |mut selection| {
 9639                            selection.start.row -= row_delta;
 9640                            selection.end.row -= row_delta;
 9641                            selection
 9642                        },
 9643                    ));
 9644
 9645                    // Move folds up
 9646                    unfold_ranges.push(range_to_move.clone());
 9647                    for fold in display_map.folds_in_range(
 9648                        buffer.anchor_before(range_to_move.start)
 9649                            ..buffer.anchor_after(range_to_move.end),
 9650                    ) {
 9651                        let mut start = fold.range.start.to_point(&buffer);
 9652                        let mut end = fold.range.end.to_point(&buffer);
 9653                        start.row -= row_delta;
 9654                        end.row -= row_delta;
 9655                        refold_creases.push(Crease::simple(start..end, fold.placeholder.clone()));
 9656                    }
 9657                }
 9658            }
 9659
 9660            // If we didn't move line(s), preserve the existing selections
 9661            new_selections.append(&mut contiguous_row_selections);
 9662        }
 9663
 9664        self.transact(window, cx, |this, window, cx| {
 9665            this.unfold_ranges(&unfold_ranges, true, true, cx);
 9666            this.buffer.update(cx, |buffer, cx| {
 9667                for (range, text) in edits {
 9668                    buffer.edit([(range, text)], None, cx);
 9669                }
 9670            });
 9671            this.fold_creases(refold_creases, true, window, cx);
 9672            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9673                s.select(new_selections);
 9674            })
 9675        });
 9676    }
 9677
 9678    pub fn move_line_down(
 9679        &mut self,
 9680        _: &MoveLineDown,
 9681        window: &mut Window,
 9682        cx: &mut Context<Self>,
 9683    ) {
 9684        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
 9685
 9686        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 9687        let buffer = self.buffer.read(cx).snapshot(cx);
 9688
 9689        let mut edits = Vec::new();
 9690        let mut unfold_ranges = Vec::new();
 9691        let mut refold_creases = Vec::new();
 9692
 9693        let selections = self.selections.all::<Point>(cx);
 9694        let mut selections = selections.iter().peekable();
 9695        let mut contiguous_row_selections = Vec::new();
 9696        let mut new_selections = Vec::new();
 9697
 9698        while let Some(selection) = selections.next() {
 9699            // Find all the selections that span a contiguous row range
 9700            let (start_row, end_row) = consume_contiguous_rows(
 9701                &mut contiguous_row_selections,
 9702                selection,
 9703                &display_map,
 9704                &mut selections,
 9705            );
 9706
 9707            // Move the text spanned by the row range to be after the last line of the row range
 9708            if end_row.0 <= buffer.max_point().row {
 9709                let range_to_move =
 9710                    MultiBufferPoint::new(start_row.0, 0)..MultiBufferPoint::new(end_row.0, 0);
 9711                let insertion_point = display_map
 9712                    .next_line_boundary(MultiBufferPoint::new(end_row.0, 0))
 9713                    .0;
 9714
 9715                // Don't move lines across excerpt boundaries
 9716                if buffer
 9717                    .excerpt_containing(range_to_move.start..insertion_point)
 9718                    .is_some()
 9719                {
 9720                    let mut text = String::from("\n");
 9721                    text.extend(buffer.text_for_range(range_to_move.clone()));
 9722                    text.pop(); // Drop trailing newline
 9723                    edits.push((
 9724                        buffer.anchor_after(range_to_move.start)
 9725                            ..buffer.anchor_before(range_to_move.end),
 9726                        String::new(),
 9727                    ));
 9728                    let insertion_anchor = buffer.anchor_after(insertion_point);
 9729                    edits.push((insertion_anchor..insertion_anchor, text));
 9730
 9731                    let row_delta = insertion_point.row - range_to_move.end.row + 1;
 9732
 9733                    // Move selections down
 9734                    new_selections.extend(contiguous_row_selections.drain(..).map(
 9735                        |mut selection| {
 9736                            selection.start.row += row_delta;
 9737                            selection.end.row += row_delta;
 9738                            selection
 9739                        },
 9740                    ));
 9741
 9742                    // Move folds down
 9743                    unfold_ranges.push(range_to_move.clone());
 9744                    for fold in display_map.folds_in_range(
 9745                        buffer.anchor_before(range_to_move.start)
 9746                            ..buffer.anchor_after(range_to_move.end),
 9747                    ) {
 9748                        let mut start = fold.range.start.to_point(&buffer);
 9749                        let mut end = fold.range.end.to_point(&buffer);
 9750                        start.row += row_delta;
 9751                        end.row += row_delta;
 9752                        refold_creases.push(Crease::simple(start..end, fold.placeholder.clone()));
 9753                    }
 9754                }
 9755            }
 9756
 9757            // If we didn't move line(s), preserve the existing selections
 9758            new_selections.append(&mut contiguous_row_selections);
 9759        }
 9760
 9761        self.transact(window, cx, |this, window, cx| {
 9762            this.unfold_ranges(&unfold_ranges, true, true, cx);
 9763            this.buffer.update(cx, |buffer, cx| {
 9764                for (range, text) in edits {
 9765                    buffer.edit([(range, text)], None, cx);
 9766                }
 9767            });
 9768            this.fold_creases(refold_creases, true, window, cx);
 9769            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9770                s.select(new_selections)
 9771            });
 9772        });
 9773    }
 9774
 9775    pub fn transpose(&mut self, _: &Transpose, window: &mut Window, cx: &mut Context<Self>) {
 9776        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
 9777        let text_layout_details = &self.text_layout_details(window);
 9778        self.transact(window, cx, |this, window, cx| {
 9779            let edits = this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9780                let mut edits: Vec<(Range<usize>, String)> = Default::default();
 9781                s.move_with(|display_map, selection| {
 9782                    if !selection.is_empty() {
 9783                        return;
 9784                    }
 9785
 9786                    let mut head = selection.head();
 9787                    let mut transpose_offset = head.to_offset(display_map, Bias::Right);
 9788                    if head.column() == display_map.line_len(head.row()) {
 9789                        transpose_offset = display_map
 9790                            .buffer_snapshot
 9791                            .clip_offset(transpose_offset.saturating_sub(1), Bias::Left);
 9792                    }
 9793
 9794                    if transpose_offset == 0 {
 9795                        return;
 9796                    }
 9797
 9798                    *head.column_mut() += 1;
 9799                    head = display_map.clip_point(head, Bias::Right);
 9800                    let goal = SelectionGoal::HorizontalPosition(
 9801                        display_map
 9802                            .x_for_display_point(head, text_layout_details)
 9803                            .into(),
 9804                    );
 9805                    selection.collapse_to(head, goal);
 9806
 9807                    let transpose_start = display_map
 9808                        .buffer_snapshot
 9809                        .clip_offset(transpose_offset.saturating_sub(1), Bias::Left);
 9810                    if edits.last().map_or(true, |e| e.0.end <= transpose_start) {
 9811                        let transpose_end = display_map
 9812                            .buffer_snapshot
 9813                            .clip_offset(transpose_offset + 1, Bias::Right);
 9814                        if let Some(ch) =
 9815                            display_map.buffer_snapshot.chars_at(transpose_start).next()
 9816                        {
 9817                            edits.push((transpose_start..transpose_offset, String::new()));
 9818                            edits.push((transpose_end..transpose_end, ch.to_string()));
 9819                        }
 9820                    }
 9821                });
 9822                edits
 9823            });
 9824            this.buffer
 9825                .update(cx, |buffer, cx| buffer.edit(edits, None, cx));
 9826            let selections = this.selections.all::<usize>(cx);
 9827            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9828                s.select(selections);
 9829            });
 9830        });
 9831    }
 9832
 9833    pub fn rewrap(&mut self, _: &Rewrap, _: &mut Window, cx: &mut Context<Self>) {
 9834        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
 9835        self.rewrap_impl(RewrapOptions::default(), cx)
 9836    }
 9837
 9838    pub fn rewrap_impl(&mut self, options: RewrapOptions, cx: &mut Context<Self>) {
 9839        let buffer = self.buffer.read(cx).snapshot(cx);
 9840        let selections = self.selections.all::<Point>(cx);
 9841        let mut selections = selections.iter().peekable();
 9842
 9843        let mut edits = Vec::new();
 9844        let mut rewrapped_row_ranges = Vec::<RangeInclusive<u32>>::new();
 9845
 9846        while let Some(selection) = selections.next() {
 9847            let mut start_row = selection.start.row;
 9848            let mut end_row = selection.end.row;
 9849
 9850            // Skip selections that overlap with a range that has already been rewrapped.
 9851            let selection_range = start_row..end_row;
 9852            if rewrapped_row_ranges
 9853                .iter()
 9854                .any(|range| range.overlaps(&selection_range))
 9855            {
 9856                continue;
 9857            }
 9858
 9859            let tab_size = buffer.language_settings_at(selection.head(), cx).tab_size;
 9860
 9861            // Since not all lines in the selection may be at the same indent
 9862            // level, choose the indent size that is the most common between all
 9863            // of the lines.
 9864            //
 9865            // If there is a tie, we use the deepest indent.
 9866            let (indent_size, indent_end) = {
 9867                let mut indent_size_occurrences = HashMap::default();
 9868                let mut rows_by_indent_size = HashMap::<IndentSize, Vec<u32>>::default();
 9869
 9870                for row in start_row..=end_row {
 9871                    let indent = buffer.indent_size_for_line(MultiBufferRow(row));
 9872                    rows_by_indent_size.entry(indent).or_default().push(row);
 9873                    *indent_size_occurrences.entry(indent).or_insert(0) += 1;
 9874                }
 9875
 9876                let indent_size = indent_size_occurrences
 9877                    .into_iter()
 9878                    .max_by_key(|(indent, count)| (*count, indent.len_with_expanded_tabs(tab_size)))
 9879                    .map(|(indent, _)| indent)
 9880                    .unwrap_or_default();
 9881                let row = rows_by_indent_size[&indent_size][0];
 9882                let indent_end = Point::new(row, indent_size.len);
 9883
 9884                (indent_size, indent_end)
 9885            };
 9886
 9887            let mut line_prefix = indent_size.chars().collect::<String>();
 9888
 9889            let mut inside_comment = false;
 9890            if let Some(comment_prefix) =
 9891                buffer
 9892                    .language_scope_at(selection.head())
 9893                    .and_then(|language| {
 9894                        language
 9895                            .line_comment_prefixes()
 9896                            .iter()
 9897                            .find(|prefix| buffer.contains_str_at(indent_end, prefix))
 9898                            .cloned()
 9899                    })
 9900            {
 9901                line_prefix.push_str(&comment_prefix);
 9902                inside_comment = true;
 9903            }
 9904
 9905            let language_settings = buffer.language_settings_at(selection.head(), cx);
 9906            let allow_rewrap_based_on_language = match language_settings.allow_rewrap {
 9907                RewrapBehavior::InComments => inside_comment,
 9908                RewrapBehavior::InSelections => !selection.is_empty(),
 9909                RewrapBehavior::Anywhere => true,
 9910            };
 9911
 9912            let should_rewrap = options.override_language_settings
 9913                || allow_rewrap_based_on_language
 9914                || self.hard_wrap.is_some();
 9915            if !should_rewrap {
 9916                continue;
 9917            }
 9918
 9919            if selection.is_empty() {
 9920                'expand_upwards: while start_row > 0 {
 9921                    let prev_row = start_row - 1;
 9922                    if buffer.contains_str_at(Point::new(prev_row, 0), &line_prefix)
 9923                        && buffer.line_len(MultiBufferRow(prev_row)) as usize > line_prefix.len()
 9924                    {
 9925                        start_row = prev_row;
 9926                    } else {
 9927                        break 'expand_upwards;
 9928                    }
 9929                }
 9930
 9931                'expand_downwards: while end_row < buffer.max_point().row {
 9932                    let next_row = end_row + 1;
 9933                    if buffer.contains_str_at(Point::new(next_row, 0), &line_prefix)
 9934                        && buffer.line_len(MultiBufferRow(next_row)) as usize > line_prefix.len()
 9935                    {
 9936                        end_row = next_row;
 9937                    } else {
 9938                        break 'expand_downwards;
 9939                    }
 9940                }
 9941            }
 9942
 9943            let start = Point::new(start_row, 0);
 9944            let start_offset = start.to_offset(&buffer);
 9945            let end = Point::new(end_row, buffer.line_len(MultiBufferRow(end_row)));
 9946            let selection_text = buffer.text_for_range(start..end).collect::<String>();
 9947            let Some(lines_without_prefixes) = selection_text
 9948                .lines()
 9949                .map(|line| {
 9950                    line.strip_prefix(&line_prefix)
 9951                        .or_else(|| line.trim_start().strip_prefix(&line_prefix.trim_start()))
 9952                        .ok_or_else(|| {
 9953                            anyhow!("line did not start with prefix {line_prefix:?}: {line:?}")
 9954                        })
 9955                })
 9956                .collect::<Result<Vec<_>, _>>()
 9957                .log_err()
 9958            else {
 9959                continue;
 9960            };
 9961
 9962            let wrap_column = self.hard_wrap.unwrap_or_else(|| {
 9963                buffer
 9964                    .language_settings_at(Point::new(start_row, 0), cx)
 9965                    .preferred_line_length as usize
 9966            });
 9967            let wrapped_text = wrap_with_prefix(
 9968                line_prefix,
 9969                lines_without_prefixes.join("\n"),
 9970                wrap_column,
 9971                tab_size,
 9972                options.preserve_existing_whitespace,
 9973            );
 9974
 9975            // TODO: should always use char-based diff while still supporting cursor behavior that
 9976            // matches vim.
 9977            let mut diff_options = DiffOptions::default();
 9978            if options.override_language_settings {
 9979                diff_options.max_word_diff_len = 0;
 9980                diff_options.max_word_diff_line_count = 0;
 9981            } else {
 9982                diff_options.max_word_diff_len = usize::MAX;
 9983                diff_options.max_word_diff_line_count = usize::MAX;
 9984            }
 9985
 9986            for (old_range, new_text) in
 9987                text_diff_with_options(&selection_text, &wrapped_text, diff_options)
 9988            {
 9989                let edit_start = buffer.anchor_after(start_offset + old_range.start);
 9990                let edit_end = buffer.anchor_after(start_offset + old_range.end);
 9991                edits.push((edit_start..edit_end, new_text));
 9992            }
 9993
 9994            rewrapped_row_ranges.push(start_row..=end_row);
 9995        }
 9996
 9997        self.buffer
 9998            .update(cx, |buffer, cx| buffer.edit(edits, None, cx));
 9999    }
10000
10001    pub fn cut_common(&mut self, window: &mut Window, cx: &mut Context<Self>) -> ClipboardItem {
10002        let mut text = String::new();
10003        let buffer = self.buffer.read(cx).snapshot(cx);
10004        let mut selections = self.selections.all::<Point>(cx);
10005        let mut clipboard_selections = Vec::with_capacity(selections.len());
10006        {
10007            let max_point = buffer.max_point();
10008            let mut is_first = true;
10009            for selection in &mut selections {
10010                let is_entire_line = selection.is_empty() || self.selections.line_mode;
10011                if is_entire_line {
10012                    selection.start = Point::new(selection.start.row, 0);
10013                    if !selection.is_empty() && selection.end.column == 0 {
10014                        selection.end = cmp::min(max_point, selection.end);
10015                    } else {
10016                        selection.end = cmp::min(max_point, Point::new(selection.end.row + 1, 0));
10017                    }
10018                    selection.goal = SelectionGoal::None;
10019                }
10020                if is_first {
10021                    is_first = false;
10022                } else {
10023                    text += "\n";
10024                }
10025                let mut len = 0;
10026                for chunk in buffer.text_for_range(selection.start..selection.end) {
10027                    text.push_str(chunk);
10028                    len += chunk.len();
10029                }
10030                clipboard_selections.push(ClipboardSelection {
10031                    len,
10032                    is_entire_line,
10033                    first_line_indent: buffer
10034                        .indent_size_for_line(MultiBufferRow(selection.start.row))
10035                        .len,
10036                });
10037            }
10038        }
10039
10040        self.transact(window, cx, |this, window, cx| {
10041            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10042                s.select(selections);
10043            });
10044            this.insert("", window, cx);
10045        });
10046        ClipboardItem::new_string_with_json_metadata(text, clipboard_selections)
10047    }
10048
10049    pub fn cut(&mut self, _: &Cut, window: &mut Window, cx: &mut Context<Self>) {
10050        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
10051        let item = self.cut_common(window, cx);
10052        cx.write_to_clipboard(item);
10053    }
10054
10055    pub fn kill_ring_cut(&mut self, _: &KillRingCut, window: &mut Window, cx: &mut Context<Self>) {
10056        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
10057        self.change_selections(None, window, cx, |s| {
10058            s.move_with(|snapshot, sel| {
10059                if sel.is_empty() {
10060                    sel.end = DisplayPoint::new(sel.end.row(), snapshot.line_len(sel.end.row()))
10061                }
10062            });
10063        });
10064        let item = self.cut_common(window, cx);
10065        cx.set_global(KillRing(item))
10066    }
10067
10068    pub fn kill_ring_yank(
10069        &mut self,
10070        _: &KillRingYank,
10071        window: &mut Window,
10072        cx: &mut Context<Self>,
10073    ) {
10074        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
10075        let (text, metadata) = if let Some(KillRing(item)) = cx.try_global() {
10076            if let Some(ClipboardEntry::String(kill_ring)) = item.entries().first() {
10077                (kill_ring.text().to_string(), kill_ring.metadata_json())
10078            } else {
10079                return;
10080            }
10081        } else {
10082            return;
10083        };
10084        self.do_paste(&text, metadata, false, window, cx);
10085    }
10086
10087    pub fn copy_and_trim(&mut self, _: &CopyAndTrim, _: &mut Window, cx: &mut Context<Self>) {
10088        self.do_copy(true, cx);
10089    }
10090
10091    pub fn copy(&mut self, _: &Copy, _: &mut Window, cx: &mut Context<Self>) {
10092        self.do_copy(false, cx);
10093    }
10094
10095    fn do_copy(&self, strip_leading_indents: bool, cx: &mut Context<Self>) {
10096        let selections = self.selections.all::<Point>(cx);
10097        let buffer = self.buffer.read(cx).read(cx);
10098        let mut text = String::new();
10099
10100        let mut clipboard_selections = Vec::with_capacity(selections.len());
10101        {
10102            let max_point = buffer.max_point();
10103            let mut is_first = true;
10104            for selection in &selections {
10105                let mut start = selection.start;
10106                let mut end = selection.end;
10107                let is_entire_line = selection.is_empty() || self.selections.line_mode;
10108                if is_entire_line {
10109                    start = Point::new(start.row, 0);
10110                    end = cmp::min(max_point, Point::new(end.row + 1, 0));
10111                }
10112
10113                let mut trimmed_selections = Vec::new();
10114                if strip_leading_indents && end.row.saturating_sub(start.row) > 0 {
10115                    let row = MultiBufferRow(start.row);
10116                    let first_indent = buffer.indent_size_for_line(row);
10117                    if first_indent.len == 0 || start.column > first_indent.len {
10118                        trimmed_selections.push(start..end);
10119                    } else {
10120                        trimmed_selections.push(
10121                            Point::new(row.0, first_indent.len)
10122                                ..Point::new(row.0, buffer.line_len(row)),
10123                        );
10124                        for row in start.row + 1..=end.row {
10125                            let mut line_len = buffer.line_len(MultiBufferRow(row));
10126                            if row == end.row {
10127                                line_len = end.column;
10128                            }
10129                            if line_len == 0 {
10130                                trimmed_selections
10131                                    .push(Point::new(row, 0)..Point::new(row, line_len));
10132                                continue;
10133                            }
10134                            let row_indent_size = buffer.indent_size_for_line(MultiBufferRow(row));
10135                            if row_indent_size.len >= first_indent.len {
10136                                trimmed_selections.push(
10137                                    Point::new(row, first_indent.len)..Point::new(row, line_len),
10138                                );
10139                            } else {
10140                                trimmed_selections.clear();
10141                                trimmed_selections.push(start..end);
10142                                break;
10143                            }
10144                        }
10145                    }
10146                } else {
10147                    trimmed_selections.push(start..end);
10148                }
10149
10150                for trimmed_range in trimmed_selections {
10151                    if is_first {
10152                        is_first = false;
10153                    } else {
10154                        text += "\n";
10155                    }
10156                    let mut len = 0;
10157                    for chunk in buffer.text_for_range(trimmed_range.start..trimmed_range.end) {
10158                        text.push_str(chunk);
10159                        len += chunk.len();
10160                    }
10161                    clipboard_selections.push(ClipboardSelection {
10162                        len,
10163                        is_entire_line,
10164                        first_line_indent: buffer
10165                            .indent_size_for_line(MultiBufferRow(trimmed_range.start.row))
10166                            .len,
10167                    });
10168                }
10169            }
10170        }
10171
10172        cx.write_to_clipboard(ClipboardItem::new_string_with_json_metadata(
10173            text,
10174            clipboard_selections,
10175        ));
10176    }
10177
10178    pub fn do_paste(
10179        &mut self,
10180        text: &String,
10181        clipboard_selections: Option<Vec<ClipboardSelection>>,
10182        handle_entire_lines: bool,
10183        window: &mut Window,
10184        cx: &mut Context<Self>,
10185    ) {
10186        if self.read_only(cx) {
10187            return;
10188        }
10189
10190        let clipboard_text = Cow::Borrowed(text);
10191
10192        self.transact(window, cx, |this, window, cx| {
10193            if let Some(mut clipboard_selections) = clipboard_selections {
10194                let old_selections = this.selections.all::<usize>(cx);
10195                let all_selections_were_entire_line =
10196                    clipboard_selections.iter().all(|s| s.is_entire_line);
10197                let first_selection_indent_column =
10198                    clipboard_selections.first().map(|s| s.first_line_indent);
10199                if clipboard_selections.len() != old_selections.len() {
10200                    clipboard_selections.drain(..);
10201                }
10202                let cursor_offset = this.selections.last::<usize>(cx).head();
10203                let mut auto_indent_on_paste = true;
10204
10205                this.buffer.update(cx, |buffer, cx| {
10206                    let snapshot = buffer.read(cx);
10207                    auto_indent_on_paste = snapshot
10208                        .language_settings_at(cursor_offset, cx)
10209                        .auto_indent_on_paste;
10210
10211                    let mut start_offset = 0;
10212                    let mut edits = Vec::new();
10213                    let mut original_indent_columns = Vec::new();
10214                    for (ix, selection) in old_selections.iter().enumerate() {
10215                        let to_insert;
10216                        let entire_line;
10217                        let original_indent_column;
10218                        if let Some(clipboard_selection) = clipboard_selections.get(ix) {
10219                            let end_offset = start_offset + clipboard_selection.len;
10220                            to_insert = &clipboard_text[start_offset..end_offset];
10221                            entire_line = clipboard_selection.is_entire_line;
10222                            start_offset = end_offset + 1;
10223                            original_indent_column = Some(clipboard_selection.first_line_indent);
10224                        } else {
10225                            to_insert = clipboard_text.as_str();
10226                            entire_line = all_selections_were_entire_line;
10227                            original_indent_column = first_selection_indent_column
10228                        }
10229
10230                        // If the corresponding selection was empty when this slice of the
10231                        // clipboard text was written, then the entire line containing the
10232                        // selection was copied. If this selection is also currently empty,
10233                        // then paste the line before the current line of the buffer.
10234                        let range = if selection.is_empty() && handle_entire_lines && entire_line {
10235                            let column = selection.start.to_point(&snapshot).column as usize;
10236                            let line_start = selection.start - column;
10237                            line_start..line_start
10238                        } else {
10239                            selection.range()
10240                        };
10241
10242                        edits.push((range, to_insert));
10243                        original_indent_columns.push(original_indent_column);
10244                    }
10245                    drop(snapshot);
10246
10247                    buffer.edit(
10248                        edits,
10249                        if auto_indent_on_paste {
10250                            Some(AutoindentMode::Block {
10251                                original_indent_columns,
10252                            })
10253                        } else {
10254                            None
10255                        },
10256                        cx,
10257                    );
10258                });
10259
10260                let selections = this.selections.all::<usize>(cx);
10261                this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10262                    s.select(selections)
10263                });
10264            } else {
10265                this.insert(&clipboard_text, window, cx);
10266            }
10267        });
10268    }
10269
10270    pub fn paste(&mut self, _: &Paste, window: &mut Window, cx: &mut Context<Self>) {
10271        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
10272        if let Some(item) = cx.read_from_clipboard() {
10273            let entries = item.entries();
10274
10275            match entries.first() {
10276                // For now, we only support applying metadata if there's one string. In the future, we can incorporate all the selections
10277                // of all the pasted entries.
10278                Some(ClipboardEntry::String(clipboard_string)) if entries.len() == 1 => self
10279                    .do_paste(
10280                        clipboard_string.text(),
10281                        clipboard_string.metadata_json::<Vec<ClipboardSelection>>(),
10282                        true,
10283                        window,
10284                        cx,
10285                    ),
10286                _ => self.do_paste(&item.text().unwrap_or_default(), None, true, window, cx),
10287            }
10288        }
10289    }
10290
10291    pub fn undo(&mut self, _: &Undo, window: &mut Window, cx: &mut Context<Self>) {
10292        if self.read_only(cx) {
10293            return;
10294        }
10295
10296        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
10297
10298        if let Some(transaction_id) = self.buffer.update(cx, |buffer, cx| buffer.undo(cx)) {
10299            if let Some((selections, _)) =
10300                self.selection_history.transaction(transaction_id).cloned()
10301            {
10302                self.change_selections(None, window, cx, |s| {
10303                    s.select_anchors(selections.to_vec());
10304                });
10305            } else {
10306                log::error!(
10307                    "No entry in selection_history found for undo. \
10308                     This may correspond to a bug where undo does not update the selection. \
10309                     If this is occurring, please add details to \
10310                     https://github.com/zed-industries/zed/issues/22692"
10311                );
10312            }
10313            self.request_autoscroll(Autoscroll::fit(), cx);
10314            self.unmark_text(window, cx);
10315            self.refresh_inline_completion(true, false, window, cx);
10316            cx.emit(EditorEvent::Edited { transaction_id });
10317            cx.emit(EditorEvent::TransactionUndone { transaction_id });
10318        }
10319    }
10320
10321    pub fn redo(&mut self, _: &Redo, window: &mut Window, cx: &mut Context<Self>) {
10322        if self.read_only(cx) {
10323            return;
10324        }
10325
10326        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
10327
10328        if let Some(transaction_id) = self.buffer.update(cx, |buffer, cx| buffer.redo(cx)) {
10329            if let Some((_, Some(selections))) =
10330                self.selection_history.transaction(transaction_id).cloned()
10331            {
10332                self.change_selections(None, window, cx, |s| {
10333                    s.select_anchors(selections.to_vec());
10334                });
10335            } else {
10336                log::error!(
10337                    "No entry in selection_history found for redo. \
10338                     This may correspond to a bug where undo does not update the selection. \
10339                     If this is occurring, please add details to \
10340                     https://github.com/zed-industries/zed/issues/22692"
10341                );
10342            }
10343            self.request_autoscroll(Autoscroll::fit(), cx);
10344            self.unmark_text(window, cx);
10345            self.refresh_inline_completion(true, false, window, cx);
10346            cx.emit(EditorEvent::Edited { transaction_id });
10347        }
10348    }
10349
10350    pub fn finalize_last_transaction(&mut self, cx: &mut Context<Self>) {
10351        self.buffer
10352            .update(cx, |buffer, cx| buffer.finalize_last_transaction(cx));
10353    }
10354
10355    pub fn group_until_transaction(&mut self, tx_id: TransactionId, cx: &mut Context<Self>) {
10356        self.buffer
10357            .update(cx, |buffer, cx| buffer.group_until_transaction(tx_id, cx));
10358    }
10359
10360    pub fn move_left(&mut self, _: &MoveLeft, window: &mut Window, cx: &mut Context<Self>) {
10361        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
10362        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10363            s.move_with(|map, selection| {
10364                let cursor = if selection.is_empty() {
10365                    movement::left(map, selection.start)
10366                } else {
10367                    selection.start
10368                };
10369                selection.collapse_to(cursor, SelectionGoal::None);
10370            });
10371        })
10372    }
10373
10374    pub fn select_left(&mut self, _: &SelectLeft, window: &mut Window, cx: &mut Context<Self>) {
10375        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
10376        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10377            s.move_heads_with(|map, head, _| (movement::left(map, head), SelectionGoal::None));
10378        })
10379    }
10380
10381    pub fn move_right(&mut self, _: &MoveRight, window: &mut Window, cx: &mut Context<Self>) {
10382        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
10383        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10384            s.move_with(|map, selection| {
10385                let cursor = if selection.is_empty() {
10386                    movement::right(map, selection.end)
10387                } else {
10388                    selection.end
10389                };
10390                selection.collapse_to(cursor, SelectionGoal::None)
10391            });
10392        })
10393    }
10394
10395    pub fn select_right(&mut self, _: &SelectRight, window: &mut Window, cx: &mut Context<Self>) {
10396        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
10397        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10398            s.move_heads_with(|map, head, _| (movement::right(map, head), SelectionGoal::None));
10399        })
10400    }
10401
10402    pub fn move_up(&mut self, _: &MoveUp, window: &mut Window, cx: &mut Context<Self>) {
10403        if self.take_rename(true, window, cx).is_some() {
10404            return;
10405        }
10406
10407        if matches!(self.mode, EditorMode::SingleLine { .. }) {
10408            cx.propagate();
10409            return;
10410        }
10411
10412        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
10413
10414        let text_layout_details = &self.text_layout_details(window);
10415        let selection_count = self.selections.count();
10416        let first_selection = self.selections.first_anchor();
10417
10418        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10419            s.move_with(|map, selection| {
10420                if !selection.is_empty() {
10421                    selection.goal = SelectionGoal::None;
10422                }
10423                let (cursor, goal) = movement::up(
10424                    map,
10425                    selection.start,
10426                    selection.goal,
10427                    false,
10428                    text_layout_details,
10429                );
10430                selection.collapse_to(cursor, goal);
10431            });
10432        });
10433
10434        if selection_count == 1 && first_selection.range() == self.selections.first_anchor().range()
10435        {
10436            cx.propagate();
10437        }
10438    }
10439
10440    pub fn move_up_by_lines(
10441        &mut self,
10442        action: &MoveUpByLines,
10443        window: &mut Window,
10444        cx: &mut Context<Self>,
10445    ) {
10446        if self.take_rename(true, window, cx).is_some() {
10447            return;
10448        }
10449
10450        if matches!(self.mode, EditorMode::SingleLine { .. }) {
10451            cx.propagate();
10452            return;
10453        }
10454
10455        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
10456
10457        let text_layout_details = &self.text_layout_details(window);
10458
10459        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10460            s.move_with(|map, selection| {
10461                if !selection.is_empty() {
10462                    selection.goal = SelectionGoal::None;
10463                }
10464                let (cursor, goal) = movement::up_by_rows(
10465                    map,
10466                    selection.start,
10467                    action.lines,
10468                    selection.goal,
10469                    false,
10470                    text_layout_details,
10471                );
10472                selection.collapse_to(cursor, goal);
10473            });
10474        })
10475    }
10476
10477    pub fn move_down_by_lines(
10478        &mut self,
10479        action: &MoveDownByLines,
10480        window: &mut Window,
10481        cx: &mut Context<Self>,
10482    ) {
10483        if self.take_rename(true, window, cx).is_some() {
10484            return;
10485        }
10486
10487        if matches!(self.mode, EditorMode::SingleLine { .. }) {
10488            cx.propagate();
10489            return;
10490        }
10491
10492        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
10493
10494        let text_layout_details = &self.text_layout_details(window);
10495
10496        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10497            s.move_with(|map, selection| {
10498                if !selection.is_empty() {
10499                    selection.goal = SelectionGoal::None;
10500                }
10501                let (cursor, goal) = movement::down_by_rows(
10502                    map,
10503                    selection.start,
10504                    action.lines,
10505                    selection.goal,
10506                    false,
10507                    text_layout_details,
10508                );
10509                selection.collapse_to(cursor, goal);
10510            });
10511        })
10512    }
10513
10514    pub fn select_down_by_lines(
10515        &mut self,
10516        action: &SelectDownByLines,
10517        window: &mut Window,
10518        cx: &mut Context<Self>,
10519    ) {
10520        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
10521        let text_layout_details = &self.text_layout_details(window);
10522        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10523            s.move_heads_with(|map, head, goal| {
10524                movement::down_by_rows(map, head, action.lines, goal, false, text_layout_details)
10525            })
10526        })
10527    }
10528
10529    pub fn select_up_by_lines(
10530        &mut self,
10531        action: &SelectUpByLines,
10532        window: &mut Window,
10533        cx: &mut Context<Self>,
10534    ) {
10535        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
10536        let text_layout_details = &self.text_layout_details(window);
10537        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10538            s.move_heads_with(|map, head, goal| {
10539                movement::up_by_rows(map, head, action.lines, goal, false, text_layout_details)
10540            })
10541        })
10542    }
10543
10544    pub fn select_page_up(
10545        &mut self,
10546        _: &SelectPageUp,
10547        window: &mut Window,
10548        cx: &mut Context<Self>,
10549    ) {
10550        let Some(row_count) = self.visible_row_count() else {
10551            return;
10552        };
10553
10554        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
10555
10556        let text_layout_details = &self.text_layout_details(window);
10557
10558        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10559            s.move_heads_with(|map, head, goal| {
10560                movement::up_by_rows(map, head, row_count, goal, false, text_layout_details)
10561            })
10562        })
10563    }
10564
10565    pub fn move_page_up(
10566        &mut self,
10567        action: &MovePageUp,
10568        window: &mut Window,
10569        cx: &mut Context<Self>,
10570    ) {
10571        if self.take_rename(true, window, cx).is_some() {
10572            return;
10573        }
10574
10575        if self
10576            .context_menu
10577            .borrow_mut()
10578            .as_mut()
10579            .map(|menu| menu.select_first(self.completion_provider.as_deref(), cx))
10580            .unwrap_or(false)
10581        {
10582            return;
10583        }
10584
10585        if matches!(self.mode, EditorMode::SingleLine { .. }) {
10586            cx.propagate();
10587            return;
10588        }
10589
10590        let Some(row_count) = self.visible_row_count() else {
10591            return;
10592        };
10593
10594        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
10595
10596        let autoscroll = if action.center_cursor {
10597            Autoscroll::center()
10598        } else {
10599            Autoscroll::fit()
10600        };
10601
10602        let text_layout_details = &self.text_layout_details(window);
10603
10604        self.change_selections(Some(autoscroll), window, cx, |s| {
10605            s.move_with(|map, selection| {
10606                if !selection.is_empty() {
10607                    selection.goal = SelectionGoal::None;
10608                }
10609                let (cursor, goal) = movement::up_by_rows(
10610                    map,
10611                    selection.end,
10612                    row_count,
10613                    selection.goal,
10614                    false,
10615                    text_layout_details,
10616                );
10617                selection.collapse_to(cursor, goal);
10618            });
10619        });
10620    }
10621
10622    pub fn select_up(&mut self, _: &SelectUp, window: &mut Window, cx: &mut Context<Self>) {
10623        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
10624        let text_layout_details = &self.text_layout_details(window);
10625        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10626            s.move_heads_with(|map, head, goal| {
10627                movement::up(map, head, goal, false, text_layout_details)
10628            })
10629        })
10630    }
10631
10632    pub fn move_down(&mut self, _: &MoveDown, window: &mut Window, cx: &mut Context<Self>) {
10633        self.take_rename(true, window, cx);
10634
10635        if matches!(self.mode, EditorMode::SingleLine { .. }) {
10636            cx.propagate();
10637            return;
10638        }
10639
10640        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
10641
10642        let text_layout_details = &self.text_layout_details(window);
10643        let selection_count = self.selections.count();
10644        let first_selection = self.selections.first_anchor();
10645
10646        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10647            s.move_with(|map, selection| {
10648                if !selection.is_empty() {
10649                    selection.goal = SelectionGoal::None;
10650                }
10651                let (cursor, goal) = movement::down(
10652                    map,
10653                    selection.end,
10654                    selection.goal,
10655                    false,
10656                    text_layout_details,
10657                );
10658                selection.collapse_to(cursor, goal);
10659            });
10660        });
10661
10662        if selection_count == 1 && first_selection.range() == self.selections.first_anchor().range()
10663        {
10664            cx.propagate();
10665        }
10666    }
10667
10668    pub fn select_page_down(
10669        &mut self,
10670        _: &SelectPageDown,
10671        window: &mut Window,
10672        cx: &mut Context<Self>,
10673    ) {
10674        let Some(row_count) = self.visible_row_count() else {
10675            return;
10676        };
10677
10678        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
10679
10680        let text_layout_details = &self.text_layout_details(window);
10681
10682        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10683            s.move_heads_with(|map, head, goal| {
10684                movement::down_by_rows(map, head, row_count, goal, false, text_layout_details)
10685            })
10686        })
10687    }
10688
10689    pub fn move_page_down(
10690        &mut self,
10691        action: &MovePageDown,
10692        window: &mut Window,
10693        cx: &mut Context<Self>,
10694    ) {
10695        if self.take_rename(true, window, cx).is_some() {
10696            return;
10697        }
10698
10699        if self
10700            .context_menu
10701            .borrow_mut()
10702            .as_mut()
10703            .map(|menu| menu.select_last(self.completion_provider.as_deref(), cx))
10704            .unwrap_or(false)
10705        {
10706            return;
10707        }
10708
10709        if matches!(self.mode, EditorMode::SingleLine { .. }) {
10710            cx.propagate();
10711            return;
10712        }
10713
10714        let Some(row_count) = self.visible_row_count() else {
10715            return;
10716        };
10717
10718        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
10719
10720        let autoscroll = if action.center_cursor {
10721            Autoscroll::center()
10722        } else {
10723            Autoscroll::fit()
10724        };
10725
10726        let text_layout_details = &self.text_layout_details(window);
10727        self.change_selections(Some(autoscroll), window, cx, |s| {
10728            s.move_with(|map, selection| {
10729                if !selection.is_empty() {
10730                    selection.goal = SelectionGoal::None;
10731                }
10732                let (cursor, goal) = movement::down_by_rows(
10733                    map,
10734                    selection.end,
10735                    row_count,
10736                    selection.goal,
10737                    false,
10738                    text_layout_details,
10739                );
10740                selection.collapse_to(cursor, goal);
10741            });
10742        });
10743    }
10744
10745    pub fn select_down(&mut self, _: &SelectDown, window: &mut Window, cx: &mut Context<Self>) {
10746        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
10747        let text_layout_details = &self.text_layout_details(window);
10748        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10749            s.move_heads_with(|map, head, goal| {
10750                movement::down(map, head, goal, false, text_layout_details)
10751            })
10752        });
10753    }
10754
10755    pub fn context_menu_first(
10756        &mut self,
10757        _: &ContextMenuFirst,
10758        _window: &mut Window,
10759        cx: &mut Context<Self>,
10760    ) {
10761        if let Some(context_menu) = self.context_menu.borrow_mut().as_mut() {
10762            context_menu.select_first(self.completion_provider.as_deref(), cx);
10763        }
10764    }
10765
10766    pub fn context_menu_prev(
10767        &mut self,
10768        _: &ContextMenuPrevious,
10769        _window: &mut Window,
10770        cx: &mut Context<Self>,
10771    ) {
10772        if let Some(context_menu) = self.context_menu.borrow_mut().as_mut() {
10773            context_menu.select_prev(self.completion_provider.as_deref(), cx);
10774        }
10775    }
10776
10777    pub fn context_menu_next(
10778        &mut self,
10779        _: &ContextMenuNext,
10780        _window: &mut Window,
10781        cx: &mut Context<Self>,
10782    ) {
10783        if let Some(context_menu) = self.context_menu.borrow_mut().as_mut() {
10784            context_menu.select_next(self.completion_provider.as_deref(), cx);
10785        }
10786    }
10787
10788    pub fn context_menu_last(
10789        &mut self,
10790        _: &ContextMenuLast,
10791        _window: &mut Window,
10792        cx: &mut Context<Self>,
10793    ) {
10794        if let Some(context_menu) = self.context_menu.borrow_mut().as_mut() {
10795            context_menu.select_last(self.completion_provider.as_deref(), cx);
10796        }
10797    }
10798
10799    pub fn move_to_previous_word_start(
10800        &mut self,
10801        _: &MoveToPreviousWordStart,
10802        window: &mut Window,
10803        cx: &mut Context<Self>,
10804    ) {
10805        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
10806        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10807            s.move_cursors_with(|map, head, _| {
10808                (
10809                    movement::previous_word_start(map, head),
10810                    SelectionGoal::None,
10811                )
10812            });
10813        })
10814    }
10815
10816    pub fn move_to_previous_subword_start(
10817        &mut self,
10818        _: &MoveToPreviousSubwordStart,
10819        window: &mut Window,
10820        cx: &mut Context<Self>,
10821    ) {
10822        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
10823        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10824            s.move_cursors_with(|map, head, _| {
10825                (
10826                    movement::previous_subword_start(map, head),
10827                    SelectionGoal::None,
10828                )
10829            });
10830        })
10831    }
10832
10833    pub fn select_to_previous_word_start(
10834        &mut self,
10835        _: &SelectToPreviousWordStart,
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_heads_with(|map, head, _| {
10842                (
10843                    movement::previous_word_start(map, head),
10844                    SelectionGoal::None,
10845                )
10846            });
10847        })
10848    }
10849
10850    pub fn select_to_previous_subword_start(
10851        &mut self,
10852        _: &SelectToPreviousSubwordStart,
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_heads_with(|map, head, _| {
10859                (
10860                    movement::previous_subword_start(map, head),
10861                    SelectionGoal::None,
10862                )
10863            });
10864        })
10865    }
10866
10867    pub fn delete_to_previous_word_start(
10868        &mut self,
10869        action: &DeleteToPreviousWordStart,
10870        window: &mut Window,
10871        cx: &mut Context<Self>,
10872    ) {
10873        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
10874        self.transact(window, cx, |this, window, cx| {
10875            this.select_autoclose_pair(window, cx);
10876            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10877                s.move_with(|map, selection| {
10878                    if selection.is_empty() {
10879                        let cursor = if action.ignore_newlines {
10880                            movement::previous_word_start(map, selection.head())
10881                        } else {
10882                            movement::previous_word_start_or_newline(map, selection.head())
10883                        };
10884                        selection.set_head(cursor, SelectionGoal::None);
10885                    }
10886                });
10887            });
10888            this.insert("", window, cx);
10889        });
10890    }
10891
10892    pub fn delete_to_previous_subword_start(
10893        &mut self,
10894        _: &DeleteToPreviousSubwordStart,
10895        window: &mut Window,
10896        cx: &mut Context<Self>,
10897    ) {
10898        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
10899        self.transact(window, cx, |this, window, cx| {
10900            this.select_autoclose_pair(window, cx);
10901            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10902                s.move_with(|map, selection| {
10903                    if selection.is_empty() {
10904                        let cursor = movement::previous_subword_start(map, selection.head());
10905                        selection.set_head(cursor, SelectionGoal::None);
10906                    }
10907                });
10908            });
10909            this.insert("", window, cx);
10910        });
10911    }
10912
10913    pub fn move_to_next_word_end(
10914        &mut self,
10915        _: &MoveToNextWordEnd,
10916        window: &mut Window,
10917        cx: &mut Context<Self>,
10918    ) {
10919        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
10920        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10921            s.move_cursors_with(|map, head, _| {
10922                (movement::next_word_end(map, head), SelectionGoal::None)
10923            });
10924        })
10925    }
10926
10927    pub fn move_to_next_subword_end(
10928        &mut self,
10929        _: &MoveToNextSubwordEnd,
10930        window: &mut Window,
10931        cx: &mut Context<Self>,
10932    ) {
10933        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
10934        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10935            s.move_cursors_with(|map, head, _| {
10936                (movement::next_subword_end(map, head), SelectionGoal::None)
10937            });
10938        })
10939    }
10940
10941    pub fn select_to_next_word_end(
10942        &mut self,
10943        _: &SelectToNextWordEnd,
10944        window: &mut Window,
10945        cx: &mut Context<Self>,
10946    ) {
10947        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
10948        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10949            s.move_heads_with(|map, head, _| {
10950                (movement::next_word_end(map, head), SelectionGoal::None)
10951            });
10952        })
10953    }
10954
10955    pub fn select_to_next_subword_end(
10956        &mut self,
10957        _: &SelectToNextSubwordEnd,
10958        window: &mut Window,
10959        cx: &mut Context<Self>,
10960    ) {
10961        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
10962        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10963            s.move_heads_with(|map, head, _| {
10964                (movement::next_subword_end(map, head), SelectionGoal::None)
10965            });
10966        })
10967    }
10968
10969    pub fn delete_to_next_word_end(
10970        &mut self,
10971        action: &DeleteToNextWordEnd,
10972        window: &mut Window,
10973        cx: &mut Context<Self>,
10974    ) {
10975        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
10976        self.transact(window, cx, |this, window, cx| {
10977            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10978                s.move_with(|map, selection| {
10979                    if selection.is_empty() {
10980                        let cursor = if action.ignore_newlines {
10981                            movement::next_word_end(map, selection.head())
10982                        } else {
10983                            movement::next_word_end_or_newline(map, selection.head())
10984                        };
10985                        selection.set_head(cursor, SelectionGoal::None);
10986                    }
10987                });
10988            });
10989            this.insert("", window, cx);
10990        });
10991    }
10992
10993    pub fn delete_to_next_subword_end(
10994        &mut self,
10995        _: &DeleteToNextSubwordEnd,
10996        window: &mut Window,
10997        cx: &mut Context<Self>,
10998    ) {
10999        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
11000        self.transact(window, cx, |this, window, cx| {
11001            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11002                s.move_with(|map, selection| {
11003                    if selection.is_empty() {
11004                        let cursor = movement::next_subword_end(map, selection.head());
11005                        selection.set_head(cursor, SelectionGoal::None);
11006                    }
11007                });
11008            });
11009            this.insert("", window, cx);
11010        });
11011    }
11012
11013    pub fn move_to_beginning_of_line(
11014        &mut self,
11015        action: &MoveToBeginningOfLine,
11016        window: &mut Window,
11017        cx: &mut Context<Self>,
11018    ) {
11019        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11020        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11021            s.move_cursors_with(|map, head, _| {
11022                (
11023                    movement::indented_line_beginning(
11024                        map,
11025                        head,
11026                        action.stop_at_soft_wraps,
11027                        action.stop_at_indent,
11028                    ),
11029                    SelectionGoal::None,
11030                )
11031            });
11032        })
11033    }
11034
11035    pub fn select_to_beginning_of_line(
11036        &mut self,
11037        action: &SelectToBeginningOfLine,
11038        window: &mut Window,
11039        cx: &mut Context<Self>,
11040    ) {
11041        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11042        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11043            s.move_heads_with(|map, head, _| {
11044                (
11045                    movement::indented_line_beginning(
11046                        map,
11047                        head,
11048                        action.stop_at_soft_wraps,
11049                        action.stop_at_indent,
11050                    ),
11051                    SelectionGoal::None,
11052                )
11053            });
11054        });
11055    }
11056
11057    pub fn delete_to_beginning_of_line(
11058        &mut self,
11059        action: &DeleteToBeginningOfLine,
11060        window: &mut Window,
11061        cx: &mut Context<Self>,
11062    ) {
11063        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
11064        self.transact(window, cx, |this, window, cx| {
11065            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11066                s.move_with(|_, selection| {
11067                    selection.reversed = true;
11068                });
11069            });
11070
11071            this.select_to_beginning_of_line(
11072                &SelectToBeginningOfLine {
11073                    stop_at_soft_wraps: false,
11074                    stop_at_indent: action.stop_at_indent,
11075                },
11076                window,
11077                cx,
11078            );
11079            this.backspace(&Backspace, window, cx);
11080        });
11081    }
11082
11083    pub fn move_to_end_of_line(
11084        &mut self,
11085        action: &MoveToEndOfLine,
11086        window: &mut Window,
11087        cx: &mut Context<Self>,
11088    ) {
11089        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11090        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11091            s.move_cursors_with(|map, head, _| {
11092                (
11093                    movement::line_end(map, head, action.stop_at_soft_wraps),
11094                    SelectionGoal::None,
11095                )
11096            });
11097        })
11098    }
11099
11100    pub fn select_to_end_of_line(
11101        &mut self,
11102        action: &SelectToEndOfLine,
11103        window: &mut Window,
11104        cx: &mut Context<Self>,
11105    ) {
11106        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11107        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11108            s.move_heads_with(|map, head, _| {
11109                (
11110                    movement::line_end(map, head, action.stop_at_soft_wraps),
11111                    SelectionGoal::None,
11112                )
11113            });
11114        })
11115    }
11116
11117    pub fn delete_to_end_of_line(
11118        &mut self,
11119        _: &DeleteToEndOfLine,
11120        window: &mut Window,
11121        cx: &mut Context<Self>,
11122    ) {
11123        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
11124        self.transact(window, cx, |this, window, cx| {
11125            this.select_to_end_of_line(
11126                &SelectToEndOfLine {
11127                    stop_at_soft_wraps: false,
11128                },
11129                window,
11130                cx,
11131            );
11132            this.delete(&Delete, window, cx);
11133        });
11134    }
11135
11136    pub fn cut_to_end_of_line(
11137        &mut self,
11138        _: &CutToEndOfLine,
11139        window: &mut Window,
11140        cx: &mut Context<Self>,
11141    ) {
11142        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
11143        self.transact(window, cx, |this, window, cx| {
11144            this.select_to_end_of_line(
11145                &SelectToEndOfLine {
11146                    stop_at_soft_wraps: false,
11147                },
11148                window,
11149                cx,
11150            );
11151            this.cut(&Cut, window, cx);
11152        });
11153    }
11154
11155    pub fn move_to_start_of_paragraph(
11156        &mut self,
11157        _: &MoveToStartOfParagraph,
11158        window: &mut Window,
11159        cx: &mut Context<Self>,
11160    ) {
11161        if matches!(self.mode, EditorMode::SingleLine { .. }) {
11162            cx.propagate();
11163            return;
11164        }
11165        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11166        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11167            s.move_with(|map, selection| {
11168                selection.collapse_to(
11169                    movement::start_of_paragraph(map, selection.head(), 1),
11170                    SelectionGoal::None,
11171                )
11172            });
11173        })
11174    }
11175
11176    pub fn move_to_end_of_paragraph(
11177        &mut self,
11178        _: &MoveToEndOfParagraph,
11179        window: &mut Window,
11180        cx: &mut Context<Self>,
11181    ) {
11182        if matches!(self.mode, EditorMode::SingleLine { .. }) {
11183            cx.propagate();
11184            return;
11185        }
11186        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11187        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11188            s.move_with(|map, selection| {
11189                selection.collapse_to(
11190                    movement::end_of_paragraph(map, selection.head(), 1),
11191                    SelectionGoal::None,
11192                )
11193            });
11194        })
11195    }
11196
11197    pub fn select_to_start_of_paragraph(
11198        &mut self,
11199        _: &SelectToStartOfParagraph,
11200        window: &mut Window,
11201        cx: &mut Context<Self>,
11202    ) {
11203        if matches!(self.mode, EditorMode::SingleLine { .. }) {
11204            cx.propagate();
11205            return;
11206        }
11207        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11208        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11209            s.move_heads_with(|map, head, _| {
11210                (
11211                    movement::start_of_paragraph(map, head, 1),
11212                    SelectionGoal::None,
11213                )
11214            });
11215        })
11216    }
11217
11218    pub fn select_to_end_of_paragraph(
11219        &mut self,
11220        _: &SelectToEndOfParagraph,
11221        window: &mut Window,
11222        cx: &mut Context<Self>,
11223    ) {
11224        if matches!(self.mode, EditorMode::SingleLine { .. }) {
11225            cx.propagate();
11226            return;
11227        }
11228        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11229        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11230            s.move_heads_with(|map, head, _| {
11231                (
11232                    movement::end_of_paragraph(map, head, 1),
11233                    SelectionGoal::None,
11234                )
11235            });
11236        })
11237    }
11238
11239    pub fn move_to_start_of_excerpt(
11240        &mut self,
11241        _: &MoveToStartOfExcerpt,
11242        window: &mut Window,
11243        cx: &mut Context<Self>,
11244    ) {
11245        if matches!(self.mode, EditorMode::SingleLine { .. }) {
11246            cx.propagate();
11247            return;
11248        }
11249        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11250        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11251            s.move_with(|map, selection| {
11252                selection.collapse_to(
11253                    movement::start_of_excerpt(
11254                        map,
11255                        selection.head(),
11256                        workspace::searchable::Direction::Prev,
11257                    ),
11258                    SelectionGoal::None,
11259                )
11260            });
11261        })
11262    }
11263
11264    pub fn move_to_start_of_next_excerpt(
11265        &mut self,
11266        _: &MoveToStartOfNextExcerpt,
11267        window: &mut Window,
11268        cx: &mut Context<Self>,
11269    ) {
11270        if matches!(self.mode, EditorMode::SingleLine { .. }) {
11271            cx.propagate();
11272            return;
11273        }
11274
11275        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11276            s.move_with(|map, selection| {
11277                selection.collapse_to(
11278                    movement::start_of_excerpt(
11279                        map,
11280                        selection.head(),
11281                        workspace::searchable::Direction::Next,
11282                    ),
11283                    SelectionGoal::None,
11284                )
11285            });
11286        })
11287    }
11288
11289    pub fn move_to_end_of_excerpt(
11290        &mut self,
11291        _: &MoveToEndOfExcerpt,
11292        window: &mut Window,
11293        cx: &mut Context<Self>,
11294    ) {
11295        if matches!(self.mode, EditorMode::SingleLine { .. }) {
11296            cx.propagate();
11297            return;
11298        }
11299        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11300        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11301            s.move_with(|map, selection| {
11302                selection.collapse_to(
11303                    movement::end_of_excerpt(
11304                        map,
11305                        selection.head(),
11306                        workspace::searchable::Direction::Next,
11307                    ),
11308                    SelectionGoal::None,
11309                )
11310            });
11311        })
11312    }
11313
11314    pub fn move_to_end_of_previous_excerpt(
11315        &mut self,
11316        _: &MoveToEndOfPreviousExcerpt,
11317        window: &mut Window,
11318        cx: &mut Context<Self>,
11319    ) {
11320        if matches!(self.mode, EditorMode::SingleLine { .. }) {
11321            cx.propagate();
11322            return;
11323        }
11324        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11325        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11326            s.move_with(|map, selection| {
11327                selection.collapse_to(
11328                    movement::end_of_excerpt(
11329                        map,
11330                        selection.head(),
11331                        workspace::searchable::Direction::Prev,
11332                    ),
11333                    SelectionGoal::None,
11334                )
11335            });
11336        })
11337    }
11338
11339    pub fn select_to_start_of_excerpt(
11340        &mut self,
11341        _: &SelectToStartOfExcerpt,
11342        window: &mut Window,
11343        cx: &mut Context<Self>,
11344    ) {
11345        if matches!(self.mode, EditorMode::SingleLine { .. }) {
11346            cx.propagate();
11347            return;
11348        }
11349        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11350        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11351            s.move_heads_with(|map, head, _| {
11352                (
11353                    movement::start_of_excerpt(map, head, workspace::searchable::Direction::Prev),
11354                    SelectionGoal::None,
11355                )
11356            });
11357        })
11358    }
11359
11360    pub fn select_to_start_of_next_excerpt(
11361        &mut self,
11362        _: &SelectToStartOfNextExcerpt,
11363        window: &mut Window,
11364        cx: &mut Context<Self>,
11365    ) {
11366        if matches!(self.mode, EditorMode::SingleLine { .. }) {
11367            cx.propagate();
11368            return;
11369        }
11370        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11371        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11372            s.move_heads_with(|map, head, _| {
11373                (
11374                    movement::start_of_excerpt(map, head, workspace::searchable::Direction::Next),
11375                    SelectionGoal::None,
11376                )
11377            });
11378        })
11379    }
11380
11381    pub fn select_to_end_of_excerpt(
11382        &mut self,
11383        _: &SelectToEndOfExcerpt,
11384        window: &mut Window,
11385        cx: &mut Context<Self>,
11386    ) {
11387        if matches!(self.mode, EditorMode::SingleLine { .. }) {
11388            cx.propagate();
11389            return;
11390        }
11391        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11392        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11393            s.move_heads_with(|map, head, _| {
11394                (
11395                    movement::end_of_excerpt(map, head, workspace::searchable::Direction::Next),
11396                    SelectionGoal::None,
11397                )
11398            });
11399        })
11400    }
11401
11402    pub fn select_to_end_of_previous_excerpt(
11403        &mut self,
11404        _: &SelectToEndOfPreviousExcerpt,
11405        window: &mut Window,
11406        cx: &mut Context<Self>,
11407    ) {
11408        if matches!(self.mode, EditorMode::SingleLine { .. }) {
11409            cx.propagate();
11410            return;
11411        }
11412        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11413        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11414            s.move_heads_with(|map, head, _| {
11415                (
11416                    movement::end_of_excerpt(map, head, workspace::searchable::Direction::Prev),
11417                    SelectionGoal::None,
11418                )
11419            });
11420        })
11421    }
11422
11423    pub fn move_to_beginning(
11424        &mut self,
11425        _: &MoveToBeginning,
11426        window: &mut Window,
11427        cx: &mut Context<Self>,
11428    ) {
11429        if matches!(self.mode, EditorMode::SingleLine { .. }) {
11430            cx.propagate();
11431            return;
11432        }
11433        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11434        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11435            s.select_ranges(vec![0..0]);
11436        });
11437    }
11438
11439    pub fn select_to_beginning(
11440        &mut self,
11441        _: &SelectToBeginning,
11442        window: &mut Window,
11443        cx: &mut Context<Self>,
11444    ) {
11445        let mut selection = self.selections.last::<Point>(cx);
11446        selection.set_head(Point::zero(), SelectionGoal::None);
11447        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11448        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11449            s.select(vec![selection]);
11450        });
11451    }
11452
11453    pub fn move_to_end(&mut self, _: &MoveToEnd, window: &mut Window, cx: &mut Context<Self>) {
11454        if matches!(self.mode, EditorMode::SingleLine { .. }) {
11455            cx.propagate();
11456            return;
11457        }
11458        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11459        let cursor = self.buffer.read(cx).read(cx).len();
11460        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11461            s.select_ranges(vec![cursor..cursor])
11462        });
11463    }
11464
11465    pub fn set_nav_history(&mut self, nav_history: Option<ItemNavHistory>) {
11466        self.nav_history = nav_history;
11467    }
11468
11469    pub fn nav_history(&self) -> Option<&ItemNavHistory> {
11470        self.nav_history.as_ref()
11471    }
11472
11473    pub fn create_nav_history_entry(&mut self, cx: &mut Context<Self>) {
11474        self.push_to_nav_history(self.selections.newest_anchor().head(), None, false, cx);
11475    }
11476
11477    fn push_to_nav_history(
11478        &mut self,
11479        cursor_anchor: Anchor,
11480        new_position: Option<Point>,
11481        is_deactivate: bool,
11482        cx: &mut Context<Self>,
11483    ) {
11484        if let Some(nav_history) = self.nav_history.as_mut() {
11485            let buffer = self.buffer.read(cx).read(cx);
11486            let cursor_position = cursor_anchor.to_point(&buffer);
11487            let scroll_state = self.scroll_manager.anchor();
11488            let scroll_top_row = scroll_state.top_row(&buffer);
11489            drop(buffer);
11490
11491            if let Some(new_position) = new_position {
11492                let row_delta = (new_position.row as i64 - cursor_position.row as i64).abs();
11493                if row_delta < MIN_NAVIGATION_HISTORY_ROW_DELTA {
11494                    return;
11495                }
11496            }
11497
11498            nav_history.push(
11499                Some(NavigationData {
11500                    cursor_anchor,
11501                    cursor_position,
11502                    scroll_anchor: scroll_state,
11503                    scroll_top_row,
11504                }),
11505                cx,
11506            );
11507            cx.emit(EditorEvent::PushedToNavHistory {
11508                anchor: cursor_anchor,
11509                is_deactivate,
11510            })
11511        }
11512    }
11513
11514    pub fn select_to_end(&mut self, _: &SelectToEnd, window: &mut Window, cx: &mut Context<Self>) {
11515        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11516        let buffer = self.buffer.read(cx).snapshot(cx);
11517        let mut selection = self.selections.first::<usize>(cx);
11518        selection.set_head(buffer.len(), SelectionGoal::None);
11519        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11520            s.select(vec![selection]);
11521        });
11522    }
11523
11524    pub fn select_all(&mut self, _: &SelectAll, window: &mut Window, cx: &mut Context<Self>) {
11525        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11526        let end = self.buffer.read(cx).read(cx).len();
11527        self.change_selections(None, window, cx, |s| {
11528            s.select_ranges(vec![0..end]);
11529        });
11530    }
11531
11532    pub fn select_line(&mut self, _: &SelectLine, window: &mut Window, cx: &mut Context<Self>) {
11533        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11534        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
11535        let mut selections = self.selections.all::<Point>(cx);
11536        let max_point = display_map.buffer_snapshot.max_point();
11537        for selection in &mut selections {
11538            let rows = selection.spanned_rows(true, &display_map);
11539            selection.start = Point::new(rows.start.0, 0);
11540            selection.end = cmp::min(max_point, Point::new(rows.end.0, 0));
11541            selection.reversed = false;
11542        }
11543        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11544            s.select(selections);
11545        });
11546    }
11547
11548    pub fn split_selection_into_lines(
11549        &mut self,
11550        _: &SplitSelectionIntoLines,
11551        window: &mut Window,
11552        cx: &mut Context<Self>,
11553    ) {
11554        let selections = self
11555            .selections
11556            .all::<Point>(cx)
11557            .into_iter()
11558            .map(|selection| selection.start..selection.end)
11559            .collect::<Vec<_>>();
11560        self.unfold_ranges(&selections, true, true, cx);
11561
11562        let mut new_selection_ranges = Vec::new();
11563        {
11564            let buffer = self.buffer.read(cx).read(cx);
11565            for selection in selections {
11566                for row in selection.start.row..selection.end.row {
11567                    let cursor = Point::new(row, buffer.line_len(MultiBufferRow(row)));
11568                    new_selection_ranges.push(cursor..cursor);
11569                }
11570
11571                let is_multiline_selection = selection.start.row != selection.end.row;
11572                // Don't insert last one if it's a multi-line selection ending at the start of a line,
11573                // so this action feels more ergonomic when paired with other selection operations
11574                let should_skip_last = is_multiline_selection && selection.end.column == 0;
11575                if !should_skip_last {
11576                    new_selection_ranges.push(selection.end..selection.end);
11577                }
11578            }
11579        }
11580        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11581            s.select_ranges(new_selection_ranges);
11582        });
11583    }
11584
11585    pub fn add_selection_above(
11586        &mut self,
11587        _: &AddSelectionAbove,
11588        window: &mut Window,
11589        cx: &mut Context<Self>,
11590    ) {
11591        self.add_selection(true, window, cx);
11592    }
11593
11594    pub fn add_selection_below(
11595        &mut self,
11596        _: &AddSelectionBelow,
11597        window: &mut Window,
11598        cx: &mut Context<Self>,
11599    ) {
11600        self.add_selection(false, window, cx);
11601    }
11602
11603    fn add_selection(&mut self, above: bool, window: &mut Window, cx: &mut Context<Self>) {
11604        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11605
11606        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
11607        let mut selections = self.selections.all::<Point>(cx);
11608        let text_layout_details = self.text_layout_details(window);
11609        let mut state = self.add_selections_state.take().unwrap_or_else(|| {
11610            let oldest_selection = selections.iter().min_by_key(|s| s.id).unwrap().clone();
11611            let range = oldest_selection.display_range(&display_map).sorted();
11612
11613            let start_x = display_map.x_for_display_point(range.start, &text_layout_details);
11614            let end_x = display_map.x_for_display_point(range.end, &text_layout_details);
11615            let positions = start_x.min(end_x)..start_x.max(end_x);
11616
11617            selections.clear();
11618            let mut stack = Vec::new();
11619            for row in range.start.row().0..=range.end.row().0 {
11620                if let Some(selection) = self.selections.build_columnar_selection(
11621                    &display_map,
11622                    DisplayRow(row),
11623                    &positions,
11624                    oldest_selection.reversed,
11625                    &text_layout_details,
11626                ) {
11627                    stack.push(selection.id);
11628                    selections.push(selection);
11629                }
11630            }
11631
11632            if above {
11633                stack.reverse();
11634            }
11635
11636            AddSelectionsState { above, stack }
11637        });
11638
11639        let last_added_selection = *state.stack.last().unwrap();
11640        let mut new_selections = Vec::new();
11641        if above == state.above {
11642            let end_row = if above {
11643                DisplayRow(0)
11644            } else {
11645                display_map.max_point().row()
11646            };
11647
11648            'outer: for selection in selections {
11649                if selection.id == last_added_selection {
11650                    let range = selection.display_range(&display_map).sorted();
11651                    debug_assert_eq!(range.start.row(), range.end.row());
11652                    let mut row = range.start.row();
11653                    let positions =
11654                        if let SelectionGoal::HorizontalRange { start, end } = selection.goal {
11655                            px(start)..px(end)
11656                        } else {
11657                            let start_x =
11658                                display_map.x_for_display_point(range.start, &text_layout_details);
11659                            let end_x =
11660                                display_map.x_for_display_point(range.end, &text_layout_details);
11661                            start_x.min(end_x)..start_x.max(end_x)
11662                        };
11663
11664                    while row != end_row {
11665                        if above {
11666                            row.0 -= 1;
11667                        } else {
11668                            row.0 += 1;
11669                        }
11670
11671                        if let Some(new_selection) = self.selections.build_columnar_selection(
11672                            &display_map,
11673                            row,
11674                            &positions,
11675                            selection.reversed,
11676                            &text_layout_details,
11677                        ) {
11678                            state.stack.push(new_selection.id);
11679                            if above {
11680                                new_selections.push(new_selection);
11681                                new_selections.push(selection);
11682                            } else {
11683                                new_selections.push(selection);
11684                                new_selections.push(new_selection);
11685                            }
11686
11687                            continue 'outer;
11688                        }
11689                    }
11690                }
11691
11692                new_selections.push(selection);
11693            }
11694        } else {
11695            new_selections = selections;
11696            new_selections.retain(|s| s.id != last_added_selection);
11697            state.stack.pop();
11698        }
11699
11700        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11701            s.select(new_selections);
11702        });
11703        if state.stack.len() > 1 {
11704            self.add_selections_state = Some(state);
11705        }
11706    }
11707
11708    pub fn select_next_match_internal(
11709        &mut self,
11710        display_map: &DisplaySnapshot,
11711        replace_newest: bool,
11712        autoscroll: Option<Autoscroll>,
11713        window: &mut Window,
11714        cx: &mut Context<Self>,
11715    ) -> Result<()> {
11716        fn select_next_match_ranges(
11717            this: &mut Editor,
11718            range: Range<usize>,
11719            replace_newest: bool,
11720            auto_scroll: Option<Autoscroll>,
11721            window: &mut Window,
11722            cx: &mut Context<Editor>,
11723        ) {
11724            this.unfold_ranges(&[range.clone()], false, auto_scroll.is_some(), cx);
11725            this.change_selections(auto_scroll, window, cx, |s| {
11726                if replace_newest {
11727                    s.delete(s.newest_anchor().id);
11728                }
11729                s.insert_range(range.clone());
11730            });
11731        }
11732
11733        let buffer = &display_map.buffer_snapshot;
11734        let mut selections = self.selections.all::<usize>(cx);
11735        if let Some(mut select_next_state) = self.select_next_state.take() {
11736            let query = &select_next_state.query;
11737            if !select_next_state.done {
11738                let first_selection = selections.iter().min_by_key(|s| s.id).unwrap();
11739                let last_selection = selections.iter().max_by_key(|s| s.id).unwrap();
11740                let mut next_selected_range = None;
11741
11742                let bytes_after_last_selection =
11743                    buffer.bytes_in_range(last_selection.end..buffer.len());
11744                let bytes_before_first_selection = buffer.bytes_in_range(0..first_selection.start);
11745                let query_matches = query
11746                    .stream_find_iter(bytes_after_last_selection)
11747                    .map(|result| (last_selection.end, result))
11748                    .chain(
11749                        query
11750                            .stream_find_iter(bytes_before_first_selection)
11751                            .map(|result| (0, result)),
11752                    );
11753
11754                for (start_offset, query_match) in query_matches {
11755                    let query_match = query_match.unwrap(); // can only fail due to I/O
11756                    let offset_range =
11757                        start_offset + query_match.start()..start_offset + query_match.end();
11758                    let display_range = offset_range.start.to_display_point(display_map)
11759                        ..offset_range.end.to_display_point(display_map);
11760
11761                    if !select_next_state.wordwise
11762                        || (!movement::is_inside_word(display_map, display_range.start)
11763                            && !movement::is_inside_word(display_map, display_range.end))
11764                    {
11765                        // TODO: This is n^2, because we might check all the selections
11766                        if !selections
11767                            .iter()
11768                            .any(|selection| selection.range().overlaps(&offset_range))
11769                        {
11770                            next_selected_range = Some(offset_range);
11771                            break;
11772                        }
11773                    }
11774                }
11775
11776                if let Some(next_selected_range) = next_selected_range {
11777                    select_next_match_ranges(
11778                        self,
11779                        next_selected_range,
11780                        replace_newest,
11781                        autoscroll,
11782                        window,
11783                        cx,
11784                    );
11785                } else {
11786                    select_next_state.done = true;
11787                }
11788            }
11789
11790            self.select_next_state = Some(select_next_state);
11791        } else {
11792            let mut only_carets = true;
11793            let mut same_text_selected = true;
11794            let mut selected_text = None;
11795
11796            let mut selections_iter = selections.iter().peekable();
11797            while let Some(selection) = selections_iter.next() {
11798                if selection.start != selection.end {
11799                    only_carets = false;
11800                }
11801
11802                if same_text_selected {
11803                    if selected_text.is_none() {
11804                        selected_text =
11805                            Some(buffer.text_for_range(selection.range()).collect::<String>());
11806                    }
11807
11808                    if let Some(next_selection) = selections_iter.peek() {
11809                        if next_selection.range().len() == selection.range().len() {
11810                            let next_selected_text = buffer
11811                                .text_for_range(next_selection.range())
11812                                .collect::<String>();
11813                            if Some(next_selected_text) != selected_text {
11814                                same_text_selected = false;
11815                                selected_text = None;
11816                            }
11817                        } else {
11818                            same_text_selected = false;
11819                            selected_text = None;
11820                        }
11821                    }
11822                }
11823            }
11824
11825            if only_carets {
11826                for selection in &mut selections {
11827                    let word_range = movement::surrounding_word(
11828                        display_map,
11829                        selection.start.to_display_point(display_map),
11830                    );
11831                    selection.start = word_range.start.to_offset(display_map, Bias::Left);
11832                    selection.end = word_range.end.to_offset(display_map, Bias::Left);
11833                    selection.goal = SelectionGoal::None;
11834                    selection.reversed = false;
11835                    select_next_match_ranges(
11836                        self,
11837                        selection.start..selection.end,
11838                        replace_newest,
11839                        autoscroll,
11840                        window,
11841                        cx,
11842                    );
11843                }
11844
11845                if selections.len() == 1 {
11846                    let selection = selections
11847                        .last()
11848                        .expect("ensured that there's only one selection");
11849                    let query = buffer
11850                        .text_for_range(selection.start..selection.end)
11851                        .collect::<String>();
11852                    let is_empty = query.is_empty();
11853                    let select_state = SelectNextState {
11854                        query: AhoCorasick::new(&[query])?,
11855                        wordwise: true,
11856                        done: is_empty,
11857                    };
11858                    self.select_next_state = Some(select_state);
11859                } else {
11860                    self.select_next_state = None;
11861                }
11862            } else if let Some(selected_text) = selected_text {
11863                self.select_next_state = Some(SelectNextState {
11864                    query: AhoCorasick::new(&[selected_text])?,
11865                    wordwise: false,
11866                    done: false,
11867                });
11868                self.select_next_match_internal(
11869                    display_map,
11870                    replace_newest,
11871                    autoscroll,
11872                    window,
11873                    cx,
11874                )?;
11875            }
11876        }
11877        Ok(())
11878    }
11879
11880    pub fn select_all_matches(
11881        &mut self,
11882        _action: &SelectAllMatches,
11883        window: &mut Window,
11884        cx: &mut Context<Self>,
11885    ) -> Result<()> {
11886        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11887
11888        self.push_to_selection_history();
11889        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
11890
11891        self.select_next_match_internal(&display_map, false, None, window, cx)?;
11892        let Some(select_next_state) = self.select_next_state.as_mut() else {
11893            return Ok(());
11894        };
11895        if select_next_state.done {
11896            return Ok(());
11897        }
11898
11899        let mut new_selections = Vec::new();
11900
11901        let reversed = self.selections.oldest::<usize>(cx).reversed;
11902        let buffer = &display_map.buffer_snapshot;
11903        let query_matches = select_next_state
11904            .query
11905            .stream_find_iter(buffer.bytes_in_range(0..buffer.len()));
11906
11907        for query_match in query_matches.into_iter() {
11908            let query_match = query_match.context("query match for select all action")?; // can only fail due to I/O
11909            let offset_range = if reversed {
11910                query_match.end()..query_match.start()
11911            } else {
11912                query_match.start()..query_match.end()
11913            };
11914            let display_range = offset_range.start.to_display_point(&display_map)
11915                ..offset_range.end.to_display_point(&display_map);
11916
11917            if !select_next_state.wordwise
11918                || (!movement::is_inside_word(&display_map, display_range.start)
11919                    && !movement::is_inside_word(&display_map, display_range.end))
11920            {
11921                new_selections.push(offset_range.start..offset_range.end);
11922            }
11923        }
11924
11925        select_next_state.done = true;
11926        self.unfold_ranges(&new_selections.clone(), false, false, cx);
11927        self.change_selections(None, window, cx, |selections| {
11928            selections.select_ranges(new_selections)
11929        });
11930
11931        Ok(())
11932    }
11933
11934    pub fn select_next(
11935        &mut self,
11936        action: &SelectNext,
11937        window: &mut Window,
11938        cx: &mut Context<Self>,
11939    ) -> Result<()> {
11940        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11941        self.push_to_selection_history();
11942        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
11943        self.select_next_match_internal(
11944            &display_map,
11945            action.replace_newest,
11946            Some(Autoscroll::newest()),
11947            window,
11948            cx,
11949        )?;
11950        Ok(())
11951    }
11952
11953    pub fn select_previous(
11954        &mut self,
11955        action: &SelectPrevious,
11956        window: &mut Window,
11957        cx: &mut Context<Self>,
11958    ) -> Result<()> {
11959        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11960        self.push_to_selection_history();
11961        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
11962        let buffer = &display_map.buffer_snapshot;
11963        let mut selections = self.selections.all::<usize>(cx);
11964        if let Some(mut select_prev_state) = self.select_prev_state.take() {
11965            let query = &select_prev_state.query;
11966            if !select_prev_state.done {
11967                let first_selection = selections.iter().min_by_key(|s| s.id).unwrap();
11968                let last_selection = selections.iter().max_by_key(|s| s.id).unwrap();
11969                let mut next_selected_range = None;
11970                // When we're iterating matches backwards, the oldest match will actually be the furthest one in the buffer.
11971                let bytes_before_last_selection =
11972                    buffer.reversed_bytes_in_range(0..last_selection.start);
11973                let bytes_after_first_selection =
11974                    buffer.reversed_bytes_in_range(first_selection.end..buffer.len());
11975                let query_matches = query
11976                    .stream_find_iter(bytes_before_last_selection)
11977                    .map(|result| (last_selection.start, result))
11978                    .chain(
11979                        query
11980                            .stream_find_iter(bytes_after_first_selection)
11981                            .map(|result| (buffer.len(), result)),
11982                    );
11983                for (end_offset, query_match) in query_matches {
11984                    let query_match = query_match.unwrap(); // can only fail due to I/O
11985                    let offset_range =
11986                        end_offset - query_match.end()..end_offset - query_match.start();
11987                    let display_range = offset_range.start.to_display_point(&display_map)
11988                        ..offset_range.end.to_display_point(&display_map);
11989
11990                    if !select_prev_state.wordwise
11991                        || (!movement::is_inside_word(&display_map, display_range.start)
11992                            && !movement::is_inside_word(&display_map, display_range.end))
11993                    {
11994                        next_selected_range = Some(offset_range);
11995                        break;
11996                    }
11997                }
11998
11999                if let Some(next_selected_range) = next_selected_range {
12000                    self.unfold_ranges(&[next_selected_range.clone()], false, true, cx);
12001                    self.change_selections(Some(Autoscroll::newest()), window, cx, |s| {
12002                        if action.replace_newest {
12003                            s.delete(s.newest_anchor().id);
12004                        }
12005                        s.insert_range(next_selected_range);
12006                    });
12007                } else {
12008                    select_prev_state.done = true;
12009                }
12010            }
12011
12012            self.select_prev_state = Some(select_prev_state);
12013        } else {
12014            let mut only_carets = true;
12015            let mut same_text_selected = true;
12016            let mut selected_text = None;
12017
12018            let mut selections_iter = selections.iter().peekable();
12019            while let Some(selection) = selections_iter.next() {
12020                if selection.start != selection.end {
12021                    only_carets = false;
12022                }
12023
12024                if same_text_selected {
12025                    if selected_text.is_none() {
12026                        selected_text =
12027                            Some(buffer.text_for_range(selection.range()).collect::<String>());
12028                    }
12029
12030                    if let Some(next_selection) = selections_iter.peek() {
12031                        if next_selection.range().len() == selection.range().len() {
12032                            let next_selected_text = buffer
12033                                .text_for_range(next_selection.range())
12034                                .collect::<String>();
12035                            if Some(next_selected_text) != selected_text {
12036                                same_text_selected = false;
12037                                selected_text = None;
12038                            }
12039                        } else {
12040                            same_text_selected = false;
12041                            selected_text = None;
12042                        }
12043                    }
12044                }
12045            }
12046
12047            if only_carets {
12048                for selection in &mut selections {
12049                    let word_range = movement::surrounding_word(
12050                        &display_map,
12051                        selection.start.to_display_point(&display_map),
12052                    );
12053                    selection.start = word_range.start.to_offset(&display_map, Bias::Left);
12054                    selection.end = word_range.end.to_offset(&display_map, Bias::Left);
12055                    selection.goal = SelectionGoal::None;
12056                    selection.reversed = false;
12057                }
12058                if selections.len() == 1 {
12059                    let selection = selections
12060                        .last()
12061                        .expect("ensured that there's only one selection");
12062                    let query = buffer
12063                        .text_for_range(selection.start..selection.end)
12064                        .collect::<String>();
12065                    let is_empty = query.is_empty();
12066                    let select_state = SelectNextState {
12067                        query: AhoCorasick::new(&[query.chars().rev().collect::<String>()])?,
12068                        wordwise: true,
12069                        done: is_empty,
12070                    };
12071                    self.select_prev_state = Some(select_state);
12072                } else {
12073                    self.select_prev_state = None;
12074                }
12075
12076                self.unfold_ranges(
12077                    &selections.iter().map(|s| s.range()).collect::<Vec<_>>(),
12078                    false,
12079                    true,
12080                    cx,
12081                );
12082                self.change_selections(Some(Autoscroll::newest()), window, cx, |s| {
12083                    s.select(selections);
12084                });
12085            } else if let Some(selected_text) = selected_text {
12086                self.select_prev_state = Some(SelectNextState {
12087                    query: AhoCorasick::new(&[selected_text.chars().rev().collect::<String>()])?,
12088                    wordwise: false,
12089                    done: false,
12090                });
12091                self.select_previous(action, window, cx)?;
12092            }
12093        }
12094        Ok(())
12095    }
12096
12097    pub fn find_next_match(
12098        &mut self,
12099        _: &FindNextMatch,
12100        window: &mut Window,
12101        cx: &mut Context<Self>,
12102    ) -> Result<()> {
12103        let selections = self.selections.disjoint_anchors();
12104        match selections.first() {
12105            Some(first) if selections.len() >= 2 => {
12106                self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
12107                    s.select_ranges([first.range()]);
12108                });
12109            }
12110            _ => self.select_next(
12111                &SelectNext {
12112                    replace_newest: true,
12113                },
12114                window,
12115                cx,
12116            )?,
12117        }
12118        Ok(())
12119    }
12120
12121    pub fn find_previous_match(
12122        &mut self,
12123        _: &FindPreviousMatch,
12124        window: &mut Window,
12125        cx: &mut Context<Self>,
12126    ) -> Result<()> {
12127        let selections = self.selections.disjoint_anchors();
12128        match selections.last() {
12129            Some(last) if selections.len() >= 2 => {
12130                self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
12131                    s.select_ranges([last.range()]);
12132                });
12133            }
12134            _ => self.select_previous(
12135                &SelectPrevious {
12136                    replace_newest: true,
12137                },
12138                window,
12139                cx,
12140            )?,
12141        }
12142        Ok(())
12143    }
12144
12145    pub fn toggle_comments(
12146        &mut self,
12147        action: &ToggleComments,
12148        window: &mut Window,
12149        cx: &mut Context<Self>,
12150    ) {
12151        if self.read_only(cx) {
12152            return;
12153        }
12154        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
12155        let text_layout_details = &self.text_layout_details(window);
12156        self.transact(window, cx, |this, window, cx| {
12157            let mut selections = this.selections.all::<MultiBufferPoint>(cx);
12158            let mut edits = Vec::new();
12159            let mut selection_edit_ranges = Vec::new();
12160            let mut last_toggled_row = None;
12161            let snapshot = this.buffer.read(cx).read(cx);
12162            let empty_str: Arc<str> = Arc::default();
12163            let mut suffixes_inserted = Vec::new();
12164            let ignore_indent = action.ignore_indent;
12165
12166            fn comment_prefix_range(
12167                snapshot: &MultiBufferSnapshot,
12168                row: MultiBufferRow,
12169                comment_prefix: &str,
12170                comment_prefix_whitespace: &str,
12171                ignore_indent: bool,
12172            ) -> Range<Point> {
12173                let indent_size = if ignore_indent {
12174                    0
12175                } else {
12176                    snapshot.indent_size_for_line(row).len
12177                };
12178
12179                let start = Point::new(row.0, indent_size);
12180
12181                let mut line_bytes = snapshot
12182                    .bytes_in_range(start..snapshot.max_point())
12183                    .flatten()
12184                    .copied();
12185
12186                // If this line currently begins with the line comment prefix, then record
12187                // the range containing the prefix.
12188                if line_bytes
12189                    .by_ref()
12190                    .take(comment_prefix.len())
12191                    .eq(comment_prefix.bytes())
12192                {
12193                    // Include any whitespace that matches the comment prefix.
12194                    let matching_whitespace_len = line_bytes
12195                        .zip(comment_prefix_whitespace.bytes())
12196                        .take_while(|(a, b)| a == b)
12197                        .count() as u32;
12198                    let end = Point::new(
12199                        start.row,
12200                        start.column + comment_prefix.len() as u32 + matching_whitespace_len,
12201                    );
12202                    start..end
12203                } else {
12204                    start..start
12205                }
12206            }
12207
12208            fn comment_suffix_range(
12209                snapshot: &MultiBufferSnapshot,
12210                row: MultiBufferRow,
12211                comment_suffix: &str,
12212                comment_suffix_has_leading_space: bool,
12213            ) -> Range<Point> {
12214                let end = Point::new(row.0, snapshot.line_len(row));
12215                let suffix_start_column = end.column.saturating_sub(comment_suffix.len() as u32);
12216
12217                let mut line_end_bytes = snapshot
12218                    .bytes_in_range(Point::new(end.row, suffix_start_column.saturating_sub(1))..end)
12219                    .flatten()
12220                    .copied();
12221
12222                let leading_space_len = if suffix_start_column > 0
12223                    && line_end_bytes.next() == Some(b' ')
12224                    && comment_suffix_has_leading_space
12225                {
12226                    1
12227                } else {
12228                    0
12229                };
12230
12231                // If this line currently begins with the line comment prefix, then record
12232                // the range containing the prefix.
12233                if line_end_bytes.by_ref().eq(comment_suffix.bytes()) {
12234                    let start = Point::new(end.row, suffix_start_column - leading_space_len);
12235                    start..end
12236                } else {
12237                    end..end
12238                }
12239            }
12240
12241            // TODO: Handle selections that cross excerpts
12242            for selection in &mut selections {
12243                let start_column = snapshot
12244                    .indent_size_for_line(MultiBufferRow(selection.start.row))
12245                    .len;
12246                let language = if let Some(language) =
12247                    snapshot.language_scope_at(Point::new(selection.start.row, start_column))
12248                {
12249                    language
12250                } else {
12251                    continue;
12252                };
12253
12254                selection_edit_ranges.clear();
12255
12256                // If multiple selections contain a given row, avoid processing that
12257                // row more than once.
12258                let mut start_row = MultiBufferRow(selection.start.row);
12259                if last_toggled_row == Some(start_row) {
12260                    start_row = start_row.next_row();
12261                }
12262                let end_row =
12263                    if selection.end.row > selection.start.row && selection.end.column == 0 {
12264                        MultiBufferRow(selection.end.row - 1)
12265                    } else {
12266                        MultiBufferRow(selection.end.row)
12267                    };
12268                last_toggled_row = Some(end_row);
12269
12270                if start_row > end_row {
12271                    continue;
12272                }
12273
12274                // If the language has line comments, toggle those.
12275                let mut full_comment_prefixes = language.line_comment_prefixes().to_vec();
12276
12277                // If ignore_indent is set, trim spaces from the right side of all full_comment_prefixes
12278                if ignore_indent {
12279                    full_comment_prefixes = full_comment_prefixes
12280                        .into_iter()
12281                        .map(|s| Arc::from(s.trim_end()))
12282                        .collect();
12283                }
12284
12285                if !full_comment_prefixes.is_empty() {
12286                    let first_prefix = full_comment_prefixes
12287                        .first()
12288                        .expect("prefixes is non-empty");
12289                    let prefix_trimmed_lengths = full_comment_prefixes
12290                        .iter()
12291                        .map(|p| p.trim_end_matches(' ').len())
12292                        .collect::<SmallVec<[usize; 4]>>();
12293
12294                    let mut all_selection_lines_are_comments = true;
12295
12296                    for row in start_row.0..=end_row.0 {
12297                        let row = MultiBufferRow(row);
12298                        if start_row < end_row && snapshot.is_line_blank(row) {
12299                            continue;
12300                        }
12301
12302                        let prefix_range = full_comment_prefixes
12303                            .iter()
12304                            .zip(prefix_trimmed_lengths.iter().copied())
12305                            .map(|(prefix, trimmed_prefix_len)| {
12306                                comment_prefix_range(
12307                                    snapshot.deref(),
12308                                    row,
12309                                    &prefix[..trimmed_prefix_len],
12310                                    &prefix[trimmed_prefix_len..],
12311                                    ignore_indent,
12312                                )
12313                            })
12314                            .max_by_key(|range| range.end.column - range.start.column)
12315                            .expect("prefixes is non-empty");
12316
12317                        if prefix_range.is_empty() {
12318                            all_selection_lines_are_comments = false;
12319                        }
12320
12321                        selection_edit_ranges.push(prefix_range);
12322                    }
12323
12324                    if all_selection_lines_are_comments {
12325                        edits.extend(
12326                            selection_edit_ranges
12327                                .iter()
12328                                .cloned()
12329                                .map(|range| (range, empty_str.clone())),
12330                        );
12331                    } else {
12332                        let min_column = selection_edit_ranges
12333                            .iter()
12334                            .map(|range| range.start.column)
12335                            .min()
12336                            .unwrap_or(0);
12337                        edits.extend(selection_edit_ranges.iter().map(|range| {
12338                            let position = Point::new(range.start.row, min_column);
12339                            (position..position, first_prefix.clone())
12340                        }));
12341                    }
12342                } else if let Some((full_comment_prefix, comment_suffix)) =
12343                    language.block_comment_delimiters()
12344                {
12345                    let comment_prefix = full_comment_prefix.trim_end_matches(' ');
12346                    let comment_prefix_whitespace = &full_comment_prefix[comment_prefix.len()..];
12347                    let prefix_range = comment_prefix_range(
12348                        snapshot.deref(),
12349                        start_row,
12350                        comment_prefix,
12351                        comment_prefix_whitespace,
12352                        ignore_indent,
12353                    );
12354                    let suffix_range = comment_suffix_range(
12355                        snapshot.deref(),
12356                        end_row,
12357                        comment_suffix.trim_start_matches(' '),
12358                        comment_suffix.starts_with(' '),
12359                    );
12360
12361                    if prefix_range.is_empty() || suffix_range.is_empty() {
12362                        edits.push((
12363                            prefix_range.start..prefix_range.start,
12364                            full_comment_prefix.clone(),
12365                        ));
12366                        edits.push((suffix_range.end..suffix_range.end, comment_suffix.clone()));
12367                        suffixes_inserted.push((end_row, comment_suffix.len()));
12368                    } else {
12369                        edits.push((prefix_range, empty_str.clone()));
12370                        edits.push((suffix_range, empty_str.clone()));
12371                    }
12372                } else {
12373                    continue;
12374                }
12375            }
12376
12377            drop(snapshot);
12378            this.buffer.update(cx, |buffer, cx| {
12379                buffer.edit(edits, None, cx);
12380            });
12381
12382            // Adjust selections so that they end before any comment suffixes that
12383            // were inserted.
12384            let mut suffixes_inserted = suffixes_inserted.into_iter().peekable();
12385            let mut selections = this.selections.all::<Point>(cx);
12386            let snapshot = this.buffer.read(cx).read(cx);
12387            for selection in &mut selections {
12388                while let Some((row, suffix_len)) = suffixes_inserted.peek().copied() {
12389                    match row.cmp(&MultiBufferRow(selection.end.row)) {
12390                        Ordering::Less => {
12391                            suffixes_inserted.next();
12392                            continue;
12393                        }
12394                        Ordering::Greater => break,
12395                        Ordering::Equal => {
12396                            if selection.end.column == snapshot.line_len(row) {
12397                                if selection.is_empty() {
12398                                    selection.start.column -= suffix_len as u32;
12399                                }
12400                                selection.end.column -= suffix_len as u32;
12401                            }
12402                            break;
12403                        }
12404                    }
12405                }
12406            }
12407
12408            drop(snapshot);
12409            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
12410                s.select(selections)
12411            });
12412
12413            let selections = this.selections.all::<Point>(cx);
12414            let selections_on_single_row = selections.windows(2).all(|selections| {
12415                selections[0].start.row == selections[1].start.row
12416                    && selections[0].end.row == selections[1].end.row
12417                    && selections[0].start.row == selections[0].end.row
12418            });
12419            let selections_selecting = selections
12420                .iter()
12421                .any(|selection| selection.start != selection.end);
12422            let advance_downwards = action.advance_downwards
12423                && selections_on_single_row
12424                && !selections_selecting
12425                && !matches!(this.mode, EditorMode::SingleLine { .. });
12426
12427            if advance_downwards {
12428                let snapshot = this.buffer.read(cx).snapshot(cx);
12429
12430                this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
12431                    s.move_cursors_with(|display_snapshot, display_point, _| {
12432                        let mut point = display_point.to_point(display_snapshot);
12433                        point.row += 1;
12434                        point = snapshot.clip_point(point, Bias::Left);
12435                        let display_point = point.to_display_point(display_snapshot);
12436                        let goal = SelectionGoal::HorizontalPosition(
12437                            display_snapshot
12438                                .x_for_display_point(display_point, text_layout_details)
12439                                .into(),
12440                        );
12441                        (display_point, goal)
12442                    })
12443                });
12444            }
12445        });
12446    }
12447
12448    pub fn select_enclosing_symbol(
12449        &mut self,
12450        _: &SelectEnclosingSymbol,
12451        window: &mut Window,
12452        cx: &mut Context<Self>,
12453    ) {
12454        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
12455
12456        let buffer = self.buffer.read(cx).snapshot(cx);
12457        let old_selections = self.selections.all::<usize>(cx).into_boxed_slice();
12458
12459        fn update_selection(
12460            selection: &Selection<usize>,
12461            buffer_snap: &MultiBufferSnapshot,
12462        ) -> Option<Selection<usize>> {
12463            let cursor = selection.head();
12464            let (_buffer_id, symbols) = buffer_snap.symbols_containing(cursor, None)?;
12465            for symbol in symbols.iter().rev() {
12466                let start = symbol.range.start.to_offset(buffer_snap);
12467                let end = symbol.range.end.to_offset(buffer_snap);
12468                let new_range = start..end;
12469                if start < selection.start || end > selection.end {
12470                    return Some(Selection {
12471                        id: selection.id,
12472                        start: new_range.start,
12473                        end: new_range.end,
12474                        goal: SelectionGoal::None,
12475                        reversed: selection.reversed,
12476                    });
12477                }
12478            }
12479            None
12480        }
12481
12482        let mut selected_larger_symbol = false;
12483        let new_selections = old_selections
12484            .iter()
12485            .map(|selection| match update_selection(selection, &buffer) {
12486                Some(new_selection) => {
12487                    if new_selection.range() != selection.range() {
12488                        selected_larger_symbol = true;
12489                    }
12490                    new_selection
12491                }
12492                None => selection.clone(),
12493            })
12494            .collect::<Vec<_>>();
12495
12496        if selected_larger_symbol {
12497            self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
12498                s.select(new_selections);
12499            });
12500        }
12501    }
12502
12503    pub fn select_larger_syntax_node(
12504        &mut self,
12505        _: &SelectLargerSyntaxNode,
12506        window: &mut Window,
12507        cx: &mut Context<Self>,
12508    ) {
12509        let Some(visible_row_count) = self.visible_row_count() else {
12510            return;
12511        };
12512        let old_selections: Box<[_]> = self.selections.all::<usize>(cx).into();
12513        if old_selections.is_empty() {
12514            return;
12515        }
12516
12517        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
12518
12519        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
12520        let buffer = self.buffer.read(cx).snapshot(cx);
12521
12522        let mut selected_larger_node = false;
12523        let mut new_selections = old_selections
12524            .iter()
12525            .map(|selection| {
12526                let old_range = selection.start..selection.end;
12527                let mut new_range = old_range.clone();
12528                let mut new_node = None;
12529                while let Some((node, containing_range)) = buffer.syntax_ancestor(new_range.clone())
12530                {
12531                    new_node = Some(node);
12532                    new_range = match containing_range {
12533                        MultiOrSingleBufferOffsetRange::Single(_) => break,
12534                        MultiOrSingleBufferOffsetRange::Multi(range) => range,
12535                    };
12536                    if !display_map.intersects_fold(new_range.start)
12537                        && !display_map.intersects_fold(new_range.end)
12538                    {
12539                        break;
12540                    }
12541                }
12542
12543                if let Some(node) = new_node {
12544                    // Log the ancestor, to support using this action as a way to explore TreeSitter
12545                    // nodes. Parent and grandparent are also logged because this operation will not
12546                    // visit nodes that have the same range as their parent.
12547                    log::info!("Node: {node:?}");
12548                    let parent = node.parent();
12549                    log::info!("Parent: {parent:?}");
12550                    let grandparent = parent.and_then(|x| x.parent());
12551                    log::info!("Grandparent: {grandparent:?}");
12552                }
12553
12554                selected_larger_node |= new_range != old_range;
12555                Selection {
12556                    id: selection.id,
12557                    start: new_range.start,
12558                    end: new_range.end,
12559                    goal: SelectionGoal::None,
12560                    reversed: selection.reversed,
12561                }
12562            })
12563            .collect::<Vec<_>>();
12564
12565        if !selected_larger_node {
12566            return; // don't put this call in the history
12567        }
12568
12569        // scroll based on transformation done to the last selection created by the user
12570        let (last_old, last_new) = old_selections
12571            .last()
12572            .zip(new_selections.last().cloned())
12573            .expect("old_selections isn't empty");
12574
12575        // revert selection
12576        let is_selection_reversed = {
12577            let should_newest_selection_be_reversed = last_old.start != last_new.start;
12578            new_selections.last_mut().expect("checked above").reversed =
12579                should_newest_selection_be_reversed;
12580            should_newest_selection_be_reversed
12581        };
12582
12583        if selected_larger_node {
12584            self.select_syntax_node_history.disable_clearing = true;
12585            self.change_selections(None, window, cx, |s| {
12586                s.select(new_selections.clone());
12587            });
12588            self.select_syntax_node_history.disable_clearing = false;
12589        }
12590
12591        let start_row = last_new.start.to_display_point(&display_map).row().0;
12592        let end_row = last_new.end.to_display_point(&display_map).row().0;
12593        let selection_height = end_row - start_row + 1;
12594        let scroll_margin_rows = self.vertical_scroll_margin() as u32;
12595
12596        let fits_on_the_screen = visible_row_count >= selection_height + scroll_margin_rows * 2;
12597        let scroll_behavior = if fits_on_the_screen {
12598            self.request_autoscroll(Autoscroll::fit(), cx);
12599            SelectSyntaxNodeScrollBehavior::FitSelection
12600        } else if is_selection_reversed {
12601            self.scroll_cursor_top(&ScrollCursorTop, window, cx);
12602            SelectSyntaxNodeScrollBehavior::CursorTop
12603        } else {
12604            self.scroll_cursor_bottom(&ScrollCursorBottom, window, cx);
12605            SelectSyntaxNodeScrollBehavior::CursorBottom
12606        };
12607
12608        self.select_syntax_node_history.push((
12609            old_selections,
12610            scroll_behavior,
12611            is_selection_reversed,
12612        ));
12613    }
12614
12615    pub fn select_smaller_syntax_node(
12616        &mut self,
12617        _: &SelectSmallerSyntaxNode,
12618        window: &mut Window,
12619        cx: &mut Context<Self>,
12620    ) {
12621        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
12622
12623        if let Some((mut selections, scroll_behavior, is_selection_reversed)) =
12624            self.select_syntax_node_history.pop()
12625        {
12626            if let Some(selection) = selections.last_mut() {
12627                selection.reversed = is_selection_reversed;
12628            }
12629
12630            self.select_syntax_node_history.disable_clearing = true;
12631            self.change_selections(None, window, cx, |s| {
12632                s.select(selections.to_vec());
12633            });
12634            self.select_syntax_node_history.disable_clearing = false;
12635
12636            match scroll_behavior {
12637                SelectSyntaxNodeScrollBehavior::CursorTop => {
12638                    self.scroll_cursor_top(&ScrollCursorTop, window, cx);
12639                }
12640                SelectSyntaxNodeScrollBehavior::FitSelection => {
12641                    self.request_autoscroll(Autoscroll::fit(), cx);
12642                }
12643                SelectSyntaxNodeScrollBehavior::CursorBottom => {
12644                    self.scroll_cursor_bottom(&ScrollCursorBottom, window, cx);
12645                }
12646            }
12647        }
12648    }
12649
12650    fn refresh_runnables(&mut self, window: &mut Window, cx: &mut Context<Self>) -> Task<()> {
12651        if !EditorSettings::get_global(cx).gutter.runnables {
12652            self.clear_tasks();
12653            return Task::ready(());
12654        }
12655        let project = self.project.as_ref().map(Entity::downgrade);
12656        let task_sources = self.lsp_task_sources(cx);
12657        cx.spawn_in(window, async move |editor, cx| {
12658            cx.background_executor().timer(UPDATE_DEBOUNCE).await;
12659            let Some(project) = project.and_then(|p| p.upgrade()) else {
12660                return;
12661            };
12662            let Ok(display_snapshot) = editor.update(cx, |this, cx| {
12663                this.display_map.update(cx, |map, cx| map.snapshot(cx))
12664            }) else {
12665                return;
12666            };
12667
12668            let hide_runnables = project
12669                .update(cx, |project, cx| {
12670                    // Do not display any test indicators in non-dev server remote projects.
12671                    project.is_via_collab() && project.ssh_connection_string(cx).is_none()
12672                })
12673                .unwrap_or(true);
12674            if hide_runnables {
12675                return;
12676            }
12677            let new_rows =
12678                cx.background_spawn({
12679                    let snapshot = display_snapshot.clone();
12680                    async move {
12681                        Self::fetch_runnable_ranges(&snapshot, Anchor::min()..Anchor::max())
12682                    }
12683                })
12684                    .await;
12685            let Ok(lsp_tasks) =
12686                cx.update(|_, cx| crate::lsp_tasks(project.clone(), &task_sources, None, cx))
12687            else {
12688                return;
12689            };
12690            let lsp_tasks = lsp_tasks.await;
12691
12692            let Ok(mut lsp_tasks_by_rows) = cx.update(|_, cx| {
12693                lsp_tasks
12694                    .into_iter()
12695                    .flat_map(|(kind, tasks)| {
12696                        tasks.into_iter().filter_map(move |(location, task)| {
12697                            Some((kind.clone(), location?, task))
12698                        })
12699                    })
12700                    .fold(HashMap::default(), |mut acc, (kind, location, task)| {
12701                        let buffer = location.target.buffer;
12702                        let buffer_snapshot = buffer.read(cx).snapshot();
12703                        let offset = display_snapshot.buffer_snapshot.excerpts().find_map(
12704                            |(excerpt_id, snapshot, _)| {
12705                                if snapshot.remote_id() == buffer_snapshot.remote_id() {
12706                                    display_snapshot
12707                                        .buffer_snapshot
12708                                        .anchor_in_excerpt(excerpt_id, location.target.range.start)
12709                                } else {
12710                                    None
12711                                }
12712                            },
12713                        );
12714                        if let Some(offset) = offset {
12715                            let task_buffer_range =
12716                                location.target.range.to_point(&buffer_snapshot);
12717                            let context_buffer_range =
12718                                task_buffer_range.to_offset(&buffer_snapshot);
12719                            let context_range = BufferOffset(context_buffer_range.start)
12720                                ..BufferOffset(context_buffer_range.end);
12721
12722                            acc.entry((buffer_snapshot.remote_id(), task_buffer_range.start.row))
12723                                .or_insert_with(|| RunnableTasks {
12724                                    templates: Vec::new(),
12725                                    offset,
12726                                    column: task_buffer_range.start.column,
12727                                    extra_variables: HashMap::default(),
12728                                    context_range,
12729                                })
12730                                .templates
12731                                .push((kind, task.original_task().clone()));
12732                        }
12733
12734                        acc
12735                    })
12736            }) else {
12737                return;
12738            };
12739
12740            let rows = Self::runnable_rows(project, display_snapshot, new_rows, cx.clone());
12741            editor
12742                .update(cx, |editor, _| {
12743                    editor.clear_tasks();
12744                    for (key, mut value) in rows {
12745                        if let Some(lsp_tasks) = lsp_tasks_by_rows.remove(&key) {
12746                            value.templates.extend(lsp_tasks.templates);
12747                        }
12748
12749                        editor.insert_tasks(key, value);
12750                    }
12751                    for (key, value) in lsp_tasks_by_rows {
12752                        editor.insert_tasks(key, value);
12753                    }
12754                })
12755                .ok();
12756        })
12757    }
12758    fn fetch_runnable_ranges(
12759        snapshot: &DisplaySnapshot,
12760        range: Range<Anchor>,
12761    ) -> Vec<language::RunnableRange> {
12762        snapshot.buffer_snapshot.runnable_ranges(range).collect()
12763    }
12764
12765    fn runnable_rows(
12766        project: Entity<Project>,
12767        snapshot: DisplaySnapshot,
12768        runnable_ranges: Vec<RunnableRange>,
12769        mut cx: AsyncWindowContext,
12770    ) -> Vec<((BufferId, BufferRow), RunnableTasks)> {
12771        runnable_ranges
12772            .into_iter()
12773            .filter_map(|mut runnable| {
12774                let tasks = cx
12775                    .update(|_, cx| Self::templates_with_tags(&project, &mut runnable.runnable, cx))
12776                    .ok()?;
12777                if tasks.is_empty() {
12778                    return None;
12779                }
12780
12781                let point = runnable.run_range.start.to_point(&snapshot.buffer_snapshot);
12782
12783                let row = snapshot
12784                    .buffer_snapshot
12785                    .buffer_line_for_row(MultiBufferRow(point.row))?
12786                    .1
12787                    .start
12788                    .row;
12789
12790                let context_range =
12791                    BufferOffset(runnable.full_range.start)..BufferOffset(runnable.full_range.end);
12792                Some((
12793                    (runnable.buffer_id, row),
12794                    RunnableTasks {
12795                        templates: tasks,
12796                        offset: snapshot
12797                            .buffer_snapshot
12798                            .anchor_before(runnable.run_range.start),
12799                        context_range,
12800                        column: point.column,
12801                        extra_variables: runnable.extra_captures,
12802                    },
12803                ))
12804            })
12805            .collect()
12806    }
12807
12808    fn templates_with_tags(
12809        project: &Entity<Project>,
12810        runnable: &mut Runnable,
12811        cx: &mut App,
12812    ) -> Vec<(TaskSourceKind, TaskTemplate)> {
12813        let (inventory, worktree_id, file) = project.read_with(cx, |project, cx| {
12814            let (worktree_id, file) = project
12815                .buffer_for_id(runnable.buffer, cx)
12816                .and_then(|buffer| buffer.read(cx).file())
12817                .map(|file| (file.worktree_id(cx), file.clone()))
12818                .unzip();
12819
12820            (
12821                project.task_store().read(cx).task_inventory().cloned(),
12822                worktree_id,
12823                file,
12824            )
12825        });
12826
12827        let mut templates_with_tags = mem::take(&mut runnable.tags)
12828            .into_iter()
12829            .flat_map(|RunnableTag(tag)| {
12830                inventory
12831                    .as_ref()
12832                    .into_iter()
12833                    .flat_map(|inventory| {
12834                        inventory.read(cx).list_tasks(
12835                            file.clone(),
12836                            Some(runnable.language.clone()),
12837                            worktree_id,
12838                            cx,
12839                        )
12840                    })
12841                    .filter(move |(_, template)| {
12842                        template.tags.iter().any(|source_tag| source_tag == &tag)
12843                    })
12844            })
12845            .sorted_by_key(|(kind, _)| kind.to_owned())
12846            .collect::<Vec<_>>();
12847        if let Some((leading_tag_source, _)) = templates_with_tags.first() {
12848            // Strongest source wins; if we have worktree tag binding, prefer that to
12849            // global and language bindings;
12850            // if we have a global binding, prefer that to language binding.
12851            let first_mismatch = templates_with_tags
12852                .iter()
12853                .position(|(tag_source, _)| tag_source != leading_tag_source);
12854            if let Some(index) = first_mismatch {
12855                templates_with_tags.truncate(index);
12856            }
12857        }
12858
12859        templates_with_tags
12860    }
12861
12862    pub fn move_to_enclosing_bracket(
12863        &mut self,
12864        _: &MoveToEnclosingBracket,
12865        window: &mut Window,
12866        cx: &mut Context<Self>,
12867    ) {
12868        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
12869        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
12870            s.move_offsets_with(|snapshot, selection| {
12871                let Some(enclosing_bracket_ranges) =
12872                    snapshot.enclosing_bracket_ranges(selection.start..selection.end)
12873                else {
12874                    return;
12875                };
12876
12877                let mut best_length = usize::MAX;
12878                let mut best_inside = false;
12879                let mut best_in_bracket_range = false;
12880                let mut best_destination = None;
12881                for (open, close) in enclosing_bracket_ranges {
12882                    let close = close.to_inclusive();
12883                    let length = close.end() - open.start;
12884                    let inside = selection.start >= open.end && selection.end <= *close.start();
12885                    let in_bracket_range = open.to_inclusive().contains(&selection.head())
12886                        || close.contains(&selection.head());
12887
12888                    // If best is next to a bracket and current isn't, skip
12889                    if !in_bracket_range && best_in_bracket_range {
12890                        continue;
12891                    }
12892
12893                    // Prefer smaller lengths unless best is inside and current isn't
12894                    if length > best_length && (best_inside || !inside) {
12895                        continue;
12896                    }
12897
12898                    best_length = length;
12899                    best_inside = inside;
12900                    best_in_bracket_range = in_bracket_range;
12901                    best_destination = Some(
12902                        if close.contains(&selection.start) && close.contains(&selection.end) {
12903                            if inside { open.end } else { open.start }
12904                        } else if inside {
12905                            *close.start()
12906                        } else {
12907                            *close.end()
12908                        },
12909                    );
12910                }
12911
12912                if let Some(destination) = best_destination {
12913                    selection.collapse_to(destination, SelectionGoal::None);
12914                }
12915            })
12916        });
12917    }
12918
12919    pub fn undo_selection(
12920        &mut self,
12921        _: &UndoSelection,
12922        window: &mut Window,
12923        cx: &mut Context<Self>,
12924    ) {
12925        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
12926        self.end_selection(window, cx);
12927        self.selection_history.mode = SelectionHistoryMode::Undoing;
12928        if let Some(entry) = self.selection_history.undo_stack.pop_back() {
12929            self.change_selections(None, window, cx, |s| {
12930                s.select_anchors(entry.selections.to_vec())
12931            });
12932            self.select_next_state = entry.select_next_state;
12933            self.select_prev_state = entry.select_prev_state;
12934            self.add_selections_state = entry.add_selections_state;
12935            self.request_autoscroll(Autoscroll::newest(), cx);
12936        }
12937        self.selection_history.mode = SelectionHistoryMode::Normal;
12938    }
12939
12940    pub fn redo_selection(
12941        &mut self,
12942        _: &RedoSelection,
12943        window: &mut Window,
12944        cx: &mut Context<Self>,
12945    ) {
12946        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
12947        self.end_selection(window, cx);
12948        self.selection_history.mode = SelectionHistoryMode::Redoing;
12949        if let Some(entry) = self.selection_history.redo_stack.pop_back() {
12950            self.change_selections(None, window, cx, |s| {
12951                s.select_anchors(entry.selections.to_vec())
12952            });
12953            self.select_next_state = entry.select_next_state;
12954            self.select_prev_state = entry.select_prev_state;
12955            self.add_selections_state = entry.add_selections_state;
12956            self.request_autoscroll(Autoscroll::newest(), cx);
12957        }
12958        self.selection_history.mode = SelectionHistoryMode::Normal;
12959    }
12960
12961    pub fn expand_excerpts(
12962        &mut self,
12963        action: &ExpandExcerpts,
12964        _: &mut Window,
12965        cx: &mut Context<Self>,
12966    ) {
12967        self.expand_excerpts_for_direction(action.lines, ExpandExcerptDirection::UpAndDown, cx)
12968    }
12969
12970    pub fn expand_excerpts_down(
12971        &mut self,
12972        action: &ExpandExcerptsDown,
12973        _: &mut Window,
12974        cx: &mut Context<Self>,
12975    ) {
12976        self.expand_excerpts_for_direction(action.lines, ExpandExcerptDirection::Down, cx)
12977    }
12978
12979    pub fn expand_excerpts_up(
12980        &mut self,
12981        action: &ExpandExcerptsUp,
12982        _: &mut Window,
12983        cx: &mut Context<Self>,
12984    ) {
12985        self.expand_excerpts_for_direction(action.lines, ExpandExcerptDirection::Up, cx)
12986    }
12987
12988    pub fn expand_excerpts_for_direction(
12989        &mut self,
12990        lines: u32,
12991        direction: ExpandExcerptDirection,
12992
12993        cx: &mut Context<Self>,
12994    ) {
12995        let selections = self.selections.disjoint_anchors();
12996
12997        let lines = if lines == 0 {
12998            EditorSettings::get_global(cx).expand_excerpt_lines
12999        } else {
13000            lines
13001        };
13002
13003        self.buffer.update(cx, |buffer, cx| {
13004            let snapshot = buffer.snapshot(cx);
13005            let mut excerpt_ids = selections
13006                .iter()
13007                .flat_map(|selection| snapshot.excerpt_ids_for_range(selection.range()))
13008                .collect::<Vec<_>>();
13009            excerpt_ids.sort();
13010            excerpt_ids.dedup();
13011            buffer.expand_excerpts(excerpt_ids, lines, direction, cx)
13012        })
13013    }
13014
13015    pub fn expand_excerpt(
13016        &mut self,
13017        excerpt: ExcerptId,
13018        direction: ExpandExcerptDirection,
13019        window: &mut Window,
13020        cx: &mut Context<Self>,
13021    ) {
13022        let current_scroll_position = self.scroll_position(cx);
13023        let lines_to_expand = EditorSettings::get_global(cx).expand_excerpt_lines;
13024        let mut should_scroll_up = false;
13025
13026        if direction == ExpandExcerptDirection::Down {
13027            let multi_buffer = self.buffer.read(cx);
13028            let snapshot = multi_buffer.snapshot(cx);
13029            if let Some(buffer_id) = snapshot.buffer_id_for_excerpt(excerpt) {
13030                if let Some(buffer) = multi_buffer.buffer(buffer_id) {
13031                    if let Some(excerpt_range) = snapshot.buffer_range_for_excerpt(excerpt) {
13032                        let buffer_snapshot = buffer.read(cx).snapshot();
13033                        let excerpt_end_row =
13034                            Point::from_anchor(&excerpt_range.end, &buffer_snapshot).row;
13035                        let last_row = buffer_snapshot.max_point().row;
13036                        let lines_below = last_row.saturating_sub(excerpt_end_row);
13037                        should_scroll_up = lines_below >= lines_to_expand;
13038                    }
13039                }
13040            }
13041        }
13042
13043        self.buffer.update(cx, |buffer, cx| {
13044            buffer.expand_excerpts([excerpt], lines_to_expand, direction, cx)
13045        });
13046
13047        if should_scroll_up {
13048            let new_scroll_position =
13049                current_scroll_position + gpui::Point::new(0.0, lines_to_expand as f32);
13050            self.set_scroll_position(new_scroll_position, window, cx);
13051        }
13052    }
13053
13054    pub fn go_to_singleton_buffer_point(
13055        &mut self,
13056        point: Point,
13057        window: &mut Window,
13058        cx: &mut Context<Self>,
13059    ) {
13060        self.go_to_singleton_buffer_range(point..point, window, cx);
13061    }
13062
13063    pub fn go_to_singleton_buffer_range(
13064        &mut self,
13065        range: Range<Point>,
13066        window: &mut Window,
13067        cx: &mut Context<Self>,
13068    ) {
13069        let multibuffer = self.buffer().read(cx);
13070        let Some(buffer) = multibuffer.as_singleton() else {
13071            return;
13072        };
13073        let Some(start) = multibuffer.buffer_point_to_anchor(&buffer, range.start, cx) else {
13074            return;
13075        };
13076        let Some(end) = multibuffer.buffer_point_to_anchor(&buffer, range.end, cx) else {
13077            return;
13078        };
13079        self.change_selections(Some(Autoscroll::center()), window, cx, |s| {
13080            s.select_anchor_ranges([start..end])
13081        });
13082    }
13083
13084    pub fn go_to_diagnostic(
13085        &mut self,
13086        _: &GoToDiagnostic,
13087        window: &mut Window,
13088        cx: &mut Context<Self>,
13089    ) {
13090        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
13091        self.go_to_diagnostic_impl(Direction::Next, window, cx)
13092    }
13093
13094    pub fn go_to_prev_diagnostic(
13095        &mut self,
13096        _: &GoToPreviousDiagnostic,
13097        window: &mut Window,
13098        cx: &mut Context<Self>,
13099    ) {
13100        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
13101        self.go_to_diagnostic_impl(Direction::Prev, window, cx)
13102    }
13103
13104    pub fn go_to_diagnostic_impl(
13105        &mut self,
13106        direction: Direction,
13107        window: &mut Window,
13108        cx: &mut Context<Self>,
13109    ) {
13110        let buffer = self.buffer.read(cx).snapshot(cx);
13111        let selection = self.selections.newest::<usize>(cx);
13112
13113        let mut active_group_id = None;
13114        if let ActiveDiagnostic::Group(active_group) = &self.active_diagnostics {
13115            if active_group.active_range.start.to_offset(&buffer) == selection.start {
13116                active_group_id = Some(active_group.group_id);
13117            }
13118        }
13119
13120        fn filtered(
13121            snapshot: EditorSnapshot,
13122            diagnostics: impl Iterator<Item = DiagnosticEntry<usize>>,
13123        ) -> impl Iterator<Item = DiagnosticEntry<usize>> {
13124            diagnostics
13125                .filter(|entry| entry.range.start != entry.range.end)
13126                .filter(|entry| !entry.diagnostic.is_unnecessary)
13127                .filter(move |entry| !snapshot.intersects_fold(entry.range.start))
13128        }
13129
13130        let snapshot = self.snapshot(window, cx);
13131        let before = filtered(
13132            snapshot.clone(),
13133            buffer
13134                .diagnostics_in_range(0..selection.start)
13135                .filter(|entry| entry.range.start <= selection.start),
13136        );
13137        let after = filtered(
13138            snapshot,
13139            buffer
13140                .diagnostics_in_range(selection.start..buffer.len())
13141                .filter(|entry| entry.range.start >= selection.start),
13142        );
13143
13144        let mut found: Option<DiagnosticEntry<usize>> = None;
13145        if direction == Direction::Prev {
13146            'outer: for prev_diagnostics in [before.collect::<Vec<_>>(), after.collect::<Vec<_>>()]
13147            {
13148                for diagnostic in prev_diagnostics.into_iter().rev() {
13149                    if diagnostic.range.start != selection.start
13150                        || active_group_id
13151                            .is_some_and(|active| diagnostic.diagnostic.group_id < active)
13152                    {
13153                        found = Some(diagnostic);
13154                        break 'outer;
13155                    }
13156                }
13157            }
13158        } else {
13159            for diagnostic in after.chain(before) {
13160                if diagnostic.range.start != selection.start
13161                    || active_group_id.is_some_and(|active| diagnostic.diagnostic.group_id > active)
13162                {
13163                    found = Some(diagnostic);
13164                    break;
13165                }
13166            }
13167        }
13168        let Some(next_diagnostic) = found else {
13169            return;
13170        };
13171
13172        let Some(buffer_id) = buffer.anchor_after(next_diagnostic.range.start).buffer_id else {
13173            return;
13174        };
13175        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
13176            s.select_ranges(vec![
13177                next_diagnostic.range.start..next_diagnostic.range.start,
13178            ])
13179        });
13180        self.activate_diagnostics(buffer_id, next_diagnostic, window, cx);
13181        self.refresh_inline_completion(false, true, window, cx);
13182    }
13183
13184    fn go_to_next_hunk(&mut self, _: &GoToHunk, window: &mut Window, cx: &mut Context<Self>) {
13185        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
13186        let snapshot = self.snapshot(window, cx);
13187        let selection = self.selections.newest::<Point>(cx);
13188        self.go_to_hunk_before_or_after_position(
13189            &snapshot,
13190            selection.head(),
13191            Direction::Next,
13192            window,
13193            cx,
13194        );
13195    }
13196
13197    pub fn go_to_hunk_before_or_after_position(
13198        &mut self,
13199        snapshot: &EditorSnapshot,
13200        position: Point,
13201        direction: Direction,
13202        window: &mut Window,
13203        cx: &mut Context<Editor>,
13204    ) {
13205        let row = if direction == Direction::Next {
13206            self.hunk_after_position(snapshot, position)
13207                .map(|hunk| hunk.row_range.start)
13208        } else {
13209            self.hunk_before_position(snapshot, position)
13210        };
13211
13212        if let Some(row) = row {
13213            let destination = Point::new(row.0, 0);
13214            let autoscroll = Autoscroll::center();
13215
13216            self.unfold_ranges(&[destination..destination], false, false, cx);
13217            self.change_selections(Some(autoscroll), window, cx, |s| {
13218                s.select_ranges([destination..destination]);
13219            });
13220        }
13221    }
13222
13223    fn hunk_after_position(
13224        &mut self,
13225        snapshot: &EditorSnapshot,
13226        position: Point,
13227    ) -> Option<MultiBufferDiffHunk> {
13228        snapshot
13229            .buffer_snapshot
13230            .diff_hunks_in_range(position..snapshot.buffer_snapshot.max_point())
13231            .find(|hunk| hunk.row_range.start.0 > position.row)
13232            .or_else(|| {
13233                snapshot
13234                    .buffer_snapshot
13235                    .diff_hunks_in_range(Point::zero()..position)
13236                    .find(|hunk| hunk.row_range.end.0 < position.row)
13237            })
13238    }
13239
13240    fn go_to_prev_hunk(
13241        &mut self,
13242        _: &GoToPreviousHunk,
13243        window: &mut Window,
13244        cx: &mut Context<Self>,
13245    ) {
13246        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
13247        let snapshot = self.snapshot(window, cx);
13248        let selection = self.selections.newest::<Point>(cx);
13249        self.go_to_hunk_before_or_after_position(
13250            &snapshot,
13251            selection.head(),
13252            Direction::Prev,
13253            window,
13254            cx,
13255        );
13256    }
13257
13258    fn hunk_before_position(
13259        &mut self,
13260        snapshot: &EditorSnapshot,
13261        position: Point,
13262    ) -> Option<MultiBufferRow> {
13263        snapshot
13264            .buffer_snapshot
13265            .diff_hunk_before(position)
13266            .or_else(|| snapshot.buffer_snapshot.diff_hunk_before(Point::MAX))
13267    }
13268
13269    fn go_to_line<T: 'static>(
13270        &mut self,
13271        position: Anchor,
13272        highlight_color: Option<Hsla>,
13273        window: &mut Window,
13274        cx: &mut Context<Self>,
13275    ) {
13276        let snapshot = self.snapshot(window, cx).display_snapshot;
13277        let position = position.to_point(&snapshot.buffer_snapshot);
13278        let start = snapshot
13279            .buffer_snapshot
13280            .clip_point(Point::new(position.row, 0), Bias::Left);
13281        let end = start + Point::new(1, 0);
13282        let start = snapshot.buffer_snapshot.anchor_before(start);
13283        let end = snapshot.buffer_snapshot.anchor_before(end);
13284
13285        self.highlight_rows::<T>(
13286            start..end,
13287            highlight_color
13288                .unwrap_or_else(|| cx.theme().colors().editor_highlighted_line_background),
13289            false,
13290            cx,
13291        );
13292        self.request_autoscroll(Autoscroll::center().for_anchor(start), cx);
13293    }
13294
13295    pub fn go_to_definition(
13296        &mut self,
13297        _: &GoToDefinition,
13298        window: &mut Window,
13299        cx: &mut Context<Self>,
13300    ) -> Task<Result<Navigated>> {
13301        let definition =
13302            self.go_to_definition_of_kind(GotoDefinitionKind::Symbol, false, window, cx);
13303        let fallback_strategy = EditorSettings::get_global(cx).go_to_definition_fallback;
13304        cx.spawn_in(window, async move |editor, cx| {
13305            if definition.await? == Navigated::Yes {
13306                return Ok(Navigated::Yes);
13307            }
13308            match fallback_strategy {
13309                GoToDefinitionFallback::None => Ok(Navigated::No),
13310                GoToDefinitionFallback::FindAllReferences => {
13311                    match editor.update_in(cx, |editor, window, cx| {
13312                        editor.find_all_references(&FindAllReferences, window, cx)
13313                    })? {
13314                        Some(references) => references.await,
13315                        None => Ok(Navigated::No),
13316                    }
13317                }
13318            }
13319        })
13320    }
13321
13322    pub fn go_to_declaration(
13323        &mut self,
13324        _: &GoToDeclaration,
13325        window: &mut Window,
13326        cx: &mut Context<Self>,
13327    ) -> Task<Result<Navigated>> {
13328        self.go_to_definition_of_kind(GotoDefinitionKind::Declaration, false, window, cx)
13329    }
13330
13331    pub fn go_to_declaration_split(
13332        &mut self,
13333        _: &GoToDeclaration,
13334        window: &mut Window,
13335        cx: &mut Context<Self>,
13336    ) -> Task<Result<Navigated>> {
13337        self.go_to_definition_of_kind(GotoDefinitionKind::Declaration, true, window, cx)
13338    }
13339
13340    pub fn go_to_implementation(
13341        &mut self,
13342        _: &GoToImplementation,
13343        window: &mut Window,
13344        cx: &mut Context<Self>,
13345    ) -> Task<Result<Navigated>> {
13346        self.go_to_definition_of_kind(GotoDefinitionKind::Implementation, false, window, cx)
13347    }
13348
13349    pub fn go_to_implementation_split(
13350        &mut self,
13351        _: &GoToImplementationSplit,
13352        window: &mut Window,
13353        cx: &mut Context<Self>,
13354    ) -> Task<Result<Navigated>> {
13355        self.go_to_definition_of_kind(GotoDefinitionKind::Implementation, true, window, cx)
13356    }
13357
13358    pub fn go_to_type_definition(
13359        &mut self,
13360        _: &GoToTypeDefinition,
13361        window: &mut Window,
13362        cx: &mut Context<Self>,
13363    ) -> Task<Result<Navigated>> {
13364        self.go_to_definition_of_kind(GotoDefinitionKind::Type, false, window, cx)
13365    }
13366
13367    pub fn go_to_definition_split(
13368        &mut self,
13369        _: &GoToDefinitionSplit,
13370        window: &mut Window,
13371        cx: &mut Context<Self>,
13372    ) -> Task<Result<Navigated>> {
13373        self.go_to_definition_of_kind(GotoDefinitionKind::Symbol, true, window, cx)
13374    }
13375
13376    pub fn go_to_type_definition_split(
13377        &mut self,
13378        _: &GoToTypeDefinitionSplit,
13379        window: &mut Window,
13380        cx: &mut Context<Self>,
13381    ) -> Task<Result<Navigated>> {
13382        self.go_to_definition_of_kind(GotoDefinitionKind::Type, true, window, cx)
13383    }
13384
13385    fn go_to_definition_of_kind(
13386        &mut self,
13387        kind: GotoDefinitionKind,
13388        split: bool,
13389        window: &mut Window,
13390        cx: &mut Context<Self>,
13391    ) -> Task<Result<Navigated>> {
13392        let Some(provider) = self.semantics_provider.clone() else {
13393            return Task::ready(Ok(Navigated::No));
13394        };
13395        let head = self.selections.newest::<usize>(cx).head();
13396        let buffer = self.buffer.read(cx);
13397        let (buffer, head) = if let Some(text_anchor) = buffer.text_anchor_for_position(head, cx) {
13398            text_anchor
13399        } else {
13400            return Task::ready(Ok(Navigated::No));
13401        };
13402
13403        let Some(definitions) = provider.definitions(&buffer, head, kind, cx) else {
13404            return Task::ready(Ok(Navigated::No));
13405        };
13406
13407        cx.spawn_in(window, async move |editor, cx| {
13408            let definitions = definitions.await?;
13409            let navigated = editor
13410                .update_in(cx, |editor, window, cx| {
13411                    editor.navigate_to_hover_links(
13412                        Some(kind),
13413                        definitions
13414                            .into_iter()
13415                            .filter(|location| {
13416                                hover_links::exclude_link_to_position(&buffer, &head, location, cx)
13417                            })
13418                            .map(HoverLink::Text)
13419                            .collect::<Vec<_>>(),
13420                        split,
13421                        window,
13422                        cx,
13423                    )
13424                })?
13425                .await?;
13426            anyhow::Ok(navigated)
13427        })
13428    }
13429
13430    pub fn open_url(&mut self, _: &OpenUrl, window: &mut Window, cx: &mut Context<Self>) {
13431        let selection = self.selections.newest_anchor();
13432        let head = selection.head();
13433        let tail = selection.tail();
13434
13435        let Some((buffer, start_position)) =
13436            self.buffer.read(cx).text_anchor_for_position(head, cx)
13437        else {
13438            return;
13439        };
13440
13441        let end_position = if head != tail {
13442            let Some((_, pos)) = self.buffer.read(cx).text_anchor_for_position(tail, cx) else {
13443                return;
13444            };
13445            Some(pos)
13446        } else {
13447            None
13448        };
13449
13450        let url_finder = cx.spawn_in(window, async move |editor, cx| {
13451            let url = if let Some(end_pos) = end_position {
13452                find_url_from_range(&buffer, start_position..end_pos, cx.clone())
13453            } else {
13454                find_url(&buffer, start_position, cx.clone()).map(|(_, url)| url)
13455            };
13456
13457            if let Some(url) = url {
13458                editor.update(cx, |_, cx| {
13459                    cx.open_url(&url);
13460                })
13461            } else {
13462                Ok(())
13463            }
13464        });
13465
13466        url_finder.detach();
13467    }
13468
13469    pub fn open_selected_filename(
13470        &mut self,
13471        _: &OpenSelectedFilename,
13472        window: &mut Window,
13473        cx: &mut Context<Self>,
13474    ) {
13475        let Some(workspace) = self.workspace() else {
13476            return;
13477        };
13478
13479        let position = self.selections.newest_anchor().head();
13480
13481        let Some((buffer, buffer_position)) =
13482            self.buffer.read(cx).text_anchor_for_position(position, cx)
13483        else {
13484            return;
13485        };
13486
13487        let project = self.project.clone();
13488
13489        cx.spawn_in(window, async move |_, cx| {
13490            let result = find_file(&buffer, project, buffer_position, cx).await;
13491
13492            if let Some((_, path)) = result {
13493                workspace
13494                    .update_in(cx, |workspace, window, cx| {
13495                        workspace.open_resolved_path(path, window, cx)
13496                    })?
13497                    .await?;
13498            }
13499            anyhow::Ok(())
13500        })
13501        .detach();
13502    }
13503
13504    pub(crate) fn navigate_to_hover_links(
13505        &mut self,
13506        kind: Option<GotoDefinitionKind>,
13507        mut definitions: Vec<HoverLink>,
13508        split: bool,
13509        window: &mut Window,
13510        cx: &mut Context<Editor>,
13511    ) -> Task<Result<Navigated>> {
13512        // If there is one definition, just open it directly
13513        if definitions.len() == 1 {
13514            let definition = definitions.pop().unwrap();
13515
13516            enum TargetTaskResult {
13517                Location(Option<Location>),
13518                AlreadyNavigated,
13519            }
13520
13521            let target_task = match definition {
13522                HoverLink::Text(link) => {
13523                    Task::ready(anyhow::Ok(TargetTaskResult::Location(Some(link.target))))
13524                }
13525                HoverLink::InlayHint(lsp_location, server_id) => {
13526                    let computation =
13527                        self.compute_target_location(lsp_location, server_id, window, cx);
13528                    cx.background_spawn(async move {
13529                        let location = computation.await?;
13530                        Ok(TargetTaskResult::Location(location))
13531                    })
13532                }
13533                HoverLink::Url(url) => {
13534                    cx.open_url(&url);
13535                    Task::ready(Ok(TargetTaskResult::AlreadyNavigated))
13536                }
13537                HoverLink::File(path) => {
13538                    if let Some(workspace) = self.workspace() {
13539                        cx.spawn_in(window, async move |_, cx| {
13540                            workspace
13541                                .update_in(cx, |workspace, window, cx| {
13542                                    workspace.open_resolved_path(path, window, cx)
13543                                })?
13544                                .await
13545                                .map(|_| TargetTaskResult::AlreadyNavigated)
13546                        })
13547                    } else {
13548                        Task::ready(Ok(TargetTaskResult::Location(None)))
13549                    }
13550                }
13551            };
13552            cx.spawn_in(window, async move |editor, cx| {
13553                let target = match target_task.await.context("target resolution task")? {
13554                    TargetTaskResult::AlreadyNavigated => return Ok(Navigated::Yes),
13555                    TargetTaskResult::Location(None) => return Ok(Navigated::No),
13556                    TargetTaskResult::Location(Some(target)) => target,
13557                };
13558
13559                editor.update_in(cx, |editor, window, cx| {
13560                    let Some(workspace) = editor.workspace() else {
13561                        return Navigated::No;
13562                    };
13563                    let pane = workspace.read(cx).active_pane().clone();
13564
13565                    let range = target.range.to_point(target.buffer.read(cx));
13566                    let range = editor.range_for_match(&range);
13567                    let range = collapse_multiline_range(range);
13568
13569                    if !split
13570                        && Some(&target.buffer) == editor.buffer.read(cx).as_singleton().as_ref()
13571                    {
13572                        editor.go_to_singleton_buffer_range(range.clone(), window, cx);
13573                    } else {
13574                        window.defer(cx, move |window, cx| {
13575                            let target_editor: Entity<Self> =
13576                                workspace.update(cx, |workspace, cx| {
13577                                    let pane = if split {
13578                                        workspace.adjacent_pane(window, cx)
13579                                    } else {
13580                                        workspace.active_pane().clone()
13581                                    };
13582
13583                                    workspace.open_project_item(
13584                                        pane,
13585                                        target.buffer.clone(),
13586                                        true,
13587                                        true,
13588                                        window,
13589                                        cx,
13590                                    )
13591                                });
13592                            target_editor.update(cx, |target_editor, cx| {
13593                                // When selecting a definition in a different buffer, disable the nav history
13594                                // to avoid creating a history entry at the previous cursor location.
13595                                pane.update(cx, |pane, _| pane.disable_history());
13596                                target_editor.go_to_singleton_buffer_range(range, window, cx);
13597                                pane.update(cx, |pane, _| pane.enable_history());
13598                            });
13599                        });
13600                    }
13601                    Navigated::Yes
13602                })
13603            })
13604        } else if !definitions.is_empty() {
13605            cx.spawn_in(window, async move |editor, cx| {
13606                let (title, location_tasks, workspace) = editor
13607                    .update_in(cx, |editor, window, cx| {
13608                        let tab_kind = match kind {
13609                            Some(GotoDefinitionKind::Implementation) => "Implementations",
13610                            _ => "Definitions",
13611                        };
13612                        let title = definitions
13613                            .iter()
13614                            .find_map(|definition| match definition {
13615                                HoverLink::Text(link) => link.origin.as_ref().map(|origin| {
13616                                    let buffer = origin.buffer.read(cx);
13617                                    format!(
13618                                        "{} for {}",
13619                                        tab_kind,
13620                                        buffer
13621                                            .text_for_range(origin.range.clone())
13622                                            .collect::<String>()
13623                                    )
13624                                }),
13625                                HoverLink::InlayHint(_, _) => None,
13626                                HoverLink::Url(_) => None,
13627                                HoverLink::File(_) => None,
13628                            })
13629                            .unwrap_or(tab_kind.to_string());
13630                        let location_tasks = definitions
13631                            .into_iter()
13632                            .map(|definition| match definition {
13633                                HoverLink::Text(link) => Task::ready(Ok(Some(link.target))),
13634                                HoverLink::InlayHint(lsp_location, server_id) => editor
13635                                    .compute_target_location(lsp_location, server_id, window, cx),
13636                                HoverLink::Url(_) => Task::ready(Ok(None)),
13637                                HoverLink::File(_) => Task::ready(Ok(None)),
13638                            })
13639                            .collect::<Vec<_>>();
13640                        (title, location_tasks, editor.workspace().clone())
13641                    })
13642                    .context("location tasks preparation")?;
13643
13644                let locations = future::join_all(location_tasks)
13645                    .await
13646                    .into_iter()
13647                    .filter_map(|location| location.transpose())
13648                    .collect::<Result<_>>()
13649                    .context("location tasks")?;
13650
13651                let Some(workspace) = workspace else {
13652                    return Ok(Navigated::No);
13653                };
13654                let opened = workspace
13655                    .update_in(cx, |workspace, window, cx| {
13656                        Self::open_locations_in_multibuffer(
13657                            workspace,
13658                            locations,
13659                            title,
13660                            split,
13661                            MultibufferSelectionMode::First,
13662                            window,
13663                            cx,
13664                        )
13665                    })
13666                    .ok();
13667
13668                anyhow::Ok(Navigated::from_bool(opened.is_some()))
13669            })
13670        } else {
13671            Task::ready(Ok(Navigated::No))
13672        }
13673    }
13674
13675    fn compute_target_location(
13676        &self,
13677        lsp_location: lsp::Location,
13678        server_id: LanguageServerId,
13679        window: &mut Window,
13680        cx: &mut Context<Self>,
13681    ) -> Task<anyhow::Result<Option<Location>>> {
13682        let Some(project) = self.project.clone() else {
13683            return Task::ready(Ok(None));
13684        };
13685
13686        cx.spawn_in(window, async move |editor, cx| {
13687            let location_task = editor.update(cx, |_, cx| {
13688                project.update(cx, |project, cx| {
13689                    let language_server_name = project
13690                        .language_server_statuses(cx)
13691                        .find(|(id, _)| server_id == *id)
13692                        .map(|(_, status)| LanguageServerName::from(status.name.as_str()));
13693                    language_server_name.map(|language_server_name| {
13694                        project.open_local_buffer_via_lsp(
13695                            lsp_location.uri.clone(),
13696                            server_id,
13697                            language_server_name,
13698                            cx,
13699                        )
13700                    })
13701                })
13702            })?;
13703            let location = match location_task {
13704                Some(task) => Some({
13705                    let target_buffer_handle = task.await.context("open local buffer")?;
13706                    let range = target_buffer_handle.update(cx, |target_buffer, _| {
13707                        let target_start = target_buffer
13708                            .clip_point_utf16(point_from_lsp(lsp_location.range.start), Bias::Left);
13709                        let target_end = target_buffer
13710                            .clip_point_utf16(point_from_lsp(lsp_location.range.end), Bias::Left);
13711                        target_buffer.anchor_after(target_start)
13712                            ..target_buffer.anchor_before(target_end)
13713                    })?;
13714                    Location {
13715                        buffer: target_buffer_handle,
13716                        range,
13717                    }
13718                }),
13719                None => None,
13720            };
13721            Ok(location)
13722        })
13723    }
13724
13725    pub fn find_all_references(
13726        &mut self,
13727        _: &FindAllReferences,
13728        window: &mut Window,
13729        cx: &mut Context<Self>,
13730    ) -> Option<Task<Result<Navigated>>> {
13731        let selection = self.selections.newest::<usize>(cx);
13732        let multi_buffer = self.buffer.read(cx);
13733        let head = selection.head();
13734
13735        let multi_buffer_snapshot = multi_buffer.snapshot(cx);
13736        let head_anchor = multi_buffer_snapshot.anchor_at(
13737            head,
13738            if head < selection.tail() {
13739                Bias::Right
13740            } else {
13741                Bias::Left
13742            },
13743        );
13744
13745        match self
13746            .find_all_references_task_sources
13747            .binary_search_by(|anchor| anchor.cmp(&head_anchor, &multi_buffer_snapshot))
13748        {
13749            Ok(_) => {
13750                log::info!(
13751                    "Ignoring repeated FindAllReferences invocation with the position of already running task"
13752                );
13753                return None;
13754            }
13755            Err(i) => {
13756                self.find_all_references_task_sources.insert(i, head_anchor);
13757            }
13758        }
13759
13760        let (buffer, head) = multi_buffer.text_anchor_for_position(head, cx)?;
13761        let workspace = self.workspace()?;
13762        let project = workspace.read(cx).project().clone();
13763        let references = project.update(cx, |project, cx| project.references(&buffer, head, cx));
13764        Some(cx.spawn_in(window, async move |editor, cx| {
13765            let _cleanup = cx.on_drop(&editor, move |editor, _| {
13766                if let Ok(i) = editor
13767                    .find_all_references_task_sources
13768                    .binary_search_by(|anchor| anchor.cmp(&head_anchor, &multi_buffer_snapshot))
13769                {
13770                    editor.find_all_references_task_sources.remove(i);
13771                }
13772            });
13773
13774            let locations = references.await?;
13775            if locations.is_empty() {
13776                return anyhow::Ok(Navigated::No);
13777            }
13778
13779            workspace.update_in(cx, |workspace, window, cx| {
13780                let title = locations
13781                    .first()
13782                    .as_ref()
13783                    .map(|location| {
13784                        let buffer = location.buffer.read(cx);
13785                        format!(
13786                            "References to `{}`",
13787                            buffer
13788                                .text_for_range(location.range.clone())
13789                                .collect::<String>()
13790                        )
13791                    })
13792                    .unwrap();
13793                Self::open_locations_in_multibuffer(
13794                    workspace,
13795                    locations,
13796                    title,
13797                    false,
13798                    MultibufferSelectionMode::First,
13799                    window,
13800                    cx,
13801                );
13802                Navigated::Yes
13803            })
13804        }))
13805    }
13806
13807    /// Opens a multibuffer with the given project locations in it
13808    pub fn open_locations_in_multibuffer(
13809        workspace: &mut Workspace,
13810        mut locations: Vec<Location>,
13811        title: String,
13812        split: bool,
13813        multibuffer_selection_mode: MultibufferSelectionMode,
13814        window: &mut Window,
13815        cx: &mut Context<Workspace>,
13816    ) {
13817        // If there are multiple definitions, open them in a multibuffer
13818        locations.sort_by_key(|location| location.buffer.read(cx).remote_id());
13819        let mut locations = locations.into_iter().peekable();
13820        let mut ranges: Vec<Range<Anchor>> = Vec::new();
13821        let capability = workspace.project().read(cx).capability();
13822
13823        let excerpt_buffer = cx.new(|cx| {
13824            let mut multibuffer = MultiBuffer::new(capability);
13825            while let Some(location) = locations.next() {
13826                let buffer = location.buffer.read(cx);
13827                let mut ranges_for_buffer = Vec::new();
13828                let range = location.range.to_point(buffer);
13829                ranges_for_buffer.push(range.clone());
13830
13831                while let Some(next_location) = locations.peek() {
13832                    if next_location.buffer == location.buffer {
13833                        ranges_for_buffer.push(next_location.range.to_point(buffer));
13834                        locations.next();
13835                    } else {
13836                        break;
13837                    }
13838                }
13839
13840                ranges_for_buffer.sort_by_key(|range| (range.start, Reverse(range.end)));
13841                let (new_ranges, _) = multibuffer.set_excerpts_for_path(
13842                    PathKey::for_buffer(&location.buffer, cx),
13843                    location.buffer.clone(),
13844                    ranges_for_buffer,
13845                    DEFAULT_MULTIBUFFER_CONTEXT,
13846                    cx,
13847                );
13848                ranges.extend(new_ranges)
13849            }
13850
13851            multibuffer.with_title(title)
13852        });
13853
13854        let editor = cx.new(|cx| {
13855            Editor::for_multibuffer(
13856                excerpt_buffer,
13857                Some(workspace.project().clone()),
13858                window,
13859                cx,
13860            )
13861        });
13862        editor.update(cx, |editor, cx| {
13863            match multibuffer_selection_mode {
13864                MultibufferSelectionMode::First => {
13865                    if let Some(first_range) = ranges.first() {
13866                        editor.change_selections(None, window, cx, |selections| {
13867                            selections.clear_disjoint();
13868                            selections.select_anchor_ranges(std::iter::once(first_range.clone()));
13869                        });
13870                    }
13871                    editor.highlight_background::<Self>(
13872                        &ranges,
13873                        |theme| theme.editor_highlighted_line_background,
13874                        cx,
13875                    );
13876                }
13877                MultibufferSelectionMode::All => {
13878                    editor.change_selections(None, window, cx, |selections| {
13879                        selections.clear_disjoint();
13880                        selections.select_anchor_ranges(ranges);
13881                    });
13882                }
13883            }
13884            editor.register_buffers_with_language_servers(cx);
13885        });
13886
13887        let item = Box::new(editor);
13888        let item_id = item.item_id();
13889
13890        if split {
13891            workspace.split_item(SplitDirection::Right, item.clone(), window, cx);
13892        } else {
13893            if PreviewTabsSettings::get_global(cx).enable_preview_from_code_navigation {
13894                let (preview_item_id, preview_item_idx) =
13895                    workspace.active_pane().update(cx, |pane, _| {
13896                        (pane.preview_item_id(), pane.preview_item_idx())
13897                    });
13898
13899                workspace.add_item_to_active_pane(item.clone(), preview_item_idx, true, window, cx);
13900
13901                if let Some(preview_item_id) = preview_item_id {
13902                    workspace.active_pane().update(cx, |pane, cx| {
13903                        pane.remove_item(preview_item_id, false, false, window, cx);
13904                    });
13905                }
13906            } else {
13907                workspace.add_item_to_active_pane(item.clone(), None, true, window, cx);
13908            }
13909        }
13910        workspace.active_pane().update(cx, |pane, cx| {
13911            pane.set_preview_item_id(Some(item_id), cx);
13912        });
13913    }
13914
13915    pub fn rename(
13916        &mut self,
13917        _: &Rename,
13918        window: &mut Window,
13919        cx: &mut Context<Self>,
13920    ) -> Option<Task<Result<()>>> {
13921        use language::ToOffset as _;
13922
13923        let provider = self.semantics_provider.clone()?;
13924        let selection = self.selections.newest_anchor().clone();
13925        let (cursor_buffer, cursor_buffer_position) = self
13926            .buffer
13927            .read(cx)
13928            .text_anchor_for_position(selection.head(), cx)?;
13929        let (tail_buffer, cursor_buffer_position_end) = self
13930            .buffer
13931            .read(cx)
13932            .text_anchor_for_position(selection.tail(), cx)?;
13933        if tail_buffer != cursor_buffer {
13934            return None;
13935        }
13936
13937        let snapshot = cursor_buffer.read(cx).snapshot();
13938        let cursor_buffer_offset = cursor_buffer_position.to_offset(&snapshot);
13939        let cursor_buffer_offset_end = cursor_buffer_position_end.to_offset(&snapshot);
13940        let prepare_rename = provider
13941            .range_for_rename(&cursor_buffer, cursor_buffer_position, cx)
13942            .unwrap_or_else(|| Task::ready(Ok(None)));
13943        drop(snapshot);
13944
13945        Some(cx.spawn_in(window, async move |this, cx| {
13946            let rename_range = if let Some(range) = prepare_rename.await? {
13947                Some(range)
13948            } else {
13949                this.update(cx, |this, cx| {
13950                    let buffer = this.buffer.read(cx).snapshot(cx);
13951                    let mut buffer_highlights = this
13952                        .document_highlights_for_position(selection.head(), &buffer)
13953                        .filter(|highlight| {
13954                            highlight.start.excerpt_id == selection.head().excerpt_id
13955                                && highlight.end.excerpt_id == selection.head().excerpt_id
13956                        });
13957                    buffer_highlights
13958                        .next()
13959                        .map(|highlight| highlight.start.text_anchor..highlight.end.text_anchor)
13960                })?
13961            };
13962            if let Some(rename_range) = rename_range {
13963                this.update_in(cx, |this, window, cx| {
13964                    let snapshot = cursor_buffer.read(cx).snapshot();
13965                    let rename_buffer_range = rename_range.to_offset(&snapshot);
13966                    let cursor_offset_in_rename_range =
13967                        cursor_buffer_offset.saturating_sub(rename_buffer_range.start);
13968                    let cursor_offset_in_rename_range_end =
13969                        cursor_buffer_offset_end.saturating_sub(rename_buffer_range.start);
13970
13971                    this.take_rename(false, window, cx);
13972                    let buffer = this.buffer.read(cx).read(cx);
13973                    let cursor_offset = selection.head().to_offset(&buffer);
13974                    let rename_start = cursor_offset.saturating_sub(cursor_offset_in_rename_range);
13975                    let rename_end = rename_start + rename_buffer_range.len();
13976                    let range = buffer.anchor_before(rename_start)..buffer.anchor_after(rename_end);
13977                    let mut old_highlight_id = None;
13978                    let old_name: Arc<str> = buffer
13979                        .chunks(rename_start..rename_end, true)
13980                        .map(|chunk| {
13981                            if old_highlight_id.is_none() {
13982                                old_highlight_id = chunk.syntax_highlight_id;
13983                            }
13984                            chunk.text
13985                        })
13986                        .collect::<String>()
13987                        .into();
13988
13989                    drop(buffer);
13990
13991                    // Position the selection in the rename editor so that it matches the current selection.
13992                    this.show_local_selections = false;
13993                    let rename_editor = cx.new(|cx| {
13994                        let mut editor = Editor::single_line(window, cx);
13995                        editor.buffer.update(cx, |buffer, cx| {
13996                            buffer.edit([(0..0, old_name.clone())], None, cx)
13997                        });
13998                        let rename_selection_range = match cursor_offset_in_rename_range
13999                            .cmp(&cursor_offset_in_rename_range_end)
14000                        {
14001                            Ordering::Equal => {
14002                                editor.select_all(&SelectAll, window, cx);
14003                                return editor;
14004                            }
14005                            Ordering::Less => {
14006                                cursor_offset_in_rename_range..cursor_offset_in_rename_range_end
14007                            }
14008                            Ordering::Greater => {
14009                                cursor_offset_in_rename_range_end..cursor_offset_in_rename_range
14010                            }
14011                        };
14012                        if rename_selection_range.end > old_name.len() {
14013                            editor.select_all(&SelectAll, window, cx);
14014                        } else {
14015                            editor.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
14016                                s.select_ranges([rename_selection_range]);
14017                            });
14018                        }
14019                        editor
14020                    });
14021                    cx.subscribe(&rename_editor, |_, _, e: &EditorEvent, cx| {
14022                        if e == &EditorEvent::Focused {
14023                            cx.emit(EditorEvent::FocusedIn)
14024                        }
14025                    })
14026                    .detach();
14027
14028                    let write_highlights =
14029                        this.clear_background_highlights::<DocumentHighlightWrite>(cx);
14030                    let read_highlights =
14031                        this.clear_background_highlights::<DocumentHighlightRead>(cx);
14032                    let ranges = write_highlights
14033                        .iter()
14034                        .flat_map(|(_, ranges)| ranges.iter())
14035                        .chain(read_highlights.iter().flat_map(|(_, ranges)| ranges.iter()))
14036                        .cloned()
14037                        .collect();
14038
14039                    this.highlight_text::<Rename>(
14040                        ranges,
14041                        HighlightStyle {
14042                            fade_out: Some(0.6),
14043                            ..Default::default()
14044                        },
14045                        cx,
14046                    );
14047                    let rename_focus_handle = rename_editor.focus_handle(cx);
14048                    window.focus(&rename_focus_handle);
14049                    let block_id = this.insert_blocks(
14050                        [BlockProperties {
14051                            style: BlockStyle::Flex,
14052                            placement: BlockPlacement::Below(range.start),
14053                            height: Some(1),
14054                            render: Arc::new({
14055                                let rename_editor = rename_editor.clone();
14056                                move |cx: &mut BlockContext| {
14057                                    let mut text_style = cx.editor_style.text.clone();
14058                                    if let Some(highlight_style) = old_highlight_id
14059                                        .and_then(|h| h.style(&cx.editor_style.syntax))
14060                                    {
14061                                        text_style = text_style.highlight(highlight_style);
14062                                    }
14063                                    div()
14064                                        .block_mouse_down()
14065                                        .pl(cx.anchor_x)
14066                                        .child(EditorElement::new(
14067                                            &rename_editor,
14068                                            EditorStyle {
14069                                                background: cx.theme().system().transparent,
14070                                                local_player: cx.editor_style.local_player,
14071                                                text: text_style,
14072                                                scrollbar_width: cx.editor_style.scrollbar_width,
14073                                                syntax: cx.editor_style.syntax.clone(),
14074                                                status: cx.editor_style.status.clone(),
14075                                                inlay_hints_style: HighlightStyle {
14076                                                    font_weight: Some(FontWeight::BOLD),
14077                                                    ..make_inlay_hints_style(cx.app)
14078                                                },
14079                                                inline_completion_styles: make_suggestion_styles(
14080                                                    cx.app,
14081                                                ),
14082                                                ..EditorStyle::default()
14083                                            },
14084                                        ))
14085                                        .into_any_element()
14086                                }
14087                            }),
14088                            priority: 0,
14089                        }],
14090                        Some(Autoscroll::fit()),
14091                        cx,
14092                    )[0];
14093                    this.pending_rename = Some(RenameState {
14094                        range,
14095                        old_name,
14096                        editor: rename_editor,
14097                        block_id,
14098                    });
14099                })?;
14100            }
14101
14102            Ok(())
14103        }))
14104    }
14105
14106    pub fn confirm_rename(
14107        &mut self,
14108        _: &ConfirmRename,
14109        window: &mut Window,
14110        cx: &mut Context<Self>,
14111    ) -> Option<Task<Result<()>>> {
14112        let rename = self.take_rename(false, window, cx)?;
14113        let workspace = self.workspace()?.downgrade();
14114        let (buffer, start) = self
14115            .buffer
14116            .read(cx)
14117            .text_anchor_for_position(rename.range.start, cx)?;
14118        let (end_buffer, _) = self
14119            .buffer
14120            .read(cx)
14121            .text_anchor_for_position(rename.range.end, cx)?;
14122        if buffer != end_buffer {
14123            return None;
14124        }
14125
14126        let old_name = rename.old_name;
14127        let new_name = rename.editor.read(cx).text(cx);
14128
14129        let rename = self.semantics_provider.as_ref()?.perform_rename(
14130            &buffer,
14131            start,
14132            new_name.clone(),
14133            cx,
14134        )?;
14135
14136        Some(cx.spawn_in(window, async move |editor, cx| {
14137            let project_transaction = rename.await?;
14138            Self::open_project_transaction(
14139                &editor,
14140                workspace,
14141                project_transaction,
14142                format!("Rename: {}{}", old_name, new_name),
14143                cx,
14144            )
14145            .await?;
14146
14147            editor.update(cx, |editor, cx| {
14148                editor.refresh_document_highlights(cx);
14149            })?;
14150            Ok(())
14151        }))
14152    }
14153
14154    fn take_rename(
14155        &mut self,
14156        moving_cursor: bool,
14157        window: &mut Window,
14158        cx: &mut Context<Self>,
14159    ) -> Option<RenameState> {
14160        let rename = self.pending_rename.take()?;
14161        if rename.editor.focus_handle(cx).is_focused(window) {
14162            window.focus(&self.focus_handle);
14163        }
14164
14165        self.remove_blocks(
14166            [rename.block_id].into_iter().collect(),
14167            Some(Autoscroll::fit()),
14168            cx,
14169        );
14170        self.clear_highlights::<Rename>(cx);
14171        self.show_local_selections = true;
14172
14173        if moving_cursor {
14174            let cursor_in_rename_editor = rename.editor.update(cx, |editor, cx| {
14175                editor.selections.newest::<usize>(cx).head()
14176            });
14177
14178            // Update the selection to match the position of the selection inside
14179            // the rename editor.
14180            let snapshot = self.buffer.read(cx).read(cx);
14181            let rename_range = rename.range.to_offset(&snapshot);
14182            let cursor_in_editor = snapshot
14183                .clip_offset(rename_range.start + cursor_in_rename_editor, Bias::Left)
14184                .min(rename_range.end);
14185            drop(snapshot);
14186
14187            self.change_selections(None, window, cx, |s| {
14188                s.select_ranges(vec![cursor_in_editor..cursor_in_editor])
14189            });
14190        } else {
14191            self.refresh_document_highlights(cx);
14192        }
14193
14194        Some(rename)
14195    }
14196
14197    pub fn pending_rename(&self) -> Option<&RenameState> {
14198        self.pending_rename.as_ref()
14199    }
14200
14201    fn format(
14202        &mut self,
14203        _: &Format,
14204        window: &mut Window,
14205        cx: &mut Context<Self>,
14206    ) -> Option<Task<Result<()>>> {
14207        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
14208
14209        let project = match &self.project {
14210            Some(project) => project.clone(),
14211            None => return None,
14212        };
14213
14214        Some(self.perform_format(
14215            project,
14216            FormatTrigger::Manual,
14217            FormatTarget::Buffers,
14218            window,
14219            cx,
14220        ))
14221    }
14222
14223    fn format_selections(
14224        &mut self,
14225        _: &FormatSelections,
14226        window: &mut Window,
14227        cx: &mut Context<Self>,
14228    ) -> Option<Task<Result<()>>> {
14229        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
14230
14231        let project = match &self.project {
14232            Some(project) => project.clone(),
14233            None => return None,
14234        };
14235
14236        let ranges = self
14237            .selections
14238            .all_adjusted(cx)
14239            .into_iter()
14240            .map(|selection| selection.range())
14241            .collect_vec();
14242
14243        Some(self.perform_format(
14244            project,
14245            FormatTrigger::Manual,
14246            FormatTarget::Ranges(ranges),
14247            window,
14248            cx,
14249        ))
14250    }
14251
14252    fn perform_format(
14253        &mut self,
14254        project: Entity<Project>,
14255        trigger: FormatTrigger,
14256        target: FormatTarget,
14257        window: &mut Window,
14258        cx: &mut Context<Self>,
14259    ) -> Task<Result<()>> {
14260        let buffer = self.buffer.clone();
14261        let (buffers, target) = match target {
14262            FormatTarget::Buffers => {
14263                let mut buffers = buffer.read(cx).all_buffers();
14264                if trigger == FormatTrigger::Save {
14265                    buffers.retain(|buffer| buffer.read(cx).is_dirty());
14266                }
14267                (buffers, LspFormatTarget::Buffers)
14268            }
14269            FormatTarget::Ranges(selection_ranges) => {
14270                let multi_buffer = buffer.read(cx);
14271                let snapshot = multi_buffer.read(cx);
14272                let mut buffers = HashSet::default();
14273                let mut buffer_id_to_ranges: BTreeMap<BufferId, Vec<Range<text::Anchor>>> =
14274                    BTreeMap::new();
14275                for selection_range in selection_ranges {
14276                    for (buffer, buffer_range, _) in
14277                        snapshot.range_to_buffer_ranges(selection_range)
14278                    {
14279                        let buffer_id = buffer.remote_id();
14280                        let start = buffer.anchor_before(buffer_range.start);
14281                        let end = buffer.anchor_after(buffer_range.end);
14282                        buffers.insert(multi_buffer.buffer(buffer_id).unwrap());
14283                        buffer_id_to_ranges
14284                            .entry(buffer_id)
14285                            .and_modify(|buffer_ranges| buffer_ranges.push(start..end))
14286                            .or_insert_with(|| vec![start..end]);
14287                    }
14288                }
14289                (buffers, LspFormatTarget::Ranges(buffer_id_to_ranges))
14290            }
14291        };
14292
14293        let transaction_id_prev = buffer.read_with(cx, |b, cx| b.last_transaction_id(cx));
14294        let selections_prev = transaction_id_prev
14295            .and_then(|transaction_id_prev| {
14296                // default to selections as they were after the last edit, if we have them,
14297                // instead of how they are now.
14298                // This will make it so that editing, moving somewhere else, formatting, then undoing the format
14299                // will take you back to where you made the last edit, instead of staying where you scrolled
14300                self.selection_history
14301                    .transaction(transaction_id_prev)
14302                    .map(|t| t.0.clone())
14303            })
14304            .unwrap_or_else(|| {
14305                log::info!("Failed to determine selections from before format. Falling back to selections when format was initiated");
14306                self.selections.disjoint_anchors()
14307            });
14308
14309        let mut timeout = cx.background_executor().timer(FORMAT_TIMEOUT).fuse();
14310        let format = project.update(cx, |project, cx| {
14311            project.format(buffers, target, true, trigger, cx)
14312        });
14313
14314        cx.spawn_in(window, async move |editor, cx| {
14315            let transaction = futures::select_biased! {
14316                transaction = format.log_err().fuse() => transaction,
14317                () = timeout => {
14318                    log::warn!("timed out waiting for formatting");
14319                    None
14320                }
14321            };
14322
14323            buffer
14324                .update(cx, |buffer, cx| {
14325                    if let Some(transaction) = transaction {
14326                        if !buffer.is_singleton() {
14327                            buffer.push_transaction(&transaction.0, cx);
14328                        }
14329                    }
14330                    cx.notify();
14331                })
14332                .ok();
14333
14334            if let Some(transaction_id_now) =
14335                buffer.read_with(cx, |b, cx| b.last_transaction_id(cx))?
14336            {
14337                let has_new_transaction = transaction_id_prev != Some(transaction_id_now);
14338                if has_new_transaction {
14339                    _ = editor.update(cx, |editor, _| {
14340                        editor
14341                            .selection_history
14342                            .insert_transaction(transaction_id_now, selections_prev);
14343                    });
14344                }
14345            }
14346
14347            Ok(())
14348        })
14349    }
14350
14351    fn organize_imports(
14352        &mut self,
14353        _: &OrganizeImports,
14354        window: &mut Window,
14355        cx: &mut Context<Self>,
14356    ) -> Option<Task<Result<()>>> {
14357        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
14358        let project = match &self.project {
14359            Some(project) => project.clone(),
14360            None => return None,
14361        };
14362        Some(self.perform_code_action_kind(
14363            project,
14364            CodeActionKind::SOURCE_ORGANIZE_IMPORTS,
14365            window,
14366            cx,
14367        ))
14368    }
14369
14370    fn perform_code_action_kind(
14371        &mut self,
14372        project: Entity<Project>,
14373        kind: CodeActionKind,
14374        window: &mut Window,
14375        cx: &mut Context<Self>,
14376    ) -> Task<Result<()>> {
14377        let buffer = self.buffer.clone();
14378        let buffers = buffer.read(cx).all_buffers();
14379        let mut timeout = cx.background_executor().timer(CODE_ACTION_TIMEOUT).fuse();
14380        let apply_action = project.update(cx, |project, cx| {
14381            project.apply_code_action_kind(buffers, kind, true, cx)
14382        });
14383        cx.spawn_in(window, async move |_, cx| {
14384            let transaction = futures::select_biased! {
14385                () = timeout => {
14386                    log::warn!("timed out waiting for executing code action");
14387                    None
14388                }
14389                transaction = apply_action.log_err().fuse() => transaction,
14390            };
14391            buffer
14392                .update(cx, |buffer, cx| {
14393                    // check if we need this
14394                    if let Some(transaction) = transaction {
14395                        if !buffer.is_singleton() {
14396                            buffer.push_transaction(&transaction.0, cx);
14397                        }
14398                    }
14399                    cx.notify();
14400                })
14401                .ok();
14402            Ok(())
14403        })
14404    }
14405
14406    fn restart_language_server(
14407        &mut self,
14408        _: &RestartLanguageServer,
14409        _: &mut Window,
14410        cx: &mut Context<Self>,
14411    ) {
14412        if let Some(project) = self.project.clone() {
14413            self.buffer.update(cx, |multi_buffer, cx| {
14414                project.update(cx, |project, cx| {
14415                    project.restart_language_servers_for_buffers(
14416                        multi_buffer.all_buffers().into_iter().collect(),
14417                        cx,
14418                    );
14419                });
14420            })
14421        }
14422    }
14423
14424    fn stop_language_server(
14425        &mut self,
14426        _: &StopLanguageServer,
14427        _: &mut Window,
14428        cx: &mut Context<Self>,
14429    ) {
14430        if let Some(project) = self.project.clone() {
14431            self.buffer.update(cx, |multi_buffer, cx| {
14432                project.update(cx, |project, cx| {
14433                    project.stop_language_servers_for_buffers(
14434                        multi_buffer.all_buffers().into_iter().collect(),
14435                        cx,
14436                    );
14437                    cx.emit(project::Event::RefreshInlayHints);
14438                });
14439            });
14440        }
14441    }
14442
14443    fn cancel_language_server_work(
14444        workspace: &mut Workspace,
14445        _: &actions::CancelLanguageServerWork,
14446        _: &mut Window,
14447        cx: &mut Context<Workspace>,
14448    ) {
14449        let project = workspace.project();
14450        let buffers = workspace
14451            .active_item(cx)
14452            .and_then(|item| item.act_as::<Editor>(cx))
14453            .map_or(HashSet::default(), |editor| {
14454                editor.read(cx).buffer.read(cx).all_buffers()
14455            });
14456        project.update(cx, |project, cx| {
14457            project.cancel_language_server_work_for_buffers(buffers, cx);
14458        });
14459    }
14460
14461    fn show_character_palette(
14462        &mut self,
14463        _: &ShowCharacterPalette,
14464        window: &mut Window,
14465        _: &mut Context<Self>,
14466    ) {
14467        window.show_character_palette();
14468    }
14469
14470    fn refresh_active_diagnostics(&mut self, cx: &mut Context<Editor>) {
14471        if let ActiveDiagnostic::Group(active_diagnostics) = &mut self.active_diagnostics {
14472            let buffer = self.buffer.read(cx).snapshot(cx);
14473            let primary_range_start = active_diagnostics.active_range.start.to_offset(&buffer);
14474            let primary_range_end = active_diagnostics.active_range.end.to_offset(&buffer);
14475            let is_valid = buffer
14476                .diagnostics_in_range::<usize>(primary_range_start..primary_range_end)
14477                .any(|entry| {
14478                    entry.diagnostic.is_primary
14479                        && !entry.range.is_empty()
14480                        && entry.range.start == primary_range_start
14481                        && entry.diagnostic.message == active_diagnostics.active_message
14482                });
14483
14484            if !is_valid {
14485                self.dismiss_diagnostics(cx);
14486            }
14487        }
14488    }
14489
14490    pub fn active_diagnostic_group(&self) -> Option<&ActiveDiagnosticGroup> {
14491        match &self.active_diagnostics {
14492            ActiveDiagnostic::Group(group) => Some(group),
14493            _ => None,
14494        }
14495    }
14496
14497    pub fn set_all_diagnostics_active(&mut self, cx: &mut Context<Self>) {
14498        self.dismiss_diagnostics(cx);
14499        self.active_diagnostics = ActiveDiagnostic::All;
14500    }
14501
14502    fn activate_diagnostics(
14503        &mut self,
14504        buffer_id: BufferId,
14505        diagnostic: DiagnosticEntry<usize>,
14506        window: &mut Window,
14507        cx: &mut Context<Self>,
14508    ) {
14509        if matches!(self.active_diagnostics, ActiveDiagnostic::All) {
14510            return;
14511        }
14512        self.dismiss_diagnostics(cx);
14513        let snapshot = self.snapshot(window, cx);
14514        let Some(diagnostic_renderer) = cx
14515            .try_global::<GlobalDiagnosticRenderer>()
14516            .map(|g| g.0.clone())
14517        else {
14518            return;
14519        };
14520        let buffer = self.buffer.read(cx).snapshot(cx);
14521
14522        let diagnostic_group = buffer
14523            .diagnostic_group(buffer_id, diagnostic.diagnostic.group_id)
14524            .collect::<Vec<_>>();
14525
14526        let blocks = diagnostic_renderer.render_group(
14527            diagnostic_group,
14528            buffer_id,
14529            snapshot,
14530            cx.weak_entity(),
14531            cx,
14532        );
14533
14534        let blocks = self.display_map.update(cx, |display_map, cx| {
14535            display_map.insert_blocks(blocks, cx).into_iter().collect()
14536        });
14537        self.active_diagnostics = ActiveDiagnostic::Group(ActiveDiagnosticGroup {
14538            active_range: buffer.anchor_before(diagnostic.range.start)
14539                ..buffer.anchor_after(diagnostic.range.end),
14540            active_message: diagnostic.diagnostic.message.clone(),
14541            group_id: diagnostic.diagnostic.group_id,
14542            blocks,
14543        });
14544        cx.notify();
14545    }
14546
14547    fn dismiss_diagnostics(&mut self, cx: &mut Context<Self>) {
14548        if matches!(self.active_diagnostics, ActiveDiagnostic::All) {
14549            return;
14550        };
14551
14552        let prev = mem::replace(&mut self.active_diagnostics, ActiveDiagnostic::None);
14553        if let ActiveDiagnostic::Group(group) = prev {
14554            self.display_map.update(cx, |display_map, cx| {
14555                display_map.remove_blocks(group.blocks, cx);
14556            });
14557            cx.notify();
14558        }
14559    }
14560
14561    /// Disable inline diagnostics rendering for this editor.
14562    pub fn disable_inline_diagnostics(&mut self) {
14563        self.inline_diagnostics_enabled = false;
14564        self.inline_diagnostics_update = Task::ready(());
14565        self.inline_diagnostics.clear();
14566    }
14567
14568    pub fn inline_diagnostics_enabled(&self) -> bool {
14569        self.inline_diagnostics_enabled
14570    }
14571
14572    pub fn show_inline_diagnostics(&self) -> bool {
14573        self.show_inline_diagnostics
14574    }
14575
14576    pub fn toggle_inline_diagnostics(
14577        &mut self,
14578        _: &ToggleInlineDiagnostics,
14579        window: &mut Window,
14580        cx: &mut Context<Editor>,
14581    ) {
14582        self.show_inline_diagnostics = !self.show_inline_diagnostics;
14583        self.refresh_inline_diagnostics(false, window, cx);
14584    }
14585
14586    fn refresh_inline_diagnostics(
14587        &mut self,
14588        debounce: bool,
14589        window: &mut Window,
14590        cx: &mut Context<Self>,
14591    ) {
14592        if !self.inline_diagnostics_enabled || !self.show_inline_diagnostics {
14593            self.inline_diagnostics_update = Task::ready(());
14594            self.inline_diagnostics.clear();
14595            return;
14596        }
14597
14598        let debounce_ms = ProjectSettings::get_global(cx)
14599            .diagnostics
14600            .inline
14601            .update_debounce_ms;
14602        let debounce = if debounce && debounce_ms > 0 {
14603            Some(Duration::from_millis(debounce_ms))
14604        } else {
14605            None
14606        };
14607        self.inline_diagnostics_update = cx.spawn_in(window, async move |editor, cx| {
14608            let editor = editor.upgrade().unwrap();
14609
14610            if let Some(debounce) = debounce {
14611                cx.background_executor().timer(debounce).await;
14612            }
14613            let Some(snapshot) = editor
14614                .update(cx, |editor, cx| editor.buffer().read(cx).snapshot(cx))
14615                .ok()
14616            else {
14617                return;
14618            };
14619
14620            let new_inline_diagnostics = cx
14621                .background_spawn(async move {
14622                    let mut inline_diagnostics = Vec::<(Anchor, InlineDiagnostic)>::new();
14623                    for diagnostic_entry in snapshot.diagnostics_in_range(0..snapshot.len()) {
14624                        let message = diagnostic_entry
14625                            .diagnostic
14626                            .message
14627                            .split_once('\n')
14628                            .map(|(line, _)| line)
14629                            .map(SharedString::new)
14630                            .unwrap_or_else(|| {
14631                                SharedString::from(diagnostic_entry.diagnostic.message)
14632                            });
14633                        let start_anchor = snapshot.anchor_before(diagnostic_entry.range.start);
14634                        let (Ok(i) | Err(i)) = inline_diagnostics
14635                            .binary_search_by(|(probe, _)| probe.cmp(&start_anchor, &snapshot));
14636                        inline_diagnostics.insert(
14637                            i,
14638                            (
14639                                start_anchor,
14640                                InlineDiagnostic {
14641                                    message,
14642                                    group_id: diagnostic_entry.diagnostic.group_id,
14643                                    start: diagnostic_entry.range.start.to_point(&snapshot),
14644                                    is_primary: diagnostic_entry.diagnostic.is_primary,
14645                                    severity: diagnostic_entry.diagnostic.severity,
14646                                },
14647                            ),
14648                        );
14649                    }
14650                    inline_diagnostics
14651                })
14652                .await;
14653
14654            editor
14655                .update(cx, |editor, cx| {
14656                    editor.inline_diagnostics = new_inline_diagnostics;
14657                    cx.notify();
14658                })
14659                .ok();
14660        });
14661    }
14662
14663    pub fn set_selections_from_remote(
14664        &mut self,
14665        selections: Vec<Selection<Anchor>>,
14666        pending_selection: Option<Selection<Anchor>>,
14667        window: &mut Window,
14668        cx: &mut Context<Self>,
14669    ) {
14670        let old_cursor_position = self.selections.newest_anchor().head();
14671        self.selections.change_with(cx, |s| {
14672            s.select_anchors(selections);
14673            if let Some(pending_selection) = pending_selection {
14674                s.set_pending(pending_selection, SelectMode::Character);
14675            } else {
14676                s.clear_pending();
14677            }
14678        });
14679        self.selections_did_change(false, &old_cursor_position, true, window, cx);
14680    }
14681
14682    fn push_to_selection_history(&mut self) {
14683        self.selection_history.push(SelectionHistoryEntry {
14684            selections: self.selections.disjoint_anchors(),
14685            select_next_state: self.select_next_state.clone(),
14686            select_prev_state: self.select_prev_state.clone(),
14687            add_selections_state: self.add_selections_state.clone(),
14688        });
14689    }
14690
14691    pub fn transact(
14692        &mut self,
14693        window: &mut Window,
14694        cx: &mut Context<Self>,
14695        update: impl FnOnce(&mut Self, &mut Window, &mut Context<Self>),
14696    ) -> Option<TransactionId> {
14697        self.start_transaction_at(Instant::now(), window, cx);
14698        update(self, window, cx);
14699        self.end_transaction_at(Instant::now(), cx)
14700    }
14701
14702    pub fn start_transaction_at(
14703        &mut self,
14704        now: Instant,
14705        window: &mut Window,
14706        cx: &mut Context<Self>,
14707    ) {
14708        self.end_selection(window, cx);
14709        if let Some(tx_id) = self
14710            .buffer
14711            .update(cx, |buffer, cx| buffer.start_transaction_at(now, cx))
14712        {
14713            self.selection_history
14714                .insert_transaction(tx_id, self.selections.disjoint_anchors());
14715            cx.emit(EditorEvent::TransactionBegun {
14716                transaction_id: tx_id,
14717            })
14718        }
14719    }
14720
14721    pub fn end_transaction_at(
14722        &mut self,
14723        now: Instant,
14724        cx: &mut Context<Self>,
14725    ) -> Option<TransactionId> {
14726        if let Some(transaction_id) = self
14727            .buffer
14728            .update(cx, |buffer, cx| buffer.end_transaction_at(now, cx))
14729        {
14730            if let Some((_, end_selections)) =
14731                self.selection_history.transaction_mut(transaction_id)
14732            {
14733                *end_selections = Some(self.selections.disjoint_anchors());
14734            } else {
14735                log::error!("unexpectedly ended a transaction that wasn't started by this editor");
14736            }
14737
14738            cx.emit(EditorEvent::Edited { transaction_id });
14739            Some(transaction_id)
14740        } else {
14741            None
14742        }
14743    }
14744
14745    pub fn set_mark(&mut self, _: &actions::SetMark, window: &mut Window, cx: &mut Context<Self>) {
14746        if self.selection_mark_mode {
14747            self.change_selections(None, window, cx, |s| {
14748                s.move_with(|_, sel| {
14749                    sel.collapse_to(sel.head(), SelectionGoal::None);
14750                });
14751            })
14752        }
14753        self.selection_mark_mode = true;
14754        cx.notify();
14755    }
14756
14757    pub fn swap_selection_ends(
14758        &mut self,
14759        _: &actions::SwapSelectionEnds,
14760        window: &mut Window,
14761        cx: &mut Context<Self>,
14762    ) {
14763        self.change_selections(None, window, cx, |s| {
14764            s.move_with(|_, sel| {
14765                if sel.start != sel.end {
14766                    sel.reversed = !sel.reversed
14767                }
14768            });
14769        });
14770        self.request_autoscroll(Autoscroll::newest(), cx);
14771        cx.notify();
14772    }
14773
14774    pub fn toggle_fold(
14775        &mut self,
14776        _: &actions::ToggleFold,
14777        window: &mut Window,
14778        cx: &mut Context<Self>,
14779    ) {
14780        if self.is_singleton(cx) {
14781            let selection = self.selections.newest::<Point>(cx);
14782
14783            let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
14784            let range = if selection.is_empty() {
14785                let point = selection.head().to_display_point(&display_map);
14786                let start = DisplayPoint::new(point.row(), 0).to_point(&display_map);
14787                let end = DisplayPoint::new(point.row(), display_map.line_len(point.row()))
14788                    .to_point(&display_map);
14789                start..end
14790            } else {
14791                selection.range()
14792            };
14793            if display_map.folds_in_range(range).next().is_some() {
14794                self.unfold_lines(&Default::default(), window, cx)
14795            } else {
14796                self.fold(&Default::default(), window, cx)
14797            }
14798        } else {
14799            let multi_buffer_snapshot = self.buffer.read(cx).snapshot(cx);
14800            let buffer_ids: HashSet<_> = self
14801                .selections
14802                .disjoint_anchor_ranges()
14803                .flat_map(|range| multi_buffer_snapshot.buffer_ids_for_range(range))
14804                .collect();
14805
14806            let should_unfold = buffer_ids
14807                .iter()
14808                .any(|buffer_id| self.is_buffer_folded(*buffer_id, cx));
14809
14810            for buffer_id in buffer_ids {
14811                if should_unfold {
14812                    self.unfold_buffer(buffer_id, cx);
14813                } else {
14814                    self.fold_buffer(buffer_id, cx);
14815                }
14816            }
14817        }
14818    }
14819
14820    pub fn toggle_fold_recursive(
14821        &mut self,
14822        _: &actions::ToggleFoldRecursive,
14823        window: &mut Window,
14824        cx: &mut Context<Self>,
14825    ) {
14826        let selection = self.selections.newest::<Point>(cx);
14827
14828        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
14829        let range = if selection.is_empty() {
14830            let point = selection.head().to_display_point(&display_map);
14831            let start = DisplayPoint::new(point.row(), 0).to_point(&display_map);
14832            let end = DisplayPoint::new(point.row(), display_map.line_len(point.row()))
14833                .to_point(&display_map);
14834            start..end
14835        } else {
14836            selection.range()
14837        };
14838        if display_map.folds_in_range(range).next().is_some() {
14839            self.unfold_recursive(&Default::default(), window, cx)
14840        } else {
14841            self.fold_recursive(&Default::default(), window, cx)
14842        }
14843    }
14844
14845    pub fn fold(&mut self, _: &actions::Fold, window: &mut Window, cx: &mut Context<Self>) {
14846        if self.is_singleton(cx) {
14847            let mut to_fold = Vec::new();
14848            let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
14849            let selections = self.selections.all_adjusted(cx);
14850
14851            for selection in selections {
14852                let range = selection.range().sorted();
14853                let buffer_start_row = range.start.row;
14854
14855                if range.start.row != range.end.row {
14856                    let mut found = false;
14857                    let mut row = range.start.row;
14858                    while row <= range.end.row {
14859                        if let Some(crease) = display_map.crease_for_buffer_row(MultiBufferRow(row))
14860                        {
14861                            found = true;
14862                            row = crease.range().end.row + 1;
14863                            to_fold.push(crease);
14864                        } else {
14865                            row += 1
14866                        }
14867                    }
14868                    if found {
14869                        continue;
14870                    }
14871                }
14872
14873                for row in (0..=range.start.row).rev() {
14874                    if let Some(crease) = display_map.crease_for_buffer_row(MultiBufferRow(row)) {
14875                        if crease.range().end.row >= buffer_start_row {
14876                            to_fold.push(crease);
14877                            if row <= range.start.row {
14878                                break;
14879                            }
14880                        }
14881                    }
14882                }
14883            }
14884
14885            self.fold_creases(to_fold, true, window, cx);
14886        } else {
14887            let multi_buffer_snapshot = self.buffer.read(cx).snapshot(cx);
14888            let buffer_ids = self
14889                .selections
14890                .disjoint_anchor_ranges()
14891                .flat_map(|range| multi_buffer_snapshot.buffer_ids_for_range(range))
14892                .collect::<HashSet<_>>();
14893            for buffer_id in buffer_ids {
14894                self.fold_buffer(buffer_id, cx);
14895            }
14896        }
14897    }
14898
14899    fn fold_at_level(
14900        &mut self,
14901        fold_at: &FoldAtLevel,
14902        window: &mut Window,
14903        cx: &mut Context<Self>,
14904    ) {
14905        if !self.buffer.read(cx).is_singleton() {
14906            return;
14907        }
14908
14909        let fold_at_level = fold_at.0;
14910        let snapshot = self.buffer.read(cx).snapshot(cx);
14911        let mut to_fold = Vec::new();
14912        let mut stack = vec![(0, snapshot.max_row().0, 1)];
14913
14914        while let Some((mut start_row, end_row, current_level)) = stack.pop() {
14915            while start_row < end_row {
14916                match self
14917                    .snapshot(window, cx)
14918                    .crease_for_buffer_row(MultiBufferRow(start_row))
14919                {
14920                    Some(crease) => {
14921                        let nested_start_row = crease.range().start.row + 1;
14922                        let nested_end_row = crease.range().end.row;
14923
14924                        if current_level < fold_at_level {
14925                            stack.push((nested_start_row, nested_end_row, current_level + 1));
14926                        } else if current_level == fold_at_level {
14927                            to_fold.push(crease);
14928                        }
14929
14930                        start_row = nested_end_row + 1;
14931                    }
14932                    None => start_row += 1,
14933                }
14934            }
14935        }
14936
14937        self.fold_creases(to_fold, true, window, cx);
14938    }
14939
14940    pub fn fold_all(&mut self, _: &actions::FoldAll, window: &mut Window, cx: &mut Context<Self>) {
14941        if self.buffer.read(cx).is_singleton() {
14942            let mut fold_ranges = Vec::new();
14943            let snapshot = self.buffer.read(cx).snapshot(cx);
14944
14945            for row in 0..snapshot.max_row().0 {
14946                if let Some(foldable_range) = self
14947                    .snapshot(window, cx)
14948                    .crease_for_buffer_row(MultiBufferRow(row))
14949                {
14950                    fold_ranges.push(foldable_range);
14951                }
14952            }
14953
14954            self.fold_creases(fold_ranges, true, window, cx);
14955        } else {
14956            self.toggle_fold_multiple_buffers = cx.spawn_in(window, async move |editor, cx| {
14957                editor
14958                    .update_in(cx, |editor, _, cx| {
14959                        for buffer_id in editor.buffer.read(cx).excerpt_buffer_ids() {
14960                            editor.fold_buffer(buffer_id, cx);
14961                        }
14962                    })
14963                    .ok();
14964            });
14965        }
14966    }
14967
14968    pub fn fold_function_bodies(
14969        &mut self,
14970        _: &actions::FoldFunctionBodies,
14971        window: &mut Window,
14972        cx: &mut Context<Self>,
14973    ) {
14974        let snapshot = self.buffer.read(cx).snapshot(cx);
14975
14976        let ranges = snapshot
14977            .text_object_ranges(0..snapshot.len(), TreeSitterOptions::default())
14978            .filter_map(|(range, obj)| (obj == TextObject::InsideFunction).then_some(range))
14979            .collect::<Vec<_>>();
14980
14981        let creases = ranges
14982            .into_iter()
14983            .map(|range| Crease::simple(range, self.display_map.read(cx).fold_placeholder.clone()))
14984            .collect();
14985
14986        self.fold_creases(creases, true, window, cx);
14987    }
14988
14989    pub fn fold_recursive(
14990        &mut self,
14991        _: &actions::FoldRecursive,
14992        window: &mut Window,
14993        cx: &mut Context<Self>,
14994    ) {
14995        let mut to_fold = Vec::new();
14996        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
14997        let selections = self.selections.all_adjusted(cx);
14998
14999        for selection in selections {
15000            let range = selection.range().sorted();
15001            let buffer_start_row = range.start.row;
15002
15003            if range.start.row != range.end.row {
15004                let mut found = false;
15005                for row in range.start.row..=range.end.row {
15006                    if let Some(crease) = display_map.crease_for_buffer_row(MultiBufferRow(row)) {
15007                        found = true;
15008                        to_fold.push(crease);
15009                    }
15010                }
15011                if found {
15012                    continue;
15013                }
15014            }
15015
15016            for row in (0..=range.start.row).rev() {
15017                if let Some(crease) = display_map.crease_for_buffer_row(MultiBufferRow(row)) {
15018                    if crease.range().end.row >= buffer_start_row {
15019                        to_fold.push(crease);
15020                    } else {
15021                        break;
15022                    }
15023                }
15024            }
15025        }
15026
15027        self.fold_creases(to_fold, true, window, cx);
15028    }
15029
15030    pub fn fold_at(
15031        &mut self,
15032        buffer_row: MultiBufferRow,
15033        window: &mut Window,
15034        cx: &mut Context<Self>,
15035    ) {
15036        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
15037
15038        if let Some(crease) = display_map.crease_for_buffer_row(buffer_row) {
15039            let autoscroll = self
15040                .selections
15041                .all::<Point>(cx)
15042                .iter()
15043                .any(|selection| crease.range().overlaps(&selection.range()));
15044
15045            self.fold_creases(vec![crease], autoscroll, window, cx);
15046        }
15047    }
15048
15049    pub fn unfold_lines(&mut self, _: &UnfoldLines, _window: &mut Window, cx: &mut Context<Self>) {
15050        if self.is_singleton(cx) {
15051            let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
15052            let buffer = &display_map.buffer_snapshot;
15053            let selections = self.selections.all::<Point>(cx);
15054            let ranges = selections
15055                .iter()
15056                .map(|s| {
15057                    let range = s.display_range(&display_map).sorted();
15058                    let mut start = range.start.to_point(&display_map);
15059                    let mut end = range.end.to_point(&display_map);
15060                    start.column = 0;
15061                    end.column = buffer.line_len(MultiBufferRow(end.row));
15062                    start..end
15063                })
15064                .collect::<Vec<_>>();
15065
15066            self.unfold_ranges(&ranges, true, true, cx);
15067        } else {
15068            let multi_buffer_snapshot = self.buffer.read(cx).snapshot(cx);
15069            let buffer_ids = self
15070                .selections
15071                .disjoint_anchor_ranges()
15072                .flat_map(|range| multi_buffer_snapshot.buffer_ids_for_range(range))
15073                .collect::<HashSet<_>>();
15074            for buffer_id in buffer_ids {
15075                self.unfold_buffer(buffer_id, cx);
15076            }
15077        }
15078    }
15079
15080    pub fn unfold_recursive(
15081        &mut self,
15082        _: &UnfoldRecursive,
15083        _window: &mut Window,
15084        cx: &mut Context<Self>,
15085    ) {
15086        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
15087        let selections = self.selections.all::<Point>(cx);
15088        let ranges = selections
15089            .iter()
15090            .map(|s| {
15091                let mut range = s.display_range(&display_map).sorted();
15092                *range.start.column_mut() = 0;
15093                *range.end.column_mut() = display_map.line_len(range.end.row());
15094                let start = range.start.to_point(&display_map);
15095                let end = range.end.to_point(&display_map);
15096                start..end
15097            })
15098            .collect::<Vec<_>>();
15099
15100        self.unfold_ranges(&ranges, true, true, cx);
15101    }
15102
15103    pub fn unfold_at(
15104        &mut self,
15105        buffer_row: MultiBufferRow,
15106        _window: &mut Window,
15107        cx: &mut Context<Self>,
15108    ) {
15109        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
15110
15111        let intersection_range = Point::new(buffer_row.0, 0)
15112            ..Point::new(
15113                buffer_row.0,
15114                display_map.buffer_snapshot.line_len(buffer_row),
15115            );
15116
15117        let autoscroll = self
15118            .selections
15119            .all::<Point>(cx)
15120            .iter()
15121            .any(|selection| RangeExt::overlaps(&selection.range(), &intersection_range));
15122
15123        self.unfold_ranges(&[intersection_range], true, autoscroll, cx);
15124    }
15125
15126    pub fn unfold_all(
15127        &mut self,
15128        _: &actions::UnfoldAll,
15129        _window: &mut Window,
15130        cx: &mut Context<Self>,
15131    ) {
15132        if self.buffer.read(cx).is_singleton() {
15133            let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
15134            self.unfold_ranges(&[0..display_map.buffer_snapshot.len()], true, true, cx);
15135        } else {
15136            self.toggle_fold_multiple_buffers = cx.spawn(async move |editor, cx| {
15137                editor
15138                    .update(cx, |editor, cx| {
15139                        for buffer_id in editor.buffer.read(cx).excerpt_buffer_ids() {
15140                            editor.unfold_buffer(buffer_id, cx);
15141                        }
15142                    })
15143                    .ok();
15144            });
15145        }
15146    }
15147
15148    pub fn fold_selected_ranges(
15149        &mut self,
15150        _: &FoldSelectedRanges,
15151        window: &mut Window,
15152        cx: &mut Context<Self>,
15153    ) {
15154        let selections = self.selections.all_adjusted(cx);
15155        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
15156        let ranges = selections
15157            .into_iter()
15158            .map(|s| Crease::simple(s.range(), display_map.fold_placeholder.clone()))
15159            .collect::<Vec<_>>();
15160        self.fold_creases(ranges, true, window, cx);
15161    }
15162
15163    pub fn fold_ranges<T: ToOffset + Clone>(
15164        &mut self,
15165        ranges: Vec<Range<T>>,
15166        auto_scroll: bool,
15167        window: &mut Window,
15168        cx: &mut Context<Self>,
15169    ) {
15170        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
15171        let ranges = ranges
15172            .into_iter()
15173            .map(|r| Crease::simple(r, display_map.fold_placeholder.clone()))
15174            .collect::<Vec<_>>();
15175        self.fold_creases(ranges, auto_scroll, window, cx);
15176    }
15177
15178    pub fn fold_creases<T: ToOffset + Clone>(
15179        &mut self,
15180        creases: Vec<Crease<T>>,
15181        auto_scroll: bool,
15182        _window: &mut Window,
15183        cx: &mut Context<Self>,
15184    ) {
15185        if creases.is_empty() {
15186            return;
15187        }
15188
15189        let mut buffers_affected = HashSet::default();
15190        let multi_buffer = self.buffer().read(cx);
15191        for crease in &creases {
15192            if let Some((_, buffer, _)) =
15193                multi_buffer.excerpt_containing(crease.range().start.clone(), cx)
15194            {
15195                buffers_affected.insert(buffer.read(cx).remote_id());
15196            };
15197        }
15198
15199        self.display_map.update(cx, |map, cx| map.fold(creases, cx));
15200
15201        if auto_scroll {
15202            self.request_autoscroll(Autoscroll::fit(), cx);
15203        }
15204
15205        cx.notify();
15206
15207        self.scrollbar_marker_state.dirty = true;
15208        self.folds_did_change(cx);
15209    }
15210
15211    /// Removes any folds whose ranges intersect any of the given ranges.
15212    pub fn unfold_ranges<T: ToOffset + Clone>(
15213        &mut self,
15214        ranges: &[Range<T>],
15215        inclusive: bool,
15216        auto_scroll: bool,
15217        cx: &mut Context<Self>,
15218    ) {
15219        self.remove_folds_with(ranges, auto_scroll, cx, |map, cx| {
15220            map.unfold_intersecting(ranges.iter().cloned(), inclusive, cx)
15221        });
15222        self.folds_did_change(cx);
15223    }
15224
15225    pub fn fold_buffer(&mut self, buffer_id: BufferId, cx: &mut Context<Self>) {
15226        if self.buffer().read(cx).is_singleton() || self.is_buffer_folded(buffer_id, cx) {
15227            return;
15228        }
15229        let folded_excerpts = self.buffer().read(cx).excerpts_for_buffer(buffer_id, cx);
15230        self.display_map.update(cx, |display_map, cx| {
15231            display_map.fold_buffers([buffer_id], cx)
15232        });
15233        cx.emit(EditorEvent::BufferFoldToggled {
15234            ids: folded_excerpts.iter().map(|&(id, _)| id).collect(),
15235            folded: true,
15236        });
15237        cx.notify();
15238    }
15239
15240    pub fn unfold_buffer(&mut self, buffer_id: BufferId, cx: &mut Context<Self>) {
15241        if self.buffer().read(cx).is_singleton() || !self.is_buffer_folded(buffer_id, cx) {
15242            return;
15243        }
15244        let unfolded_excerpts = self.buffer().read(cx).excerpts_for_buffer(buffer_id, cx);
15245        self.display_map.update(cx, |display_map, cx| {
15246            display_map.unfold_buffers([buffer_id], cx);
15247        });
15248        cx.emit(EditorEvent::BufferFoldToggled {
15249            ids: unfolded_excerpts.iter().map(|&(id, _)| id).collect(),
15250            folded: false,
15251        });
15252        cx.notify();
15253    }
15254
15255    pub fn is_buffer_folded(&self, buffer: BufferId, cx: &App) -> bool {
15256        self.display_map.read(cx).is_buffer_folded(buffer)
15257    }
15258
15259    pub fn folded_buffers<'a>(&self, cx: &'a App) -> &'a HashSet<BufferId> {
15260        self.display_map.read(cx).folded_buffers()
15261    }
15262
15263    pub fn disable_header_for_buffer(&mut self, buffer_id: BufferId, cx: &mut Context<Self>) {
15264        self.display_map.update(cx, |display_map, cx| {
15265            display_map.disable_header_for_buffer(buffer_id, cx);
15266        });
15267        cx.notify();
15268    }
15269
15270    /// Removes any folds with the given ranges.
15271    pub fn remove_folds_with_type<T: ToOffset + Clone>(
15272        &mut self,
15273        ranges: &[Range<T>],
15274        type_id: TypeId,
15275        auto_scroll: bool,
15276        cx: &mut Context<Self>,
15277    ) {
15278        self.remove_folds_with(ranges, auto_scroll, cx, |map, cx| {
15279            map.remove_folds_with_type(ranges.iter().cloned(), type_id, cx)
15280        });
15281        self.folds_did_change(cx);
15282    }
15283
15284    fn remove_folds_with<T: ToOffset + Clone>(
15285        &mut self,
15286        ranges: &[Range<T>],
15287        auto_scroll: bool,
15288        cx: &mut Context<Self>,
15289        update: impl FnOnce(&mut DisplayMap, &mut Context<DisplayMap>),
15290    ) {
15291        if ranges.is_empty() {
15292            return;
15293        }
15294
15295        let mut buffers_affected = HashSet::default();
15296        let multi_buffer = self.buffer().read(cx);
15297        for range in ranges {
15298            if let Some((_, buffer, _)) = multi_buffer.excerpt_containing(range.start.clone(), cx) {
15299                buffers_affected.insert(buffer.read(cx).remote_id());
15300            };
15301        }
15302
15303        self.display_map.update(cx, update);
15304
15305        if auto_scroll {
15306            self.request_autoscroll(Autoscroll::fit(), cx);
15307        }
15308
15309        cx.notify();
15310        self.scrollbar_marker_state.dirty = true;
15311        self.active_indent_guides_state.dirty = true;
15312    }
15313
15314    pub fn update_fold_widths(
15315        &mut self,
15316        widths: impl IntoIterator<Item = (FoldId, Pixels)>,
15317        cx: &mut Context<Self>,
15318    ) -> bool {
15319        self.display_map
15320            .update(cx, |map, cx| map.update_fold_widths(widths, cx))
15321    }
15322
15323    pub fn default_fold_placeholder(&self, cx: &App) -> FoldPlaceholder {
15324        self.display_map.read(cx).fold_placeholder.clone()
15325    }
15326
15327    pub fn set_expand_all_diff_hunks(&mut self, cx: &mut App) {
15328        self.buffer.update(cx, |buffer, cx| {
15329            buffer.set_all_diff_hunks_expanded(cx);
15330        });
15331    }
15332
15333    pub fn expand_all_diff_hunks(
15334        &mut self,
15335        _: &ExpandAllDiffHunks,
15336        _window: &mut Window,
15337        cx: &mut Context<Self>,
15338    ) {
15339        self.buffer.update(cx, |buffer, cx| {
15340            buffer.expand_diff_hunks(vec![Anchor::min()..Anchor::max()], cx)
15341        });
15342    }
15343
15344    pub fn toggle_selected_diff_hunks(
15345        &mut self,
15346        _: &ToggleSelectedDiffHunks,
15347        _window: &mut Window,
15348        cx: &mut Context<Self>,
15349    ) {
15350        let ranges: Vec<_> = self.selections.disjoint.iter().map(|s| s.range()).collect();
15351        self.toggle_diff_hunks_in_ranges(ranges, cx);
15352    }
15353
15354    pub fn diff_hunks_in_ranges<'a>(
15355        &'a self,
15356        ranges: &'a [Range<Anchor>],
15357        buffer: &'a MultiBufferSnapshot,
15358    ) -> impl 'a + Iterator<Item = MultiBufferDiffHunk> {
15359        ranges.iter().flat_map(move |range| {
15360            let end_excerpt_id = range.end.excerpt_id;
15361            let range = range.to_point(buffer);
15362            let mut peek_end = range.end;
15363            if range.end.row < buffer.max_row().0 {
15364                peek_end = Point::new(range.end.row + 1, 0);
15365            }
15366            buffer
15367                .diff_hunks_in_range(range.start..peek_end)
15368                .filter(move |hunk| hunk.excerpt_id.cmp(&end_excerpt_id, buffer).is_le())
15369        })
15370    }
15371
15372    pub fn has_stageable_diff_hunks_in_ranges(
15373        &self,
15374        ranges: &[Range<Anchor>],
15375        snapshot: &MultiBufferSnapshot,
15376    ) -> bool {
15377        let mut hunks = self.diff_hunks_in_ranges(ranges, &snapshot);
15378        hunks.any(|hunk| hunk.status().has_secondary_hunk())
15379    }
15380
15381    pub fn toggle_staged_selected_diff_hunks(
15382        &mut self,
15383        _: &::git::ToggleStaged,
15384        _: &mut Window,
15385        cx: &mut Context<Self>,
15386    ) {
15387        let snapshot = self.buffer.read(cx).snapshot(cx);
15388        let ranges: Vec<_> = self.selections.disjoint.iter().map(|s| s.range()).collect();
15389        let stage = self.has_stageable_diff_hunks_in_ranges(&ranges, &snapshot);
15390        self.stage_or_unstage_diff_hunks(stage, ranges, cx);
15391    }
15392
15393    pub fn set_render_diff_hunk_controls(
15394        &mut self,
15395        render_diff_hunk_controls: RenderDiffHunkControlsFn,
15396        cx: &mut Context<Self>,
15397    ) {
15398        self.render_diff_hunk_controls = render_diff_hunk_controls;
15399        cx.notify();
15400    }
15401
15402    pub fn stage_and_next(
15403        &mut self,
15404        _: &::git::StageAndNext,
15405        window: &mut Window,
15406        cx: &mut Context<Self>,
15407    ) {
15408        self.do_stage_or_unstage_and_next(true, window, cx);
15409    }
15410
15411    pub fn unstage_and_next(
15412        &mut self,
15413        _: &::git::UnstageAndNext,
15414        window: &mut Window,
15415        cx: &mut Context<Self>,
15416    ) {
15417        self.do_stage_or_unstage_and_next(false, window, cx);
15418    }
15419
15420    pub fn stage_or_unstage_diff_hunks(
15421        &mut self,
15422        stage: bool,
15423        ranges: Vec<Range<Anchor>>,
15424        cx: &mut Context<Self>,
15425    ) {
15426        let task = self.save_buffers_for_ranges_if_needed(&ranges, cx);
15427        cx.spawn(async move |this, cx| {
15428            task.await?;
15429            this.update(cx, |this, cx| {
15430                let snapshot = this.buffer.read(cx).snapshot(cx);
15431                let chunk_by = this
15432                    .diff_hunks_in_ranges(&ranges, &snapshot)
15433                    .chunk_by(|hunk| hunk.buffer_id);
15434                for (buffer_id, hunks) in &chunk_by {
15435                    this.do_stage_or_unstage(stage, buffer_id, hunks, cx);
15436                }
15437            })
15438        })
15439        .detach_and_log_err(cx);
15440    }
15441
15442    fn save_buffers_for_ranges_if_needed(
15443        &mut self,
15444        ranges: &[Range<Anchor>],
15445        cx: &mut Context<Editor>,
15446    ) -> Task<Result<()>> {
15447        let multibuffer = self.buffer.read(cx);
15448        let snapshot = multibuffer.read(cx);
15449        let buffer_ids: HashSet<_> = ranges
15450            .iter()
15451            .flat_map(|range| snapshot.buffer_ids_for_range(range.clone()))
15452            .collect();
15453        drop(snapshot);
15454
15455        let mut buffers = HashSet::default();
15456        for buffer_id in buffer_ids {
15457            if let Some(buffer_entity) = multibuffer.buffer(buffer_id) {
15458                let buffer = buffer_entity.read(cx);
15459                if buffer.file().is_some_and(|file| file.disk_state().exists()) && buffer.is_dirty()
15460                {
15461                    buffers.insert(buffer_entity);
15462                }
15463            }
15464        }
15465
15466        if let Some(project) = &self.project {
15467            project.update(cx, |project, cx| project.save_buffers(buffers, cx))
15468        } else {
15469            Task::ready(Ok(()))
15470        }
15471    }
15472
15473    fn do_stage_or_unstage_and_next(
15474        &mut self,
15475        stage: bool,
15476        window: &mut Window,
15477        cx: &mut Context<Self>,
15478    ) {
15479        let ranges = self.selections.disjoint_anchor_ranges().collect::<Vec<_>>();
15480
15481        if ranges.iter().any(|range| range.start != range.end) {
15482            self.stage_or_unstage_diff_hunks(stage, ranges, cx);
15483            return;
15484        }
15485
15486        self.stage_or_unstage_diff_hunks(stage, ranges, cx);
15487        let snapshot = self.snapshot(window, cx);
15488        let position = self.selections.newest::<Point>(cx).head();
15489        let mut row = snapshot
15490            .buffer_snapshot
15491            .diff_hunks_in_range(position..snapshot.buffer_snapshot.max_point())
15492            .find(|hunk| hunk.row_range.start.0 > position.row)
15493            .map(|hunk| hunk.row_range.start);
15494
15495        let all_diff_hunks_expanded = self.buffer().read(cx).all_diff_hunks_expanded();
15496        // Outside of the project diff editor, wrap around to the beginning.
15497        if !all_diff_hunks_expanded {
15498            row = row.or_else(|| {
15499                snapshot
15500                    .buffer_snapshot
15501                    .diff_hunks_in_range(Point::zero()..position)
15502                    .find(|hunk| hunk.row_range.end.0 < position.row)
15503                    .map(|hunk| hunk.row_range.start)
15504            });
15505        }
15506
15507        if let Some(row) = row {
15508            let destination = Point::new(row.0, 0);
15509            let autoscroll = Autoscroll::center();
15510
15511            self.unfold_ranges(&[destination..destination], false, false, cx);
15512            self.change_selections(Some(autoscroll), window, cx, |s| {
15513                s.select_ranges([destination..destination]);
15514            });
15515        }
15516    }
15517
15518    fn do_stage_or_unstage(
15519        &self,
15520        stage: bool,
15521        buffer_id: BufferId,
15522        hunks: impl Iterator<Item = MultiBufferDiffHunk>,
15523        cx: &mut App,
15524    ) -> Option<()> {
15525        let project = self.project.as_ref()?;
15526        let buffer = project.read(cx).buffer_for_id(buffer_id, cx)?;
15527        let diff = self.buffer.read(cx).diff_for(buffer_id)?;
15528        let buffer_snapshot = buffer.read(cx).snapshot();
15529        let file_exists = buffer_snapshot
15530            .file()
15531            .is_some_and(|file| file.disk_state().exists());
15532        diff.update(cx, |diff, cx| {
15533            diff.stage_or_unstage_hunks(
15534                stage,
15535                &hunks
15536                    .map(|hunk| buffer_diff::DiffHunk {
15537                        buffer_range: hunk.buffer_range,
15538                        diff_base_byte_range: hunk.diff_base_byte_range,
15539                        secondary_status: hunk.secondary_status,
15540                        range: Point::zero()..Point::zero(), // unused
15541                    })
15542                    .collect::<Vec<_>>(),
15543                &buffer_snapshot,
15544                file_exists,
15545                cx,
15546            )
15547        });
15548        None
15549    }
15550
15551    pub fn expand_selected_diff_hunks(&mut self, cx: &mut Context<Self>) {
15552        let ranges: Vec<_> = self.selections.disjoint.iter().map(|s| s.range()).collect();
15553        self.buffer
15554            .update(cx, |buffer, cx| buffer.expand_diff_hunks(ranges, cx))
15555    }
15556
15557    pub fn clear_expanded_diff_hunks(&mut self, cx: &mut Context<Self>) -> bool {
15558        self.buffer.update(cx, |buffer, cx| {
15559            let ranges = vec![Anchor::min()..Anchor::max()];
15560            if !buffer.all_diff_hunks_expanded()
15561                && buffer.has_expanded_diff_hunks_in_ranges(&ranges, cx)
15562            {
15563                buffer.collapse_diff_hunks(ranges, cx);
15564                true
15565            } else {
15566                false
15567            }
15568        })
15569    }
15570
15571    fn toggle_diff_hunks_in_ranges(
15572        &mut self,
15573        ranges: Vec<Range<Anchor>>,
15574        cx: &mut Context<Editor>,
15575    ) {
15576        self.buffer.update(cx, |buffer, cx| {
15577            let expand = !buffer.has_expanded_diff_hunks_in_ranges(&ranges, cx);
15578            buffer.expand_or_collapse_diff_hunks(ranges, expand, cx);
15579        })
15580    }
15581
15582    fn toggle_single_diff_hunk(&mut self, range: Range<Anchor>, cx: &mut Context<Self>) {
15583        self.buffer.update(cx, |buffer, cx| {
15584            let snapshot = buffer.snapshot(cx);
15585            let excerpt_id = range.end.excerpt_id;
15586            let point_range = range.to_point(&snapshot);
15587            let expand = !buffer.single_hunk_is_expanded(range, cx);
15588            buffer.expand_or_collapse_diff_hunks_inner([(point_range, excerpt_id)], expand, cx);
15589        })
15590    }
15591
15592    pub(crate) fn apply_all_diff_hunks(
15593        &mut self,
15594        _: &ApplyAllDiffHunks,
15595        window: &mut Window,
15596        cx: &mut Context<Self>,
15597    ) {
15598        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
15599
15600        let buffers = self.buffer.read(cx).all_buffers();
15601        for branch_buffer in buffers {
15602            branch_buffer.update(cx, |branch_buffer, cx| {
15603                branch_buffer.merge_into_base(Vec::new(), cx);
15604            });
15605        }
15606
15607        if let Some(project) = self.project.clone() {
15608            self.save(true, project, window, cx).detach_and_log_err(cx);
15609        }
15610    }
15611
15612    pub(crate) fn apply_selected_diff_hunks(
15613        &mut self,
15614        _: &ApplyDiffHunk,
15615        window: &mut Window,
15616        cx: &mut Context<Self>,
15617    ) {
15618        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
15619        let snapshot = self.snapshot(window, cx);
15620        let hunks = snapshot.hunks_for_ranges(self.selections.ranges(cx));
15621        let mut ranges_by_buffer = HashMap::default();
15622        self.transact(window, cx, |editor, _window, cx| {
15623            for hunk in hunks {
15624                if let Some(buffer) = editor.buffer.read(cx).buffer(hunk.buffer_id) {
15625                    ranges_by_buffer
15626                        .entry(buffer.clone())
15627                        .or_insert_with(Vec::new)
15628                        .push(hunk.buffer_range.to_offset(buffer.read(cx)));
15629                }
15630            }
15631
15632            for (buffer, ranges) in ranges_by_buffer {
15633                buffer.update(cx, |buffer, cx| {
15634                    buffer.merge_into_base(ranges, cx);
15635                });
15636            }
15637        });
15638
15639        if let Some(project) = self.project.clone() {
15640            self.save(true, project, window, cx).detach_and_log_err(cx);
15641        }
15642    }
15643
15644    pub fn set_gutter_hovered(&mut self, hovered: bool, cx: &mut Context<Self>) {
15645        if hovered != self.gutter_hovered {
15646            self.gutter_hovered = hovered;
15647            cx.notify();
15648        }
15649    }
15650
15651    pub fn insert_blocks(
15652        &mut self,
15653        blocks: impl IntoIterator<Item = BlockProperties<Anchor>>,
15654        autoscroll: Option<Autoscroll>,
15655        cx: &mut Context<Self>,
15656    ) -> Vec<CustomBlockId> {
15657        let blocks = self
15658            .display_map
15659            .update(cx, |display_map, cx| display_map.insert_blocks(blocks, cx));
15660        if let Some(autoscroll) = autoscroll {
15661            self.request_autoscroll(autoscroll, cx);
15662        }
15663        cx.notify();
15664        blocks
15665    }
15666
15667    pub fn resize_blocks(
15668        &mut self,
15669        heights: HashMap<CustomBlockId, u32>,
15670        autoscroll: Option<Autoscroll>,
15671        cx: &mut Context<Self>,
15672    ) {
15673        self.display_map
15674            .update(cx, |display_map, cx| display_map.resize_blocks(heights, cx));
15675        if let Some(autoscroll) = autoscroll {
15676            self.request_autoscroll(autoscroll, cx);
15677        }
15678        cx.notify();
15679    }
15680
15681    pub fn replace_blocks(
15682        &mut self,
15683        renderers: HashMap<CustomBlockId, RenderBlock>,
15684        autoscroll: Option<Autoscroll>,
15685        cx: &mut Context<Self>,
15686    ) {
15687        self.display_map
15688            .update(cx, |display_map, _cx| display_map.replace_blocks(renderers));
15689        if let Some(autoscroll) = autoscroll {
15690            self.request_autoscroll(autoscroll, cx);
15691        }
15692        cx.notify();
15693    }
15694
15695    pub fn remove_blocks(
15696        &mut self,
15697        block_ids: HashSet<CustomBlockId>,
15698        autoscroll: Option<Autoscroll>,
15699        cx: &mut Context<Self>,
15700    ) {
15701        self.display_map.update(cx, |display_map, cx| {
15702            display_map.remove_blocks(block_ids, cx)
15703        });
15704        if let Some(autoscroll) = autoscroll {
15705            self.request_autoscroll(autoscroll, cx);
15706        }
15707        cx.notify();
15708    }
15709
15710    pub fn row_for_block(
15711        &self,
15712        block_id: CustomBlockId,
15713        cx: &mut Context<Self>,
15714    ) -> Option<DisplayRow> {
15715        self.display_map
15716            .update(cx, |map, cx| map.row_for_block(block_id, cx))
15717    }
15718
15719    pub(crate) fn set_focused_block(&mut self, focused_block: FocusedBlock) {
15720        self.focused_block = Some(focused_block);
15721    }
15722
15723    pub(crate) fn take_focused_block(&mut self) -> Option<FocusedBlock> {
15724        self.focused_block.take()
15725    }
15726
15727    pub fn insert_creases(
15728        &mut self,
15729        creases: impl IntoIterator<Item = Crease<Anchor>>,
15730        cx: &mut Context<Self>,
15731    ) -> Vec<CreaseId> {
15732        self.display_map
15733            .update(cx, |map, cx| map.insert_creases(creases, cx))
15734    }
15735
15736    pub fn remove_creases(
15737        &mut self,
15738        ids: impl IntoIterator<Item = CreaseId>,
15739        cx: &mut Context<Self>,
15740    ) {
15741        self.display_map
15742            .update(cx, |map, cx| map.remove_creases(ids, cx));
15743    }
15744
15745    pub fn longest_row(&self, cx: &mut App) -> DisplayRow {
15746        self.display_map
15747            .update(cx, |map, cx| map.snapshot(cx))
15748            .longest_row()
15749    }
15750
15751    pub fn max_point(&self, cx: &mut App) -> DisplayPoint {
15752        self.display_map
15753            .update(cx, |map, cx| map.snapshot(cx))
15754            .max_point()
15755    }
15756
15757    pub fn text(&self, cx: &App) -> String {
15758        self.buffer.read(cx).read(cx).text()
15759    }
15760
15761    pub fn is_empty(&self, cx: &App) -> bool {
15762        self.buffer.read(cx).read(cx).is_empty()
15763    }
15764
15765    pub fn text_option(&self, cx: &App) -> Option<String> {
15766        let text = self.text(cx);
15767        let text = text.trim();
15768
15769        if text.is_empty() {
15770            return None;
15771        }
15772
15773        Some(text.to_string())
15774    }
15775
15776    pub fn set_text(
15777        &mut self,
15778        text: impl Into<Arc<str>>,
15779        window: &mut Window,
15780        cx: &mut Context<Self>,
15781    ) {
15782        self.transact(window, cx, |this, _, cx| {
15783            this.buffer
15784                .read(cx)
15785                .as_singleton()
15786                .expect("you can only call set_text on editors for singleton buffers")
15787                .update(cx, |buffer, cx| buffer.set_text(text, cx));
15788        });
15789    }
15790
15791    pub fn display_text(&self, cx: &mut App) -> String {
15792        self.display_map
15793            .update(cx, |map, cx| map.snapshot(cx))
15794            .text()
15795    }
15796
15797    pub fn wrap_guides(&self, cx: &App) -> SmallVec<[(usize, bool); 2]> {
15798        let mut wrap_guides = smallvec::smallvec![];
15799
15800        if self.show_wrap_guides == Some(false) {
15801            return wrap_guides;
15802        }
15803
15804        let settings = self.buffer.read(cx).language_settings(cx);
15805        if settings.show_wrap_guides {
15806            match self.soft_wrap_mode(cx) {
15807                SoftWrap::Column(soft_wrap) => {
15808                    wrap_guides.push((soft_wrap as usize, true));
15809                }
15810                SoftWrap::Bounded(soft_wrap) => {
15811                    wrap_guides.push((soft_wrap as usize, true));
15812                }
15813                SoftWrap::GitDiff | SoftWrap::None | SoftWrap::EditorWidth => {}
15814            }
15815            wrap_guides.extend(settings.wrap_guides.iter().map(|guide| (*guide, false)))
15816        }
15817
15818        wrap_guides
15819    }
15820
15821    pub fn soft_wrap_mode(&self, cx: &App) -> SoftWrap {
15822        let settings = self.buffer.read(cx).language_settings(cx);
15823        let mode = self.soft_wrap_mode_override.unwrap_or(settings.soft_wrap);
15824        match mode {
15825            language_settings::SoftWrap::PreferLine | language_settings::SoftWrap::None => {
15826                SoftWrap::None
15827            }
15828            language_settings::SoftWrap::EditorWidth => SoftWrap::EditorWidth,
15829            language_settings::SoftWrap::PreferredLineLength => {
15830                SoftWrap::Column(settings.preferred_line_length)
15831            }
15832            language_settings::SoftWrap::Bounded => {
15833                SoftWrap::Bounded(settings.preferred_line_length)
15834            }
15835        }
15836    }
15837
15838    pub fn set_soft_wrap_mode(
15839        &mut self,
15840        mode: language_settings::SoftWrap,
15841
15842        cx: &mut Context<Self>,
15843    ) {
15844        self.soft_wrap_mode_override = Some(mode);
15845        cx.notify();
15846    }
15847
15848    pub fn set_hard_wrap(&mut self, hard_wrap: Option<usize>, cx: &mut Context<Self>) {
15849        self.hard_wrap = hard_wrap;
15850        cx.notify();
15851    }
15852
15853    pub fn set_text_style_refinement(&mut self, style: TextStyleRefinement) {
15854        self.text_style_refinement = Some(style);
15855    }
15856
15857    /// called by the Element so we know what style we were most recently rendered with.
15858    pub(crate) fn set_style(
15859        &mut self,
15860        style: EditorStyle,
15861        window: &mut Window,
15862        cx: &mut Context<Self>,
15863    ) {
15864        let rem_size = window.rem_size();
15865        self.display_map.update(cx, |map, cx| {
15866            map.set_font(
15867                style.text.font(),
15868                style.text.font_size.to_pixels(rem_size),
15869                cx,
15870            )
15871        });
15872        self.style = Some(style);
15873    }
15874
15875    pub fn style(&self) -> Option<&EditorStyle> {
15876        self.style.as_ref()
15877    }
15878
15879    // Called by the element. This method is not designed to be called outside of the editor
15880    // element's layout code because it does not notify when rewrapping is computed synchronously.
15881    pub(crate) fn set_wrap_width(&self, width: Option<Pixels>, cx: &mut App) -> bool {
15882        self.display_map
15883            .update(cx, |map, cx| map.set_wrap_width(width, cx))
15884    }
15885
15886    pub fn set_soft_wrap(&mut self) {
15887        self.soft_wrap_mode_override = Some(language_settings::SoftWrap::EditorWidth)
15888    }
15889
15890    pub fn toggle_soft_wrap(&mut self, _: &ToggleSoftWrap, _: &mut Window, cx: &mut Context<Self>) {
15891        if self.soft_wrap_mode_override.is_some() {
15892            self.soft_wrap_mode_override.take();
15893        } else {
15894            let soft_wrap = match self.soft_wrap_mode(cx) {
15895                SoftWrap::GitDiff => return,
15896                SoftWrap::None => language_settings::SoftWrap::EditorWidth,
15897                SoftWrap::EditorWidth | SoftWrap::Column(_) | SoftWrap::Bounded(_) => {
15898                    language_settings::SoftWrap::None
15899                }
15900            };
15901            self.soft_wrap_mode_override = Some(soft_wrap);
15902        }
15903        cx.notify();
15904    }
15905
15906    pub fn toggle_tab_bar(&mut self, _: &ToggleTabBar, _: &mut Window, cx: &mut Context<Self>) {
15907        let Some(workspace) = self.workspace() else {
15908            return;
15909        };
15910        let fs = workspace.read(cx).app_state().fs.clone();
15911        let current_show = TabBarSettings::get_global(cx).show;
15912        update_settings_file::<TabBarSettings>(fs, cx, move |setting, _| {
15913            setting.show = Some(!current_show);
15914        });
15915    }
15916
15917    pub fn toggle_indent_guides(
15918        &mut self,
15919        _: &ToggleIndentGuides,
15920        _: &mut Window,
15921        cx: &mut Context<Self>,
15922    ) {
15923        let currently_enabled = self.should_show_indent_guides().unwrap_or_else(|| {
15924            self.buffer
15925                .read(cx)
15926                .language_settings(cx)
15927                .indent_guides
15928                .enabled
15929        });
15930        self.show_indent_guides = Some(!currently_enabled);
15931        cx.notify();
15932    }
15933
15934    fn should_show_indent_guides(&self) -> Option<bool> {
15935        self.show_indent_guides
15936    }
15937
15938    pub fn toggle_line_numbers(
15939        &mut self,
15940        _: &ToggleLineNumbers,
15941        _: &mut Window,
15942        cx: &mut Context<Self>,
15943    ) {
15944        let mut editor_settings = EditorSettings::get_global(cx).clone();
15945        editor_settings.gutter.line_numbers = !editor_settings.gutter.line_numbers;
15946        EditorSettings::override_global(editor_settings, cx);
15947    }
15948
15949    pub fn line_numbers_enabled(&self, cx: &App) -> bool {
15950        if let Some(show_line_numbers) = self.show_line_numbers {
15951            return show_line_numbers;
15952        }
15953        EditorSettings::get_global(cx).gutter.line_numbers
15954    }
15955
15956    pub fn should_use_relative_line_numbers(&self, cx: &mut App) -> bool {
15957        self.use_relative_line_numbers
15958            .unwrap_or(EditorSettings::get_global(cx).relative_line_numbers)
15959    }
15960
15961    pub fn toggle_relative_line_numbers(
15962        &mut self,
15963        _: &ToggleRelativeLineNumbers,
15964        _: &mut Window,
15965        cx: &mut Context<Self>,
15966    ) {
15967        let is_relative = self.should_use_relative_line_numbers(cx);
15968        self.set_relative_line_number(Some(!is_relative), cx)
15969    }
15970
15971    pub fn set_relative_line_number(&mut self, is_relative: Option<bool>, cx: &mut Context<Self>) {
15972        self.use_relative_line_numbers = is_relative;
15973        cx.notify();
15974    }
15975
15976    pub fn set_show_gutter(&mut self, show_gutter: bool, cx: &mut Context<Self>) {
15977        self.show_gutter = show_gutter;
15978        cx.notify();
15979    }
15980
15981    pub fn set_show_scrollbars(&mut self, show_scrollbars: bool, cx: &mut Context<Self>) {
15982        self.show_scrollbars = show_scrollbars;
15983        cx.notify();
15984    }
15985
15986    pub fn set_show_line_numbers(&mut self, show_line_numbers: bool, cx: &mut Context<Self>) {
15987        self.show_line_numbers = Some(show_line_numbers);
15988        cx.notify();
15989    }
15990
15991    pub fn set_show_git_diff_gutter(&mut self, show_git_diff_gutter: bool, cx: &mut Context<Self>) {
15992        self.show_git_diff_gutter = Some(show_git_diff_gutter);
15993        cx.notify();
15994    }
15995
15996    pub fn set_show_code_actions(&mut self, show_code_actions: bool, cx: &mut Context<Self>) {
15997        self.show_code_actions = Some(show_code_actions);
15998        cx.notify();
15999    }
16000
16001    pub fn set_show_runnables(&mut self, show_runnables: bool, cx: &mut Context<Self>) {
16002        self.show_runnables = Some(show_runnables);
16003        cx.notify();
16004    }
16005
16006    pub fn set_show_breakpoints(&mut self, show_breakpoints: bool, cx: &mut Context<Self>) {
16007        self.show_breakpoints = Some(show_breakpoints);
16008        cx.notify();
16009    }
16010
16011    pub fn set_masked(&mut self, masked: bool, cx: &mut Context<Self>) {
16012        if self.display_map.read(cx).masked != masked {
16013            self.display_map.update(cx, |map, _| map.masked = masked);
16014        }
16015        cx.notify()
16016    }
16017
16018    pub fn set_show_wrap_guides(&mut self, show_wrap_guides: bool, cx: &mut Context<Self>) {
16019        self.show_wrap_guides = Some(show_wrap_guides);
16020        cx.notify();
16021    }
16022
16023    pub fn set_show_indent_guides(&mut self, show_indent_guides: bool, cx: &mut Context<Self>) {
16024        self.show_indent_guides = Some(show_indent_guides);
16025        cx.notify();
16026    }
16027
16028    pub fn working_directory(&self, cx: &App) -> Option<PathBuf> {
16029        if let Some(buffer) = self.buffer().read(cx).as_singleton() {
16030            if let Some(file) = buffer.read(cx).file().and_then(|f| f.as_local()) {
16031                if let Some(dir) = file.abs_path(cx).parent() {
16032                    return Some(dir.to_owned());
16033                }
16034            }
16035
16036            if let Some(project_path) = buffer.read(cx).project_path(cx) {
16037                return Some(project_path.path.to_path_buf());
16038            }
16039        }
16040
16041        None
16042    }
16043
16044    fn target_file<'a>(&self, cx: &'a App) -> Option<&'a dyn language::LocalFile> {
16045        self.active_excerpt(cx)?
16046            .1
16047            .read(cx)
16048            .file()
16049            .and_then(|f| f.as_local())
16050    }
16051
16052    pub fn target_file_abs_path(&self, cx: &mut Context<Self>) -> Option<PathBuf> {
16053        self.active_excerpt(cx).and_then(|(_, buffer, _)| {
16054            let buffer = buffer.read(cx);
16055            if let Some(project_path) = buffer.project_path(cx) {
16056                let project = self.project.as_ref()?.read(cx);
16057                project.absolute_path(&project_path, cx)
16058            } else {
16059                buffer
16060                    .file()
16061                    .and_then(|file| file.as_local().map(|file| file.abs_path(cx)))
16062            }
16063        })
16064    }
16065
16066    fn target_file_path(&self, cx: &mut Context<Self>) -> Option<PathBuf> {
16067        self.active_excerpt(cx).and_then(|(_, buffer, _)| {
16068            let project_path = buffer.read(cx).project_path(cx)?;
16069            let project = self.project.as_ref()?.read(cx);
16070            let entry = project.entry_for_path(&project_path, cx)?;
16071            let path = entry.path.to_path_buf();
16072            Some(path)
16073        })
16074    }
16075
16076    pub fn reveal_in_finder(
16077        &mut self,
16078        _: &RevealInFileManager,
16079        _window: &mut Window,
16080        cx: &mut Context<Self>,
16081    ) {
16082        if let Some(target) = self.target_file(cx) {
16083            cx.reveal_path(&target.abs_path(cx));
16084        }
16085    }
16086
16087    pub fn copy_path(
16088        &mut self,
16089        _: &zed_actions::workspace::CopyPath,
16090        _window: &mut Window,
16091        cx: &mut Context<Self>,
16092    ) {
16093        if let Some(path) = self.target_file_abs_path(cx) {
16094            if let Some(path) = path.to_str() {
16095                cx.write_to_clipboard(ClipboardItem::new_string(path.to_string()));
16096            }
16097        }
16098    }
16099
16100    pub fn copy_relative_path(
16101        &mut self,
16102        _: &zed_actions::workspace::CopyRelativePath,
16103        _window: &mut Window,
16104        cx: &mut Context<Self>,
16105    ) {
16106        if let Some(path) = self.target_file_path(cx) {
16107            if let Some(path) = path.to_str() {
16108                cx.write_to_clipboard(ClipboardItem::new_string(path.to_string()));
16109            }
16110        }
16111    }
16112
16113    pub fn project_path(&self, cx: &App) -> Option<ProjectPath> {
16114        if let Some(buffer) = self.buffer.read(cx).as_singleton() {
16115            buffer.read(cx).project_path(cx)
16116        } else {
16117            None
16118        }
16119    }
16120
16121    // Returns true if the editor handled a go-to-line request
16122    pub fn go_to_active_debug_line(&mut self, window: &mut Window, cx: &mut Context<Self>) -> bool {
16123        maybe!({
16124            let breakpoint_store = self.breakpoint_store.as_ref()?;
16125
16126            let Some((_, _, active_position)) =
16127                breakpoint_store.read(cx).active_position().cloned()
16128            else {
16129                self.clear_row_highlights::<DebugCurrentRowHighlight>();
16130                return None;
16131            };
16132
16133            let snapshot = self
16134                .project
16135                .as_ref()?
16136                .read(cx)
16137                .buffer_for_id(active_position.buffer_id?, cx)?
16138                .read(cx)
16139                .snapshot();
16140
16141            let mut handled = false;
16142            for (id, ExcerptRange { context, .. }) in self
16143                .buffer
16144                .read(cx)
16145                .excerpts_for_buffer(active_position.buffer_id?, cx)
16146            {
16147                if context.start.cmp(&active_position, &snapshot).is_ge()
16148                    || context.end.cmp(&active_position, &snapshot).is_lt()
16149                {
16150                    continue;
16151                }
16152                let snapshot = self.buffer.read(cx).snapshot(cx);
16153                let multibuffer_anchor = snapshot.anchor_in_excerpt(id, active_position)?;
16154
16155                handled = true;
16156                self.clear_row_highlights::<DebugCurrentRowHighlight>();
16157                self.go_to_line::<DebugCurrentRowHighlight>(
16158                    multibuffer_anchor,
16159                    Some(cx.theme().colors().editor_debugger_active_line_background),
16160                    window,
16161                    cx,
16162                );
16163
16164                cx.notify();
16165            }
16166            handled.then_some(())
16167        })
16168        .is_some()
16169    }
16170
16171    pub fn copy_file_name_without_extension(
16172        &mut self,
16173        _: &CopyFileNameWithoutExtension,
16174        _: &mut Window,
16175        cx: &mut Context<Self>,
16176    ) {
16177        if let Some(file) = self.target_file(cx) {
16178            if let Some(file_stem) = file.path().file_stem() {
16179                if let Some(name) = file_stem.to_str() {
16180                    cx.write_to_clipboard(ClipboardItem::new_string(name.to_string()));
16181                }
16182            }
16183        }
16184    }
16185
16186    pub fn copy_file_name(&mut self, _: &CopyFileName, _: &mut Window, cx: &mut Context<Self>) {
16187        if let Some(file) = self.target_file(cx) {
16188            if let Some(file_name) = file.path().file_name() {
16189                if let Some(name) = file_name.to_str() {
16190                    cx.write_to_clipboard(ClipboardItem::new_string(name.to_string()));
16191                }
16192            }
16193        }
16194    }
16195
16196    pub fn toggle_git_blame(
16197        &mut self,
16198        _: &::git::Blame,
16199        window: &mut Window,
16200        cx: &mut Context<Self>,
16201    ) {
16202        self.show_git_blame_gutter = !self.show_git_blame_gutter;
16203
16204        if self.show_git_blame_gutter && !self.has_blame_entries(cx) {
16205            self.start_git_blame(true, window, cx);
16206        }
16207
16208        cx.notify();
16209    }
16210
16211    pub fn toggle_git_blame_inline(
16212        &mut self,
16213        _: &ToggleGitBlameInline,
16214        window: &mut Window,
16215        cx: &mut Context<Self>,
16216    ) {
16217        self.toggle_git_blame_inline_internal(true, window, cx);
16218        cx.notify();
16219    }
16220
16221    pub fn open_git_blame_commit(
16222        &mut self,
16223        _: &OpenGitBlameCommit,
16224        window: &mut Window,
16225        cx: &mut Context<Self>,
16226    ) {
16227        self.open_git_blame_commit_internal(window, cx);
16228    }
16229
16230    fn open_git_blame_commit_internal(
16231        &mut self,
16232        window: &mut Window,
16233        cx: &mut Context<Self>,
16234    ) -> Option<()> {
16235        let blame = self.blame.as_ref()?;
16236        let snapshot = self.snapshot(window, cx);
16237        let cursor = self.selections.newest::<Point>(cx).head();
16238        let (buffer, point, _) = snapshot.buffer_snapshot.point_to_buffer_point(cursor)?;
16239        let blame_entry = blame
16240            .update(cx, |blame, cx| {
16241                blame
16242                    .blame_for_rows(
16243                        &[RowInfo {
16244                            buffer_id: Some(buffer.remote_id()),
16245                            buffer_row: Some(point.row),
16246                            ..Default::default()
16247                        }],
16248                        cx,
16249                    )
16250                    .next()
16251            })
16252            .flatten()?;
16253        let renderer = cx.global::<GlobalBlameRenderer>().0.clone();
16254        let repo = blame.read(cx).repository(cx)?;
16255        let workspace = self.workspace()?.downgrade();
16256        renderer.open_blame_commit(blame_entry, repo, workspace, window, cx);
16257        None
16258    }
16259
16260    pub fn git_blame_inline_enabled(&self) -> bool {
16261        self.git_blame_inline_enabled
16262    }
16263
16264    pub fn toggle_selection_menu(
16265        &mut self,
16266        _: &ToggleSelectionMenu,
16267        _: &mut Window,
16268        cx: &mut Context<Self>,
16269    ) {
16270        self.show_selection_menu = self
16271            .show_selection_menu
16272            .map(|show_selections_menu| !show_selections_menu)
16273            .or_else(|| Some(!EditorSettings::get_global(cx).toolbar.selections_menu));
16274
16275        cx.notify();
16276    }
16277
16278    pub fn selection_menu_enabled(&self, cx: &App) -> bool {
16279        self.show_selection_menu
16280            .unwrap_or_else(|| EditorSettings::get_global(cx).toolbar.selections_menu)
16281    }
16282
16283    fn start_git_blame(
16284        &mut self,
16285        user_triggered: bool,
16286        window: &mut Window,
16287        cx: &mut Context<Self>,
16288    ) {
16289        if let Some(project) = self.project.as_ref() {
16290            let Some(buffer) = self.buffer().read(cx).as_singleton() else {
16291                return;
16292            };
16293
16294            if buffer.read(cx).file().is_none() {
16295                return;
16296            }
16297
16298            let focused = self.focus_handle(cx).contains_focused(window, cx);
16299
16300            let project = project.clone();
16301            let blame = cx.new(|cx| GitBlame::new(buffer, project, user_triggered, focused, cx));
16302            self.blame_subscription =
16303                Some(cx.observe_in(&blame, window, |_, _, _, cx| cx.notify()));
16304            self.blame = Some(blame);
16305        }
16306    }
16307
16308    fn toggle_git_blame_inline_internal(
16309        &mut self,
16310        user_triggered: bool,
16311        window: &mut Window,
16312        cx: &mut Context<Self>,
16313    ) {
16314        if self.git_blame_inline_enabled {
16315            self.git_blame_inline_enabled = false;
16316            self.show_git_blame_inline = false;
16317            self.show_git_blame_inline_delay_task.take();
16318        } else {
16319            self.git_blame_inline_enabled = true;
16320            self.start_git_blame_inline(user_triggered, window, cx);
16321        }
16322
16323        cx.notify();
16324    }
16325
16326    fn start_git_blame_inline(
16327        &mut self,
16328        user_triggered: bool,
16329        window: &mut Window,
16330        cx: &mut Context<Self>,
16331    ) {
16332        self.start_git_blame(user_triggered, window, cx);
16333
16334        if ProjectSettings::get_global(cx)
16335            .git
16336            .inline_blame_delay()
16337            .is_some()
16338        {
16339            self.start_inline_blame_timer(window, cx);
16340        } else {
16341            self.show_git_blame_inline = true
16342        }
16343    }
16344
16345    pub fn blame(&self) -> Option<&Entity<GitBlame>> {
16346        self.blame.as_ref()
16347    }
16348
16349    pub fn show_git_blame_gutter(&self) -> bool {
16350        self.show_git_blame_gutter
16351    }
16352
16353    pub fn render_git_blame_gutter(&self, cx: &App) -> bool {
16354        self.show_git_blame_gutter && self.has_blame_entries(cx)
16355    }
16356
16357    pub fn render_git_blame_inline(&self, window: &Window, cx: &App) -> bool {
16358        self.show_git_blame_inline
16359            && (self.focus_handle.is_focused(window)
16360                || self
16361                    .git_blame_inline_tooltip
16362                    .as_ref()
16363                    .and_then(|t| t.upgrade())
16364                    .is_some())
16365            && !self.newest_selection_head_on_empty_line(cx)
16366            && self.has_blame_entries(cx)
16367    }
16368
16369    fn has_blame_entries(&self, cx: &App) -> bool {
16370        self.blame()
16371            .map_or(false, |blame| blame.read(cx).has_generated_entries())
16372    }
16373
16374    fn newest_selection_head_on_empty_line(&self, cx: &App) -> bool {
16375        let cursor_anchor = self.selections.newest_anchor().head();
16376
16377        let snapshot = self.buffer.read(cx).snapshot(cx);
16378        let buffer_row = MultiBufferRow(cursor_anchor.to_point(&snapshot).row);
16379
16380        snapshot.line_len(buffer_row) == 0
16381    }
16382
16383    fn get_permalink_to_line(&self, cx: &mut Context<Self>) -> Task<Result<url::Url>> {
16384        let buffer_and_selection = maybe!({
16385            let selection = self.selections.newest::<Point>(cx);
16386            let selection_range = selection.range();
16387
16388            let multi_buffer = self.buffer().read(cx);
16389            let multi_buffer_snapshot = multi_buffer.snapshot(cx);
16390            let buffer_ranges = multi_buffer_snapshot.range_to_buffer_ranges(selection_range);
16391
16392            let (buffer, range, _) = if selection.reversed {
16393                buffer_ranges.first()
16394            } else {
16395                buffer_ranges.last()
16396            }?;
16397
16398            let selection = text::ToPoint::to_point(&range.start, &buffer).row
16399                ..text::ToPoint::to_point(&range.end, &buffer).row;
16400            Some((
16401                multi_buffer.buffer(buffer.remote_id()).unwrap().clone(),
16402                selection,
16403            ))
16404        });
16405
16406        let Some((buffer, selection)) = buffer_and_selection else {
16407            return Task::ready(Err(anyhow!("failed to determine buffer and selection")));
16408        };
16409
16410        let Some(project) = self.project.as_ref() else {
16411            return Task::ready(Err(anyhow!("editor does not have project")));
16412        };
16413
16414        project.update(cx, |project, cx| {
16415            project.get_permalink_to_line(&buffer, selection, cx)
16416        })
16417    }
16418
16419    pub fn copy_permalink_to_line(
16420        &mut self,
16421        _: &CopyPermalinkToLine,
16422        window: &mut Window,
16423        cx: &mut Context<Self>,
16424    ) {
16425        let permalink_task = self.get_permalink_to_line(cx);
16426        let workspace = self.workspace();
16427
16428        cx.spawn_in(window, async move |_, cx| match permalink_task.await {
16429            Ok(permalink) => {
16430                cx.update(|_, cx| {
16431                    cx.write_to_clipboard(ClipboardItem::new_string(permalink.to_string()));
16432                })
16433                .ok();
16434            }
16435            Err(err) => {
16436                let message = format!("Failed to copy permalink: {err}");
16437
16438                Err::<(), anyhow::Error>(err).log_err();
16439
16440                if let Some(workspace) = workspace {
16441                    workspace
16442                        .update_in(cx, |workspace, _, cx| {
16443                            struct CopyPermalinkToLine;
16444
16445                            workspace.show_toast(
16446                                Toast::new(
16447                                    NotificationId::unique::<CopyPermalinkToLine>(),
16448                                    message,
16449                                ),
16450                                cx,
16451                            )
16452                        })
16453                        .ok();
16454                }
16455            }
16456        })
16457        .detach();
16458    }
16459
16460    pub fn copy_file_location(
16461        &mut self,
16462        _: &CopyFileLocation,
16463        _: &mut Window,
16464        cx: &mut Context<Self>,
16465    ) {
16466        let selection = self.selections.newest::<Point>(cx).start.row + 1;
16467        if let Some(file) = self.target_file(cx) {
16468            if let Some(path) = file.path().to_str() {
16469                cx.write_to_clipboard(ClipboardItem::new_string(format!("{path}:{selection}")));
16470            }
16471        }
16472    }
16473
16474    pub fn open_permalink_to_line(
16475        &mut self,
16476        _: &OpenPermalinkToLine,
16477        window: &mut Window,
16478        cx: &mut Context<Self>,
16479    ) {
16480        let permalink_task = self.get_permalink_to_line(cx);
16481        let workspace = self.workspace();
16482
16483        cx.spawn_in(window, async move |_, cx| match permalink_task.await {
16484            Ok(permalink) => {
16485                cx.update(|_, cx| {
16486                    cx.open_url(permalink.as_ref());
16487                })
16488                .ok();
16489            }
16490            Err(err) => {
16491                let message = format!("Failed to open permalink: {err}");
16492
16493                Err::<(), anyhow::Error>(err).log_err();
16494
16495                if let Some(workspace) = workspace {
16496                    workspace
16497                        .update(cx, |workspace, cx| {
16498                            struct OpenPermalinkToLine;
16499
16500                            workspace.show_toast(
16501                                Toast::new(
16502                                    NotificationId::unique::<OpenPermalinkToLine>(),
16503                                    message,
16504                                ),
16505                                cx,
16506                            )
16507                        })
16508                        .ok();
16509                }
16510            }
16511        })
16512        .detach();
16513    }
16514
16515    pub fn insert_uuid_v4(
16516        &mut self,
16517        _: &InsertUuidV4,
16518        window: &mut Window,
16519        cx: &mut Context<Self>,
16520    ) {
16521        self.insert_uuid(UuidVersion::V4, window, cx);
16522    }
16523
16524    pub fn insert_uuid_v7(
16525        &mut self,
16526        _: &InsertUuidV7,
16527        window: &mut Window,
16528        cx: &mut Context<Self>,
16529    ) {
16530        self.insert_uuid(UuidVersion::V7, window, cx);
16531    }
16532
16533    fn insert_uuid(&mut self, version: UuidVersion, window: &mut Window, cx: &mut Context<Self>) {
16534        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
16535        self.transact(window, cx, |this, window, cx| {
16536            let edits = this
16537                .selections
16538                .all::<Point>(cx)
16539                .into_iter()
16540                .map(|selection| {
16541                    let uuid = match version {
16542                        UuidVersion::V4 => uuid::Uuid::new_v4(),
16543                        UuidVersion::V7 => uuid::Uuid::now_v7(),
16544                    };
16545
16546                    (selection.range(), uuid.to_string())
16547                });
16548            this.edit(edits, cx);
16549            this.refresh_inline_completion(true, false, window, cx);
16550        });
16551    }
16552
16553    pub fn open_selections_in_multibuffer(
16554        &mut self,
16555        _: &OpenSelectionsInMultibuffer,
16556        window: &mut Window,
16557        cx: &mut Context<Self>,
16558    ) {
16559        let multibuffer = self.buffer.read(cx);
16560
16561        let Some(buffer) = multibuffer.as_singleton() else {
16562            return;
16563        };
16564
16565        let Some(workspace) = self.workspace() else {
16566            return;
16567        };
16568
16569        let locations = self
16570            .selections
16571            .disjoint_anchors()
16572            .iter()
16573            .map(|range| Location {
16574                buffer: buffer.clone(),
16575                range: range.start.text_anchor..range.end.text_anchor,
16576            })
16577            .collect::<Vec<_>>();
16578
16579        let title = multibuffer.title(cx).to_string();
16580
16581        cx.spawn_in(window, async move |_, cx| {
16582            workspace.update_in(cx, |workspace, window, cx| {
16583                Self::open_locations_in_multibuffer(
16584                    workspace,
16585                    locations,
16586                    format!("Selections for '{title}'"),
16587                    false,
16588                    MultibufferSelectionMode::All,
16589                    window,
16590                    cx,
16591                );
16592            })
16593        })
16594        .detach();
16595    }
16596
16597    /// Adds a row highlight for the given range. If a row has multiple highlights, the
16598    /// last highlight added will be used.
16599    ///
16600    /// If the range ends at the beginning of a line, then that line will not be highlighted.
16601    pub fn highlight_rows<T: 'static>(
16602        &mut self,
16603        range: Range<Anchor>,
16604        color: Hsla,
16605        should_autoscroll: bool,
16606        cx: &mut Context<Self>,
16607    ) {
16608        let snapshot = self.buffer().read(cx).snapshot(cx);
16609        let row_highlights = self.highlighted_rows.entry(TypeId::of::<T>()).or_default();
16610        let ix = row_highlights.binary_search_by(|highlight| {
16611            Ordering::Equal
16612                .then_with(|| highlight.range.start.cmp(&range.start, &snapshot))
16613                .then_with(|| highlight.range.end.cmp(&range.end, &snapshot))
16614        });
16615
16616        if let Err(mut ix) = ix {
16617            let index = post_inc(&mut self.highlight_order);
16618
16619            // If this range intersects with the preceding highlight, then merge it with
16620            // the preceding highlight. Otherwise insert a new highlight.
16621            let mut merged = false;
16622            if ix > 0 {
16623                let prev_highlight = &mut row_highlights[ix - 1];
16624                if prev_highlight
16625                    .range
16626                    .end
16627                    .cmp(&range.start, &snapshot)
16628                    .is_ge()
16629                {
16630                    ix -= 1;
16631                    if prev_highlight.range.end.cmp(&range.end, &snapshot).is_lt() {
16632                        prev_highlight.range.end = range.end;
16633                    }
16634                    merged = true;
16635                    prev_highlight.index = index;
16636                    prev_highlight.color = color;
16637                    prev_highlight.should_autoscroll = should_autoscroll;
16638                }
16639            }
16640
16641            if !merged {
16642                row_highlights.insert(
16643                    ix,
16644                    RowHighlight {
16645                        range: range.clone(),
16646                        index,
16647                        color,
16648                        should_autoscroll,
16649                    },
16650                );
16651            }
16652
16653            // If any of the following highlights intersect with this one, merge them.
16654            while let Some(next_highlight) = row_highlights.get(ix + 1) {
16655                let highlight = &row_highlights[ix];
16656                if next_highlight
16657                    .range
16658                    .start
16659                    .cmp(&highlight.range.end, &snapshot)
16660                    .is_le()
16661                {
16662                    if next_highlight
16663                        .range
16664                        .end
16665                        .cmp(&highlight.range.end, &snapshot)
16666                        .is_gt()
16667                    {
16668                        row_highlights[ix].range.end = next_highlight.range.end;
16669                    }
16670                    row_highlights.remove(ix + 1);
16671                } else {
16672                    break;
16673                }
16674            }
16675        }
16676    }
16677
16678    /// Remove any highlighted row ranges of the given type that intersect the
16679    /// given ranges.
16680    pub fn remove_highlighted_rows<T: 'static>(
16681        &mut self,
16682        ranges_to_remove: Vec<Range<Anchor>>,
16683        cx: &mut Context<Self>,
16684    ) {
16685        let snapshot = self.buffer().read(cx).snapshot(cx);
16686        let row_highlights = self.highlighted_rows.entry(TypeId::of::<T>()).or_default();
16687        let mut ranges_to_remove = ranges_to_remove.iter().peekable();
16688        row_highlights.retain(|highlight| {
16689            while let Some(range_to_remove) = ranges_to_remove.peek() {
16690                match range_to_remove.end.cmp(&highlight.range.start, &snapshot) {
16691                    Ordering::Less | Ordering::Equal => {
16692                        ranges_to_remove.next();
16693                    }
16694                    Ordering::Greater => {
16695                        match range_to_remove.start.cmp(&highlight.range.end, &snapshot) {
16696                            Ordering::Less | Ordering::Equal => {
16697                                return false;
16698                            }
16699                            Ordering::Greater => break,
16700                        }
16701                    }
16702                }
16703            }
16704
16705            true
16706        })
16707    }
16708
16709    /// Clear all anchor ranges for a certain highlight context type, so no corresponding rows will be highlighted.
16710    pub fn clear_row_highlights<T: 'static>(&mut self) {
16711        self.highlighted_rows.remove(&TypeId::of::<T>());
16712    }
16713
16714    /// For a highlight given context type, gets all anchor ranges that will be used for row highlighting.
16715    pub fn highlighted_rows<T: 'static>(&self) -> impl '_ + Iterator<Item = (Range<Anchor>, Hsla)> {
16716        self.highlighted_rows
16717            .get(&TypeId::of::<T>())
16718            .map_or(&[] as &[_], |vec| vec.as_slice())
16719            .iter()
16720            .map(|highlight| (highlight.range.clone(), highlight.color))
16721    }
16722
16723    /// Merges all anchor ranges for all context types ever set, picking the last highlight added in case of a row conflict.
16724    /// Returns a map of display rows that are highlighted and their corresponding highlight color.
16725    /// Allows to ignore certain kinds of highlights.
16726    pub fn highlighted_display_rows(
16727        &self,
16728        window: &mut Window,
16729        cx: &mut App,
16730    ) -> BTreeMap<DisplayRow, LineHighlight> {
16731        let snapshot = self.snapshot(window, cx);
16732        let mut used_highlight_orders = HashMap::default();
16733        self.highlighted_rows
16734            .iter()
16735            .flat_map(|(_, highlighted_rows)| highlighted_rows.iter())
16736            .fold(
16737                BTreeMap::<DisplayRow, LineHighlight>::new(),
16738                |mut unique_rows, highlight| {
16739                    let start = highlight.range.start.to_display_point(&snapshot);
16740                    let end = highlight.range.end.to_display_point(&snapshot);
16741                    let start_row = start.row().0;
16742                    let end_row = if highlight.range.end.text_anchor != text::Anchor::MAX
16743                        && end.column() == 0
16744                    {
16745                        end.row().0.saturating_sub(1)
16746                    } else {
16747                        end.row().0
16748                    };
16749                    for row in start_row..=end_row {
16750                        let used_index =
16751                            used_highlight_orders.entry(row).or_insert(highlight.index);
16752                        if highlight.index >= *used_index {
16753                            *used_index = highlight.index;
16754                            unique_rows.insert(DisplayRow(row), highlight.color.into());
16755                        }
16756                    }
16757                    unique_rows
16758                },
16759            )
16760    }
16761
16762    pub fn highlighted_display_row_for_autoscroll(
16763        &self,
16764        snapshot: &DisplaySnapshot,
16765    ) -> Option<DisplayRow> {
16766        self.highlighted_rows
16767            .values()
16768            .flat_map(|highlighted_rows| highlighted_rows.iter())
16769            .filter_map(|highlight| {
16770                if highlight.should_autoscroll {
16771                    Some(highlight.range.start.to_display_point(snapshot).row())
16772                } else {
16773                    None
16774                }
16775            })
16776            .min()
16777    }
16778
16779    pub fn set_search_within_ranges(&mut self, ranges: &[Range<Anchor>], cx: &mut Context<Self>) {
16780        self.highlight_background::<SearchWithinRange>(
16781            ranges,
16782            |colors| colors.editor_document_highlight_read_background,
16783            cx,
16784        )
16785    }
16786
16787    pub fn set_breadcrumb_header(&mut self, new_header: String) {
16788        self.breadcrumb_header = Some(new_header);
16789    }
16790
16791    pub fn clear_search_within_ranges(&mut self, cx: &mut Context<Self>) {
16792        self.clear_background_highlights::<SearchWithinRange>(cx);
16793    }
16794
16795    pub fn highlight_background<T: 'static>(
16796        &mut self,
16797        ranges: &[Range<Anchor>],
16798        color_fetcher: fn(&ThemeColors) -> Hsla,
16799        cx: &mut Context<Self>,
16800    ) {
16801        self.background_highlights
16802            .insert(TypeId::of::<T>(), (color_fetcher, Arc::from(ranges)));
16803        self.scrollbar_marker_state.dirty = true;
16804        cx.notify();
16805    }
16806
16807    pub fn clear_background_highlights<T: 'static>(
16808        &mut self,
16809        cx: &mut Context<Self>,
16810    ) -> Option<BackgroundHighlight> {
16811        let text_highlights = self.background_highlights.remove(&TypeId::of::<T>())?;
16812        if !text_highlights.1.is_empty() {
16813            self.scrollbar_marker_state.dirty = true;
16814            cx.notify();
16815        }
16816        Some(text_highlights)
16817    }
16818
16819    pub fn highlight_gutter<T: 'static>(
16820        &mut self,
16821        ranges: &[Range<Anchor>],
16822        color_fetcher: fn(&App) -> Hsla,
16823        cx: &mut Context<Self>,
16824    ) {
16825        self.gutter_highlights
16826            .insert(TypeId::of::<T>(), (color_fetcher, Arc::from(ranges)));
16827        cx.notify();
16828    }
16829
16830    pub fn clear_gutter_highlights<T: 'static>(
16831        &mut self,
16832        cx: &mut Context<Self>,
16833    ) -> Option<GutterHighlight> {
16834        cx.notify();
16835        self.gutter_highlights.remove(&TypeId::of::<T>())
16836    }
16837
16838    #[cfg(feature = "test-support")]
16839    pub fn all_text_background_highlights(
16840        &self,
16841        window: &mut Window,
16842        cx: &mut Context<Self>,
16843    ) -> Vec<(Range<DisplayPoint>, Hsla)> {
16844        let snapshot = self.snapshot(window, cx);
16845        let buffer = &snapshot.buffer_snapshot;
16846        let start = buffer.anchor_before(0);
16847        let end = buffer.anchor_after(buffer.len());
16848        let theme = cx.theme().colors();
16849        self.background_highlights_in_range(start..end, &snapshot, theme)
16850    }
16851
16852    #[cfg(feature = "test-support")]
16853    pub fn search_background_highlights(&mut self, cx: &mut Context<Self>) -> Vec<Range<Point>> {
16854        let snapshot = self.buffer().read(cx).snapshot(cx);
16855
16856        let highlights = self
16857            .background_highlights
16858            .get(&TypeId::of::<items::BufferSearchHighlights>());
16859
16860        if let Some((_color, ranges)) = highlights {
16861            ranges
16862                .iter()
16863                .map(|range| range.start.to_point(&snapshot)..range.end.to_point(&snapshot))
16864                .collect_vec()
16865        } else {
16866            vec![]
16867        }
16868    }
16869
16870    fn document_highlights_for_position<'a>(
16871        &'a self,
16872        position: Anchor,
16873        buffer: &'a MultiBufferSnapshot,
16874    ) -> impl 'a + Iterator<Item = &'a Range<Anchor>> {
16875        let read_highlights = self
16876            .background_highlights
16877            .get(&TypeId::of::<DocumentHighlightRead>())
16878            .map(|h| &h.1);
16879        let write_highlights = self
16880            .background_highlights
16881            .get(&TypeId::of::<DocumentHighlightWrite>())
16882            .map(|h| &h.1);
16883        let left_position = position.bias_left(buffer);
16884        let right_position = position.bias_right(buffer);
16885        read_highlights
16886            .into_iter()
16887            .chain(write_highlights)
16888            .flat_map(move |ranges| {
16889                let start_ix = match ranges.binary_search_by(|probe| {
16890                    let cmp = probe.end.cmp(&left_position, buffer);
16891                    if cmp.is_ge() {
16892                        Ordering::Greater
16893                    } else {
16894                        Ordering::Less
16895                    }
16896                }) {
16897                    Ok(i) | Err(i) => i,
16898                };
16899
16900                ranges[start_ix..]
16901                    .iter()
16902                    .take_while(move |range| range.start.cmp(&right_position, buffer).is_le())
16903            })
16904    }
16905
16906    pub fn has_background_highlights<T: 'static>(&self) -> bool {
16907        self.background_highlights
16908            .get(&TypeId::of::<T>())
16909            .map_or(false, |(_, highlights)| !highlights.is_empty())
16910    }
16911
16912    pub fn background_highlights_in_range(
16913        &self,
16914        search_range: Range<Anchor>,
16915        display_snapshot: &DisplaySnapshot,
16916        theme: &ThemeColors,
16917    ) -> Vec<(Range<DisplayPoint>, Hsla)> {
16918        let mut results = Vec::new();
16919        for (color_fetcher, ranges) in self.background_highlights.values() {
16920            let color = color_fetcher(theme);
16921            let start_ix = match ranges.binary_search_by(|probe| {
16922                let cmp = probe
16923                    .end
16924                    .cmp(&search_range.start, &display_snapshot.buffer_snapshot);
16925                if cmp.is_gt() {
16926                    Ordering::Greater
16927                } else {
16928                    Ordering::Less
16929                }
16930            }) {
16931                Ok(i) | Err(i) => i,
16932            };
16933            for range in &ranges[start_ix..] {
16934                if range
16935                    .start
16936                    .cmp(&search_range.end, &display_snapshot.buffer_snapshot)
16937                    .is_ge()
16938                {
16939                    break;
16940                }
16941
16942                let start = range.start.to_display_point(display_snapshot);
16943                let end = range.end.to_display_point(display_snapshot);
16944                results.push((start..end, color))
16945            }
16946        }
16947        results
16948    }
16949
16950    pub fn background_highlight_row_ranges<T: 'static>(
16951        &self,
16952        search_range: Range<Anchor>,
16953        display_snapshot: &DisplaySnapshot,
16954        count: usize,
16955    ) -> Vec<RangeInclusive<DisplayPoint>> {
16956        let mut results = Vec::new();
16957        let Some((_, ranges)) = self.background_highlights.get(&TypeId::of::<T>()) else {
16958            return vec![];
16959        };
16960
16961        let start_ix = match ranges.binary_search_by(|probe| {
16962            let cmp = probe
16963                .end
16964                .cmp(&search_range.start, &display_snapshot.buffer_snapshot);
16965            if cmp.is_gt() {
16966                Ordering::Greater
16967            } else {
16968                Ordering::Less
16969            }
16970        }) {
16971            Ok(i) | Err(i) => i,
16972        };
16973        let mut push_region = |start: Option<Point>, end: Option<Point>| {
16974            if let (Some(start_display), Some(end_display)) = (start, end) {
16975                results.push(
16976                    start_display.to_display_point(display_snapshot)
16977                        ..=end_display.to_display_point(display_snapshot),
16978                );
16979            }
16980        };
16981        let mut start_row: Option<Point> = None;
16982        let mut end_row: Option<Point> = None;
16983        if ranges.len() > count {
16984            return Vec::new();
16985        }
16986        for range in &ranges[start_ix..] {
16987            if range
16988                .start
16989                .cmp(&search_range.end, &display_snapshot.buffer_snapshot)
16990                .is_ge()
16991            {
16992                break;
16993            }
16994            let end = range.end.to_point(&display_snapshot.buffer_snapshot);
16995            if let Some(current_row) = &end_row {
16996                if end.row == current_row.row {
16997                    continue;
16998                }
16999            }
17000            let start = range.start.to_point(&display_snapshot.buffer_snapshot);
17001            if start_row.is_none() {
17002                assert_eq!(end_row, None);
17003                start_row = Some(start);
17004                end_row = Some(end);
17005                continue;
17006            }
17007            if let Some(current_end) = end_row.as_mut() {
17008                if start.row > current_end.row + 1 {
17009                    push_region(start_row, end_row);
17010                    start_row = Some(start);
17011                    end_row = Some(end);
17012                } else {
17013                    // Merge two hunks.
17014                    *current_end = end;
17015                }
17016            } else {
17017                unreachable!();
17018            }
17019        }
17020        // We might still have a hunk that was not rendered (if there was a search hit on the last line)
17021        push_region(start_row, end_row);
17022        results
17023    }
17024
17025    pub fn gutter_highlights_in_range(
17026        &self,
17027        search_range: Range<Anchor>,
17028        display_snapshot: &DisplaySnapshot,
17029        cx: &App,
17030    ) -> Vec<(Range<DisplayPoint>, Hsla)> {
17031        let mut results = Vec::new();
17032        for (color_fetcher, ranges) in self.gutter_highlights.values() {
17033            let color = color_fetcher(cx);
17034            let start_ix = match ranges.binary_search_by(|probe| {
17035                let cmp = probe
17036                    .end
17037                    .cmp(&search_range.start, &display_snapshot.buffer_snapshot);
17038                if cmp.is_gt() {
17039                    Ordering::Greater
17040                } else {
17041                    Ordering::Less
17042                }
17043            }) {
17044                Ok(i) | Err(i) => i,
17045            };
17046            for range in &ranges[start_ix..] {
17047                if range
17048                    .start
17049                    .cmp(&search_range.end, &display_snapshot.buffer_snapshot)
17050                    .is_ge()
17051                {
17052                    break;
17053                }
17054
17055                let start = range.start.to_display_point(display_snapshot);
17056                let end = range.end.to_display_point(display_snapshot);
17057                results.push((start..end, color))
17058            }
17059        }
17060        results
17061    }
17062
17063    /// Get the text ranges corresponding to the redaction query
17064    pub fn redacted_ranges(
17065        &self,
17066        search_range: Range<Anchor>,
17067        display_snapshot: &DisplaySnapshot,
17068        cx: &App,
17069    ) -> Vec<Range<DisplayPoint>> {
17070        display_snapshot
17071            .buffer_snapshot
17072            .redacted_ranges(search_range, |file| {
17073                if let Some(file) = file {
17074                    file.is_private()
17075                        && EditorSettings::get(
17076                            Some(SettingsLocation {
17077                                worktree_id: file.worktree_id(cx),
17078                                path: file.path().as_ref(),
17079                            }),
17080                            cx,
17081                        )
17082                        .redact_private_values
17083                } else {
17084                    false
17085                }
17086            })
17087            .map(|range| {
17088                range.start.to_display_point(display_snapshot)
17089                    ..range.end.to_display_point(display_snapshot)
17090            })
17091            .collect()
17092    }
17093
17094    pub fn highlight_text<T: 'static>(
17095        &mut self,
17096        ranges: Vec<Range<Anchor>>,
17097        style: HighlightStyle,
17098        cx: &mut Context<Self>,
17099    ) {
17100        self.display_map.update(cx, |map, _| {
17101            map.highlight_text(TypeId::of::<T>(), ranges, style)
17102        });
17103        cx.notify();
17104    }
17105
17106    pub(crate) fn highlight_inlays<T: 'static>(
17107        &mut self,
17108        highlights: Vec<InlayHighlight>,
17109        style: HighlightStyle,
17110        cx: &mut Context<Self>,
17111    ) {
17112        self.display_map.update(cx, |map, _| {
17113            map.highlight_inlays(TypeId::of::<T>(), highlights, style)
17114        });
17115        cx.notify();
17116    }
17117
17118    pub fn text_highlights<'a, T: 'static>(
17119        &'a self,
17120        cx: &'a App,
17121    ) -> Option<(HighlightStyle, &'a [Range<Anchor>])> {
17122        self.display_map.read(cx).text_highlights(TypeId::of::<T>())
17123    }
17124
17125    pub fn clear_highlights<T: 'static>(&mut self, cx: &mut Context<Self>) {
17126        let cleared = self
17127            .display_map
17128            .update(cx, |map, _| map.clear_highlights(TypeId::of::<T>()));
17129        if cleared {
17130            cx.notify();
17131        }
17132    }
17133
17134    pub fn show_local_cursors(&self, window: &mut Window, cx: &mut App) -> bool {
17135        (self.read_only(cx) || self.blink_manager.read(cx).visible())
17136            && self.focus_handle.is_focused(window)
17137    }
17138
17139    pub fn set_show_cursor_when_unfocused(&mut self, is_enabled: bool, cx: &mut Context<Self>) {
17140        self.show_cursor_when_unfocused = is_enabled;
17141        cx.notify();
17142    }
17143
17144    fn on_buffer_changed(&mut self, _: Entity<MultiBuffer>, cx: &mut Context<Self>) {
17145        cx.notify();
17146    }
17147
17148    fn on_buffer_event(
17149        &mut self,
17150        multibuffer: &Entity<MultiBuffer>,
17151        event: &multi_buffer::Event,
17152        window: &mut Window,
17153        cx: &mut Context<Self>,
17154    ) {
17155        match event {
17156            multi_buffer::Event::Edited {
17157                singleton_buffer_edited,
17158                edited_buffer: buffer_edited,
17159            } => {
17160                self.scrollbar_marker_state.dirty = true;
17161                self.active_indent_guides_state.dirty = true;
17162                self.refresh_active_diagnostics(cx);
17163                self.refresh_code_actions(window, cx);
17164                if self.has_active_inline_completion() {
17165                    self.update_visible_inline_completion(window, cx);
17166                }
17167                if let Some(buffer) = buffer_edited {
17168                    let buffer_id = buffer.read(cx).remote_id();
17169                    if !self.registered_buffers.contains_key(&buffer_id) {
17170                        if let Some(project) = self.project.as_ref() {
17171                            project.update(cx, |project, cx| {
17172                                self.registered_buffers.insert(
17173                                    buffer_id,
17174                                    project.register_buffer_with_language_servers(&buffer, cx),
17175                                );
17176                            })
17177                        }
17178                    }
17179                }
17180                cx.emit(EditorEvent::BufferEdited);
17181                cx.emit(SearchEvent::MatchesInvalidated);
17182                if *singleton_buffer_edited {
17183                    if let Some(project) = &self.project {
17184                        #[allow(clippy::mutable_key_type)]
17185                        let languages_affected = multibuffer.update(cx, |multibuffer, cx| {
17186                            multibuffer
17187                                .all_buffers()
17188                                .into_iter()
17189                                .filter_map(|buffer| {
17190                                    buffer.update(cx, |buffer, cx| {
17191                                        let language = buffer.language()?;
17192                                        let should_discard = project.update(cx, |project, cx| {
17193                                            project.is_local()
17194                                                && !project.has_language_servers_for(buffer, cx)
17195                                        });
17196                                        should_discard.not().then_some(language.clone())
17197                                    })
17198                                })
17199                                .collect::<HashSet<_>>()
17200                        });
17201                        if !languages_affected.is_empty() {
17202                            self.refresh_inlay_hints(
17203                                InlayHintRefreshReason::BufferEdited(languages_affected),
17204                                cx,
17205                            );
17206                        }
17207                    }
17208                }
17209
17210                let Some(project) = &self.project else { return };
17211                let (telemetry, is_via_ssh) = {
17212                    let project = project.read(cx);
17213                    let telemetry = project.client().telemetry().clone();
17214                    let is_via_ssh = project.is_via_ssh();
17215                    (telemetry, is_via_ssh)
17216                };
17217                refresh_linked_ranges(self, window, cx);
17218                telemetry.log_edit_event("editor", is_via_ssh);
17219            }
17220            multi_buffer::Event::ExcerptsAdded {
17221                buffer,
17222                predecessor,
17223                excerpts,
17224            } => {
17225                self.tasks_update_task = Some(self.refresh_runnables(window, cx));
17226                let buffer_id = buffer.read(cx).remote_id();
17227                if self.buffer.read(cx).diff_for(buffer_id).is_none() {
17228                    if let Some(project) = &self.project {
17229                        get_uncommitted_diff_for_buffer(
17230                            project,
17231                            [buffer.clone()],
17232                            self.buffer.clone(),
17233                            cx,
17234                        )
17235                        .detach();
17236                    }
17237                }
17238                cx.emit(EditorEvent::ExcerptsAdded {
17239                    buffer: buffer.clone(),
17240                    predecessor: *predecessor,
17241                    excerpts: excerpts.clone(),
17242                });
17243                self.refresh_inlay_hints(InlayHintRefreshReason::NewLinesShown, cx);
17244            }
17245            multi_buffer::Event::ExcerptsRemoved { ids } => {
17246                self.refresh_inlay_hints(InlayHintRefreshReason::ExcerptsRemoved(ids.clone()), cx);
17247                let buffer = self.buffer.read(cx);
17248                self.registered_buffers
17249                    .retain(|buffer_id, _| buffer.buffer(*buffer_id).is_some());
17250                jsx_tag_auto_close::refresh_enabled_in_any_buffer(self, multibuffer, cx);
17251                cx.emit(EditorEvent::ExcerptsRemoved { ids: ids.clone() })
17252            }
17253            multi_buffer::Event::ExcerptsEdited {
17254                excerpt_ids,
17255                buffer_ids,
17256            } => {
17257                self.display_map.update(cx, |map, cx| {
17258                    map.unfold_buffers(buffer_ids.iter().copied(), cx)
17259                });
17260                cx.emit(EditorEvent::ExcerptsEdited {
17261                    ids: excerpt_ids.clone(),
17262                })
17263            }
17264            multi_buffer::Event::ExcerptsExpanded { ids } => {
17265                self.refresh_inlay_hints(InlayHintRefreshReason::NewLinesShown, cx);
17266                cx.emit(EditorEvent::ExcerptsExpanded { ids: ids.clone() })
17267            }
17268            multi_buffer::Event::Reparsed(buffer_id) => {
17269                self.tasks_update_task = Some(self.refresh_runnables(window, cx));
17270                jsx_tag_auto_close::refresh_enabled_in_any_buffer(self, multibuffer, cx);
17271
17272                cx.emit(EditorEvent::Reparsed(*buffer_id));
17273            }
17274            multi_buffer::Event::DiffHunksToggled => {
17275                self.tasks_update_task = Some(self.refresh_runnables(window, cx));
17276            }
17277            multi_buffer::Event::LanguageChanged(buffer_id) => {
17278                linked_editing_ranges::refresh_linked_ranges(self, window, cx);
17279                jsx_tag_auto_close::refresh_enabled_in_any_buffer(self, multibuffer, cx);
17280                cx.emit(EditorEvent::Reparsed(*buffer_id));
17281                cx.notify();
17282            }
17283            multi_buffer::Event::DirtyChanged => cx.emit(EditorEvent::DirtyChanged),
17284            multi_buffer::Event::Saved => cx.emit(EditorEvent::Saved),
17285            multi_buffer::Event::FileHandleChanged
17286            | multi_buffer::Event::Reloaded
17287            | multi_buffer::Event::BufferDiffChanged => cx.emit(EditorEvent::TitleChanged),
17288            multi_buffer::Event::Closed => cx.emit(EditorEvent::Closed),
17289            multi_buffer::Event::DiagnosticsUpdated => {
17290                self.refresh_active_diagnostics(cx);
17291                self.refresh_inline_diagnostics(true, window, cx);
17292                self.scrollbar_marker_state.dirty = true;
17293                cx.notify();
17294            }
17295            _ => {}
17296        };
17297    }
17298
17299    fn on_display_map_changed(
17300        &mut self,
17301        _: Entity<DisplayMap>,
17302        _: &mut Window,
17303        cx: &mut Context<Self>,
17304    ) {
17305        cx.notify();
17306    }
17307
17308    fn settings_changed(&mut self, window: &mut Window, cx: &mut Context<Self>) {
17309        self.tasks_update_task = Some(self.refresh_runnables(window, cx));
17310        self.update_edit_prediction_settings(cx);
17311        self.refresh_inline_completion(true, false, window, cx);
17312        self.refresh_inlay_hints(
17313            InlayHintRefreshReason::SettingsChange(inlay_hint_settings(
17314                self.selections.newest_anchor().head(),
17315                &self.buffer.read(cx).snapshot(cx),
17316                cx,
17317            )),
17318            cx,
17319        );
17320
17321        let old_cursor_shape = self.cursor_shape;
17322
17323        {
17324            let editor_settings = EditorSettings::get_global(cx);
17325            self.scroll_manager.vertical_scroll_margin = editor_settings.vertical_scroll_margin;
17326            self.show_breadcrumbs = editor_settings.toolbar.breadcrumbs;
17327            self.cursor_shape = editor_settings.cursor_shape.unwrap_or_default();
17328            self.hide_mouse_mode = editor_settings.hide_mouse.unwrap_or_default();
17329        }
17330
17331        if old_cursor_shape != self.cursor_shape {
17332            cx.emit(EditorEvent::CursorShapeChanged);
17333        }
17334
17335        let project_settings = ProjectSettings::get_global(cx);
17336        self.serialize_dirty_buffers = project_settings.session.restore_unsaved_buffers;
17337
17338        if self.mode.is_full() {
17339            let show_inline_diagnostics = project_settings.diagnostics.inline.enabled;
17340            let inline_blame_enabled = project_settings.git.inline_blame_enabled();
17341            if self.show_inline_diagnostics != show_inline_diagnostics {
17342                self.show_inline_diagnostics = show_inline_diagnostics;
17343                self.refresh_inline_diagnostics(false, window, cx);
17344            }
17345
17346            if self.git_blame_inline_enabled != inline_blame_enabled {
17347                self.toggle_git_blame_inline_internal(false, window, cx);
17348            }
17349        }
17350
17351        cx.notify();
17352    }
17353
17354    pub fn set_searchable(&mut self, searchable: bool) {
17355        self.searchable = searchable;
17356    }
17357
17358    pub fn searchable(&self) -> bool {
17359        self.searchable
17360    }
17361
17362    fn open_proposed_changes_editor(
17363        &mut self,
17364        _: &OpenProposedChangesEditor,
17365        window: &mut Window,
17366        cx: &mut Context<Self>,
17367    ) {
17368        let Some(workspace) = self.workspace() else {
17369            cx.propagate();
17370            return;
17371        };
17372
17373        let selections = self.selections.all::<usize>(cx);
17374        let multi_buffer = self.buffer.read(cx);
17375        let multi_buffer_snapshot = multi_buffer.snapshot(cx);
17376        let mut new_selections_by_buffer = HashMap::default();
17377        for selection in selections {
17378            for (buffer, range, _) in
17379                multi_buffer_snapshot.range_to_buffer_ranges(selection.start..selection.end)
17380            {
17381                let mut range = range.to_point(buffer);
17382                range.start.column = 0;
17383                range.end.column = buffer.line_len(range.end.row);
17384                new_selections_by_buffer
17385                    .entry(multi_buffer.buffer(buffer.remote_id()).unwrap())
17386                    .or_insert(Vec::new())
17387                    .push(range)
17388            }
17389        }
17390
17391        let proposed_changes_buffers = new_selections_by_buffer
17392            .into_iter()
17393            .map(|(buffer, ranges)| ProposedChangeLocation { buffer, ranges })
17394            .collect::<Vec<_>>();
17395        let proposed_changes_editor = cx.new(|cx| {
17396            ProposedChangesEditor::new(
17397                "Proposed changes",
17398                proposed_changes_buffers,
17399                self.project.clone(),
17400                window,
17401                cx,
17402            )
17403        });
17404
17405        window.defer(cx, move |window, cx| {
17406            workspace.update(cx, |workspace, cx| {
17407                workspace.active_pane().update(cx, |pane, cx| {
17408                    pane.add_item(
17409                        Box::new(proposed_changes_editor),
17410                        true,
17411                        true,
17412                        None,
17413                        window,
17414                        cx,
17415                    );
17416                });
17417            });
17418        });
17419    }
17420
17421    pub fn open_excerpts_in_split(
17422        &mut self,
17423        _: &OpenExcerptsSplit,
17424        window: &mut Window,
17425        cx: &mut Context<Self>,
17426    ) {
17427        self.open_excerpts_common(None, true, window, cx)
17428    }
17429
17430    pub fn open_excerpts(&mut self, _: &OpenExcerpts, window: &mut Window, cx: &mut Context<Self>) {
17431        self.open_excerpts_common(None, false, window, cx)
17432    }
17433
17434    fn open_excerpts_common(
17435        &mut self,
17436        jump_data: Option<JumpData>,
17437        split: bool,
17438        window: &mut Window,
17439        cx: &mut Context<Self>,
17440    ) {
17441        let Some(workspace) = self.workspace() else {
17442            cx.propagate();
17443            return;
17444        };
17445
17446        if self.buffer.read(cx).is_singleton() {
17447            cx.propagate();
17448            return;
17449        }
17450
17451        let mut new_selections_by_buffer = HashMap::default();
17452        match &jump_data {
17453            Some(JumpData::MultiBufferPoint {
17454                excerpt_id,
17455                position,
17456                anchor,
17457                line_offset_from_top,
17458            }) => {
17459                let multi_buffer_snapshot = self.buffer.read(cx).snapshot(cx);
17460                if let Some(buffer) = multi_buffer_snapshot
17461                    .buffer_id_for_excerpt(*excerpt_id)
17462                    .and_then(|buffer_id| self.buffer.read(cx).buffer(buffer_id))
17463                {
17464                    let buffer_snapshot = buffer.read(cx).snapshot();
17465                    let jump_to_point = if buffer_snapshot.can_resolve(anchor) {
17466                        language::ToPoint::to_point(anchor, &buffer_snapshot)
17467                    } else {
17468                        buffer_snapshot.clip_point(*position, Bias::Left)
17469                    };
17470                    let jump_to_offset = buffer_snapshot.point_to_offset(jump_to_point);
17471                    new_selections_by_buffer.insert(
17472                        buffer,
17473                        (
17474                            vec![jump_to_offset..jump_to_offset],
17475                            Some(*line_offset_from_top),
17476                        ),
17477                    );
17478                }
17479            }
17480            Some(JumpData::MultiBufferRow {
17481                row,
17482                line_offset_from_top,
17483            }) => {
17484                let point = MultiBufferPoint::new(row.0, 0);
17485                if let Some((buffer, buffer_point, _)) =
17486                    self.buffer.read(cx).point_to_buffer_point(point, cx)
17487                {
17488                    let buffer_offset = buffer.read(cx).point_to_offset(buffer_point);
17489                    new_selections_by_buffer
17490                        .entry(buffer)
17491                        .or_insert((Vec::new(), Some(*line_offset_from_top)))
17492                        .0
17493                        .push(buffer_offset..buffer_offset)
17494                }
17495            }
17496            None => {
17497                let selections = self.selections.all::<usize>(cx);
17498                let multi_buffer = self.buffer.read(cx);
17499                for selection in selections {
17500                    for (snapshot, range, _, anchor) in multi_buffer
17501                        .snapshot(cx)
17502                        .range_to_buffer_ranges_with_deleted_hunks(selection.range())
17503                    {
17504                        if let Some(anchor) = anchor {
17505                            // selection is in a deleted hunk
17506                            let Some(buffer_id) = anchor.buffer_id else {
17507                                continue;
17508                            };
17509                            let Some(buffer_handle) = multi_buffer.buffer(buffer_id) else {
17510                                continue;
17511                            };
17512                            let offset = text::ToOffset::to_offset(
17513                                &anchor.text_anchor,
17514                                &buffer_handle.read(cx).snapshot(),
17515                            );
17516                            let range = offset..offset;
17517                            new_selections_by_buffer
17518                                .entry(buffer_handle)
17519                                .or_insert((Vec::new(), None))
17520                                .0
17521                                .push(range)
17522                        } else {
17523                            let Some(buffer_handle) = multi_buffer.buffer(snapshot.remote_id())
17524                            else {
17525                                continue;
17526                            };
17527                            new_selections_by_buffer
17528                                .entry(buffer_handle)
17529                                .or_insert((Vec::new(), None))
17530                                .0
17531                                .push(range)
17532                        }
17533                    }
17534                }
17535            }
17536        }
17537
17538        new_selections_by_buffer
17539            .retain(|buffer, _| Self::can_open_excerpts_in_file(buffer.read(cx).file()));
17540
17541        if new_selections_by_buffer.is_empty() {
17542            return;
17543        }
17544
17545        // We defer the pane interaction because we ourselves are a workspace item
17546        // and activating a new item causes the pane to call a method on us reentrantly,
17547        // which panics if we're on the stack.
17548        window.defer(cx, move |window, cx| {
17549            workspace.update(cx, |workspace, cx| {
17550                let pane = if split {
17551                    workspace.adjacent_pane(window, cx)
17552                } else {
17553                    workspace.active_pane().clone()
17554                };
17555
17556                for (buffer, (ranges, scroll_offset)) in new_selections_by_buffer {
17557                    let editor = buffer
17558                        .read(cx)
17559                        .file()
17560                        .is_none()
17561                        .then(|| {
17562                            // Handle file-less buffers separately: those are not really the project items, so won't have a project path or entity id,
17563                            // so `workspace.open_project_item` will never find them, always opening a new editor.
17564                            // Instead, we try to activate the existing editor in the pane first.
17565                            let (editor, pane_item_index) =
17566                                pane.read(cx).items().enumerate().find_map(|(i, item)| {
17567                                    let editor = item.downcast::<Editor>()?;
17568                                    let singleton_buffer =
17569                                        editor.read(cx).buffer().read(cx).as_singleton()?;
17570                                    if singleton_buffer == buffer {
17571                                        Some((editor, i))
17572                                    } else {
17573                                        None
17574                                    }
17575                                })?;
17576                            pane.update(cx, |pane, cx| {
17577                                pane.activate_item(pane_item_index, true, true, window, cx)
17578                            });
17579                            Some(editor)
17580                        })
17581                        .flatten()
17582                        .unwrap_or_else(|| {
17583                            workspace.open_project_item::<Self>(
17584                                pane.clone(),
17585                                buffer,
17586                                true,
17587                                true,
17588                                window,
17589                                cx,
17590                            )
17591                        });
17592
17593                    editor.update(cx, |editor, cx| {
17594                        let autoscroll = match scroll_offset {
17595                            Some(scroll_offset) => Autoscroll::top_relative(scroll_offset as usize),
17596                            None => Autoscroll::newest(),
17597                        };
17598                        let nav_history = editor.nav_history.take();
17599                        editor.change_selections(Some(autoscroll), window, cx, |s| {
17600                            s.select_ranges(ranges);
17601                        });
17602                        editor.nav_history = nav_history;
17603                    });
17604                }
17605            })
17606        });
17607    }
17608
17609    // For now, don't allow opening excerpts in buffers that aren't backed by
17610    // regular project files.
17611    fn can_open_excerpts_in_file(file: Option<&Arc<dyn language::File>>) -> bool {
17612        file.map_or(true, |file| project::File::from_dyn(Some(file)).is_some())
17613    }
17614
17615    fn marked_text_ranges(&self, cx: &App) -> Option<Vec<Range<OffsetUtf16>>> {
17616        let snapshot = self.buffer.read(cx).read(cx);
17617        let (_, ranges) = self.text_highlights::<InputComposition>(cx)?;
17618        Some(
17619            ranges
17620                .iter()
17621                .map(move |range| {
17622                    range.start.to_offset_utf16(&snapshot)..range.end.to_offset_utf16(&snapshot)
17623                })
17624                .collect(),
17625        )
17626    }
17627
17628    fn selection_replacement_ranges(
17629        &self,
17630        range: Range<OffsetUtf16>,
17631        cx: &mut App,
17632    ) -> Vec<Range<OffsetUtf16>> {
17633        let selections = self.selections.all::<OffsetUtf16>(cx);
17634        let newest_selection = selections
17635            .iter()
17636            .max_by_key(|selection| selection.id)
17637            .unwrap();
17638        let start_delta = range.start.0 as isize - newest_selection.start.0 as isize;
17639        let end_delta = range.end.0 as isize - newest_selection.end.0 as isize;
17640        let snapshot = self.buffer.read(cx).read(cx);
17641        selections
17642            .into_iter()
17643            .map(|mut selection| {
17644                selection.start.0 =
17645                    (selection.start.0 as isize).saturating_add(start_delta) as usize;
17646                selection.end.0 = (selection.end.0 as isize).saturating_add(end_delta) as usize;
17647                snapshot.clip_offset_utf16(selection.start, Bias::Left)
17648                    ..snapshot.clip_offset_utf16(selection.end, Bias::Right)
17649            })
17650            .collect()
17651    }
17652
17653    fn report_editor_event(
17654        &self,
17655        event_type: &'static str,
17656        file_extension: Option<String>,
17657        cx: &App,
17658    ) {
17659        if cfg!(any(test, feature = "test-support")) {
17660            return;
17661        }
17662
17663        let Some(project) = &self.project else { return };
17664
17665        // If None, we are in a file without an extension
17666        let file = self
17667            .buffer
17668            .read(cx)
17669            .as_singleton()
17670            .and_then(|b| b.read(cx).file());
17671        let file_extension = file_extension.or(file
17672            .as_ref()
17673            .and_then(|file| Path::new(file.file_name(cx)).extension())
17674            .and_then(|e| e.to_str())
17675            .map(|a| a.to_string()));
17676
17677        let vim_mode = cx
17678            .global::<SettingsStore>()
17679            .raw_user_settings()
17680            .get("vim_mode")
17681            == Some(&serde_json::Value::Bool(true));
17682
17683        let edit_predictions_provider = all_language_settings(file, cx).edit_predictions.provider;
17684        let copilot_enabled = edit_predictions_provider
17685            == language::language_settings::EditPredictionProvider::Copilot;
17686        let copilot_enabled_for_language = self
17687            .buffer
17688            .read(cx)
17689            .language_settings(cx)
17690            .show_edit_predictions;
17691
17692        let project = project.read(cx);
17693        telemetry::event!(
17694            event_type,
17695            file_extension,
17696            vim_mode,
17697            copilot_enabled,
17698            copilot_enabled_for_language,
17699            edit_predictions_provider,
17700            is_via_ssh = project.is_via_ssh(),
17701        );
17702    }
17703
17704    /// Copy the highlighted chunks to the clipboard as JSON. The format is an array of lines,
17705    /// with each line being an array of {text, highlight} objects.
17706    fn copy_highlight_json(
17707        &mut self,
17708        _: &CopyHighlightJson,
17709        window: &mut Window,
17710        cx: &mut Context<Self>,
17711    ) {
17712        #[derive(Serialize)]
17713        struct Chunk<'a> {
17714            text: String,
17715            highlight: Option<&'a str>,
17716        }
17717
17718        let snapshot = self.buffer.read(cx).snapshot(cx);
17719        let range = self
17720            .selected_text_range(false, window, cx)
17721            .and_then(|selection| {
17722                if selection.range.is_empty() {
17723                    None
17724                } else {
17725                    Some(selection.range)
17726                }
17727            })
17728            .unwrap_or_else(|| 0..snapshot.len());
17729
17730        let chunks = snapshot.chunks(range, true);
17731        let mut lines = Vec::new();
17732        let mut line: VecDeque<Chunk> = VecDeque::new();
17733
17734        let Some(style) = self.style.as_ref() else {
17735            return;
17736        };
17737
17738        for chunk in chunks {
17739            let highlight = chunk
17740                .syntax_highlight_id
17741                .and_then(|id| id.name(&style.syntax));
17742            let mut chunk_lines = chunk.text.split('\n').peekable();
17743            while let Some(text) = chunk_lines.next() {
17744                let mut merged_with_last_token = false;
17745                if let Some(last_token) = line.back_mut() {
17746                    if last_token.highlight == highlight {
17747                        last_token.text.push_str(text);
17748                        merged_with_last_token = true;
17749                    }
17750                }
17751
17752                if !merged_with_last_token {
17753                    line.push_back(Chunk {
17754                        text: text.into(),
17755                        highlight,
17756                    });
17757                }
17758
17759                if chunk_lines.peek().is_some() {
17760                    if line.len() > 1 && line.front().unwrap().text.is_empty() {
17761                        line.pop_front();
17762                    }
17763                    if line.len() > 1 && line.back().unwrap().text.is_empty() {
17764                        line.pop_back();
17765                    }
17766
17767                    lines.push(mem::take(&mut line));
17768                }
17769            }
17770        }
17771
17772        let Some(lines) = serde_json::to_string_pretty(&lines).log_err() else {
17773            return;
17774        };
17775        cx.write_to_clipboard(ClipboardItem::new_string(lines));
17776    }
17777
17778    pub fn open_context_menu(
17779        &mut self,
17780        _: &OpenContextMenu,
17781        window: &mut Window,
17782        cx: &mut Context<Self>,
17783    ) {
17784        self.request_autoscroll(Autoscroll::newest(), cx);
17785        let position = self.selections.newest_display(cx).start;
17786        mouse_context_menu::deploy_context_menu(self, None, position, window, cx);
17787    }
17788
17789    pub fn inlay_hint_cache(&self) -> &InlayHintCache {
17790        &self.inlay_hint_cache
17791    }
17792
17793    pub fn replay_insert_event(
17794        &mut self,
17795        text: &str,
17796        relative_utf16_range: Option<Range<isize>>,
17797        window: &mut Window,
17798        cx: &mut Context<Self>,
17799    ) {
17800        if !self.input_enabled {
17801            cx.emit(EditorEvent::InputIgnored { text: text.into() });
17802            return;
17803        }
17804        if let Some(relative_utf16_range) = relative_utf16_range {
17805            let selections = self.selections.all::<OffsetUtf16>(cx);
17806            self.change_selections(None, window, cx, |s| {
17807                let new_ranges = selections.into_iter().map(|range| {
17808                    let start = OffsetUtf16(
17809                        range
17810                            .head()
17811                            .0
17812                            .saturating_add_signed(relative_utf16_range.start),
17813                    );
17814                    let end = OffsetUtf16(
17815                        range
17816                            .head()
17817                            .0
17818                            .saturating_add_signed(relative_utf16_range.end),
17819                    );
17820                    start..end
17821                });
17822                s.select_ranges(new_ranges);
17823            });
17824        }
17825
17826        self.handle_input(text, window, cx);
17827    }
17828
17829    pub fn supports_inlay_hints(&self, cx: &mut App) -> bool {
17830        let Some(provider) = self.semantics_provider.as_ref() else {
17831            return false;
17832        };
17833
17834        let mut supports = false;
17835        self.buffer().update(cx, |this, cx| {
17836            this.for_each_buffer(|buffer| {
17837                supports |= provider.supports_inlay_hints(buffer, cx);
17838            });
17839        });
17840
17841        supports
17842    }
17843
17844    pub fn is_focused(&self, window: &Window) -> bool {
17845        self.focus_handle.is_focused(window)
17846    }
17847
17848    fn handle_focus(&mut self, window: &mut Window, cx: &mut Context<Self>) {
17849        cx.emit(EditorEvent::Focused);
17850
17851        if let Some(descendant) = self
17852            .last_focused_descendant
17853            .take()
17854            .and_then(|descendant| descendant.upgrade())
17855        {
17856            window.focus(&descendant);
17857        } else {
17858            if let Some(blame) = self.blame.as_ref() {
17859                blame.update(cx, GitBlame::focus)
17860            }
17861
17862            self.blink_manager.update(cx, BlinkManager::enable);
17863            self.show_cursor_names(window, cx);
17864            self.buffer.update(cx, |buffer, cx| {
17865                buffer.finalize_last_transaction(cx);
17866                if self.leader_peer_id.is_none() {
17867                    buffer.set_active_selections(
17868                        &self.selections.disjoint_anchors(),
17869                        self.selections.line_mode,
17870                        self.cursor_shape,
17871                        cx,
17872                    );
17873                }
17874            });
17875        }
17876    }
17877
17878    fn handle_focus_in(&mut self, _: &mut Window, cx: &mut Context<Self>) {
17879        cx.emit(EditorEvent::FocusedIn)
17880    }
17881
17882    fn handle_focus_out(
17883        &mut self,
17884        event: FocusOutEvent,
17885        _window: &mut Window,
17886        cx: &mut Context<Self>,
17887    ) {
17888        if event.blurred != self.focus_handle {
17889            self.last_focused_descendant = Some(event.blurred);
17890        }
17891        self.refresh_inlay_hints(InlayHintRefreshReason::ModifiersChanged(false), cx);
17892    }
17893
17894    pub fn handle_blur(&mut self, window: &mut Window, cx: &mut Context<Self>) {
17895        self.blink_manager.update(cx, BlinkManager::disable);
17896        self.buffer
17897            .update(cx, |buffer, cx| buffer.remove_active_selections(cx));
17898
17899        if let Some(blame) = self.blame.as_ref() {
17900            blame.update(cx, GitBlame::blur)
17901        }
17902        if !self.hover_state.focused(window, cx) {
17903            hide_hover(self, cx);
17904        }
17905        if !self
17906            .context_menu
17907            .borrow()
17908            .as_ref()
17909            .is_some_and(|context_menu| context_menu.focused(window, cx))
17910        {
17911            self.hide_context_menu(window, cx);
17912        }
17913        self.discard_inline_completion(false, cx);
17914        cx.emit(EditorEvent::Blurred);
17915        cx.notify();
17916    }
17917
17918    pub fn register_action<A: Action>(
17919        &mut self,
17920        listener: impl Fn(&A, &mut Window, &mut App) + 'static,
17921    ) -> Subscription {
17922        let id = self.next_editor_action_id.post_inc();
17923        let listener = Arc::new(listener);
17924        self.editor_actions.borrow_mut().insert(
17925            id,
17926            Box::new(move |window, _| {
17927                let listener = listener.clone();
17928                window.on_action(TypeId::of::<A>(), move |action, phase, window, cx| {
17929                    let action = action.downcast_ref().unwrap();
17930                    if phase == DispatchPhase::Bubble {
17931                        listener(action, window, cx)
17932                    }
17933                })
17934            }),
17935        );
17936
17937        let editor_actions = self.editor_actions.clone();
17938        Subscription::new(move || {
17939            editor_actions.borrow_mut().remove(&id);
17940        })
17941    }
17942
17943    pub fn file_header_size(&self) -> u32 {
17944        FILE_HEADER_HEIGHT
17945    }
17946
17947    pub fn restore(
17948        &mut self,
17949        revert_changes: HashMap<BufferId, Vec<(Range<text::Anchor>, Rope)>>,
17950        window: &mut Window,
17951        cx: &mut Context<Self>,
17952    ) {
17953        let workspace = self.workspace();
17954        let project = self.project.as_ref();
17955        let save_tasks = self.buffer().update(cx, |multi_buffer, cx| {
17956            let mut tasks = Vec::new();
17957            for (buffer_id, changes) in revert_changes {
17958                if let Some(buffer) = multi_buffer.buffer(buffer_id) {
17959                    buffer.update(cx, |buffer, cx| {
17960                        buffer.edit(
17961                            changes
17962                                .into_iter()
17963                                .map(|(range, text)| (range, text.to_string())),
17964                            None,
17965                            cx,
17966                        );
17967                    });
17968
17969                    if let Some(project) =
17970                        project.filter(|_| multi_buffer.all_diff_hunks_expanded())
17971                    {
17972                        project.update(cx, |project, cx| {
17973                            tasks.push((buffer.clone(), project.save_buffer(buffer, cx)));
17974                        })
17975                    }
17976                }
17977            }
17978            tasks
17979        });
17980        cx.spawn_in(window, async move |_, cx| {
17981            for (buffer, task) in save_tasks {
17982                let result = task.await;
17983                if result.is_err() {
17984                    let Some(path) = buffer
17985                        .read_with(cx, |buffer, cx| buffer.project_path(cx))
17986                        .ok()
17987                    else {
17988                        continue;
17989                    };
17990                    if let Some((workspace, path)) = workspace.as_ref().zip(path) {
17991                        let Some(task) = cx
17992                            .update_window_entity(&workspace, |workspace, window, cx| {
17993                                workspace
17994                                    .open_path_preview(path, None, false, false, false, window, cx)
17995                            })
17996                            .ok()
17997                        else {
17998                            continue;
17999                        };
18000                        task.await.log_err();
18001                    }
18002                }
18003            }
18004        })
18005        .detach();
18006        self.change_selections(None, window, cx, |selections| selections.refresh());
18007    }
18008
18009    pub fn to_pixel_point(
18010        &self,
18011        source: multi_buffer::Anchor,
18012        editor_snapshot: &EditorSnapshot,
18013        window: &mut Window,
18014    ) -> Option<gpui::Point<Pixels>> {
18015        let source_point = source.to_display_point(editor_snapshot);
18016        self.display_to_pixel_point(source_point, editor_snapshot, window)
18017    }
18018
18019    pub fn display_to_pixel_point(
18020        &self,
18021        source: DisplayPoint,
18022        editor_snapshot: &EditorSnapshot,
18023        window: &mut Window,
18024    ) -> Option<gpui::Point<Pixels>> {
18025        let line_height = self.style()?.text.line_height_in_pixels(window.rem_size());
18026        let text_layout_details = self.text_layout_details(window);
18027        let scroll_top = text_layout_details
18028            .scroll_anchor
18029            .scroll_position(editor_snapshot)
18030            .y;
18031
18032        if source.row().as_f32() < scroll_top.floor() {
18033            return None;
18034        }
18035        let source_x = editor_snapshot.x_for_display_point(source, &text_layout_details);
18036        let source_y = line_height * (source.row().as_f32() - scroll_top);
18037        Some(gpui::Point::new(source_x, source_y))
18038    }
18039
18040    pub fn has_visible_completions_menu(&self) -> bool {
18041        !self.edit_prediction_preview_is_active()
18042            && self.context_menu.borrow().as_ref().map_or(false, |menu| {
18043                menu.visible() && matches!(menu, CodeContextMenu::Completions(_))
18044            })
18045    }
18046
18047    pub fn register_addon<T: Addon>(&mut self, instance: T) {
18048        self.addons
18049            .insert(std::any::TypeId::of::<T>(), Box::new(instance));
18050    }
18051
18052    pub fn unregister_addon<T: Addon>(&mut self) {
18053        self.addons.remove(&std::any::TypeId::of::<T>());
18054    }
18055
18056    pub fn addon<T: Addon>(&self) -> Option<&T> {
18057        let type_id = std::any::TypeId::of::<T>();
18058        self.addons
18059            .get(&type_id)
18060            .and_then(|item| item.to_any().downcast_ref::<T>())
18061    }
18062
18063    fn character_size(&self, window: &mut Window) -> gpui::Size<Pixels> {
18064        let text_layout_details = self.text_layout_details(window);
18065        let style = &text_layout_details.editor_style;
18066        let font_id = window.text_system().resolve_font(&style.text.font());
18067        let font_size = style.text.font_size.to_pixels(window.rem_size());
18068        let line_height = style.text.line_height_in_pixels(window.rem_size());
18069        let em_width = window.text_system().em_width(font_id, font_size).unwrap();
18070
18071        gpui::Size::new(em_width, line_height)
18072    }
18073
18074    pub fn wait_for_diff_to_load(&self) -> Option<Shared<Task<()>>> {
18075        self.load_diff_task.clone()
18076    }
18077
18078    fn read_metadata_from_db(
18079        &mut self,
18080        item_id: u64,
18081        workspace_id: WorkspaceId,
18082        window: &mut Window,
18083        cx: &mut Context<Editor>,
18084    ) {
18085        if self.is_singleton(cx)
18086            && WorkspaceSettings::get(None, cx).restore_on_startup != RestoreOnStartupBehavior::None
18087        {
18088            let buffer_snapshot = OnceCell::new();
18089
18090            if let Some(folds) = DB.get_editor_folds(item_id, workspace_id).log_err() {
18091                if !folds.is_empty() {
18092                    let snapshot =
18093                        buffer_snapshot.get_or_init(|| self.buffer.read(cx).snapshot(cx));
18094                    self.fold_ranges(
18095                        folds
18096                            .into_iter()
18097                            .map(|(start, end)| {
18098                                snapshot.clip_offset(start, Bias::Left)
18099                                    ..snapshot.clip_offset(end, Bias::Right)
18100                            })
18101                            .collect(),
18102                        false,
18103                        window,
18104                        cx,
18105                    );
18106                }
18107            }
18108
18109            if let Some(selections) = DB.get_editor_selections(item_id, workspace_id).log_err() {
18110                if !selections.is_empty() {
18111                    let snapshot =
18112                        buffer_snapshot.get_or_init(|| self.buffer.read(cx).snapshot(cx));
18113                    self.change_selections(None, window, cx, |s| {
18114                        s.select_ranges(selections.into_iter().map(|(start, end)| {
18115                            snapshot.clip_offset(start, Bias::Left)
18116                                ..snapshot.clip_offset(end, Bias::Right)
18117                        }));
18118                    });
18119                }
18120            };
18121        }
18122
18123        self.read_scroll_position_from_db(item_id, workspace_id, window, cx);
18124    }
18125}
18126
18127// Consider user intent and default settings
18128fn choose_completion_range(
18129    completion: &Completion,
18130    intent: CompletionIntent,
18131    buffer: &Entity<Buffer>,
18132    cx: &mut Context<Editor>,
18133) -> Range<usize> {
18134    fn should_replace(
18135        completion: &Completion,
18136        insert_range: &Range<text::Anchor>,
18137        intent: CompletionIntent,
18138        completion_mode_setting: LspInsertMode,
18139        buffer: &Buffer,
18140    ) -> bool {
18141        // specific actions take precedence over settings
18142        match intent {
18143            CompletionIntent::CompleteWithInsert => return false,
18144            CompletionIntent::CompleteWithReplace => return true,
18145            CompletionIntent::Complete | CompletionIntent::Compose => {}
18146        }
18147
18148        match completion_mode_setting {
18149            LspInsertMode::Insert => false,
18150            LspInsertMode::Replace => true,
18151            LspInsertMode::ReplaceSubsequence => {
18152                let mut text_to_replace = buffer.chars_for_range(
18153                    buffer.anchor_before(completion.replace_range.start)
18154                        ..buffer.anchor_after(completion.replace_range.end),
18155                );
18156                let mut completion_text = completion.new_text.chars();
18157
18158                // is `text_to_replace` a subsequence of `completion_text`
18159                text_to_replace
18160                    .all(|needle_ch| completion_text.any(|haystack_ch| haystack_ch == needle_ch))
18161            }
18162            LspInsertMode::ReplaceSuffix => {
18163                let range_after_cursor = insert_range.end..completion.replace_range.end;
18164
18165                let text_after_cursor = buffer
18166                    .text_for_range(
18167                        buffer.anchor_before(range_after_cursor.start)
18168                            ..buffer.anchor_after(range_after_cursor.end),
18169                    )
18170                    .collect::<String>();
18171                completion.new_text.ends_with(&text_after_cursor)
18172            }
18173        }
18174    }
18175
18176    let buffer = buffer.read(cx);
18177
18178    if let CompletionSource::Lsp {
18179        insert_range: Some(insert_range),
18180        ..
18181    } = &completion.source
18182    {
18183        let completion_mode_setting =
18184            language_settings(buffer.language().map(|l| l.name()), buffer.file(), cx)
18185                .completions
18186                .lsp_insert_mode;
18187
18188        if !should_replace(
18189            completion,
18190            &insert_range,
18191            intent,
18192            completion_mode_setting,
18193            buffer,
18194        ) {
18195            return insert_range.to_offset(buffer);
18196        }
18197    }
18198
18199    completion.replace_range.to_offset(buffer)
18200}
18201
18202fn insert_extra_newline_brackets(
18203    buffer: &MultiBufferSnapshot,
18204    range: Range<usize>,
18205    language: &language::LanguageScope,
18206) -> bool {
18207    let leading_whitespace_len = buffer
18208        .reversed_chars_at(range.start)
18209        .take_while(|c| c.is_whitespace() && *c != '\n')
18210        .map(|c| c.len_utf8())
18211        .sum::<usize>();
18212    let trailing_whitespace_len = buffer
18213        .chars_at(range.end)
18214        .take_while(|c| c.is_whitespace() && *c != '\n')
18215        .map(|c| c.len_utf8())
18216        .sum::<usize>();
18217    let range = range.start - leading_whitespace_len..range.end + trailing_whitespace_len;
18218
18219    language.brackets().any(|(pair, enabled)| {
18220        let pair_start = pair.start.trim_end();
18221        let pair_end = pair.end.trim_start();
18222
18223        enabled
18224            && pair.newline
18225            && buffer.contains_str_at(range.end, pair_end)
18226            && buffer.contains_str_at(range.start.saturating_sub(pair_start.len()), pair_start)
18227    })
18228}
18229
18230fn insert_extra_newline_tree_sitter(buffer: &MultiBufferSnapshot, range: Range<usize>) -> bool {
18231    let (buffer, range) = match buffer.range_to_buffer_ranges(range).as_slice() {
18232        [(buffer, range, _)] => (*buffer, range.clone()),
18233        _ => return false,
18234    };
18235    let pair = {
18236        let mut result: Option<BracketMatch> = None;
18237
18238        for pair in buffer
18239            .all_bracket_ranges(range.clone())
18240            .filter(move |pair| {
18241                pair.open_range.start <= range.start && pair.close_range.end >= range.end
18242            })
18243        {
18244            let len = pair.close_range.end - pair.open_range.start;
18245
18246            if let Some(existing) = &result {
18247                let existing_len = existing.close_range.end - existing.open_range.start;
18248                if len > existing_len {
18249                    continue;
18250                }
18251            }
18252
18253            result = Some(pair);
18254        }
18255
18256        result
18257    };
18258    let Some(pair) = pair else {
18259        return false;
18260    };
18261    pair.newline_only
18262        && buffer
18263            .chars_for_range(pair.open_range.end..range.start)
18264            .chain(buffer.chars_for_range(range.end..pair.close_range.start))
18265            .all(|c| c.is_whitespace() && c != '\n')
18266}
18267
18268fn get_uncommitted_diff_for_buffer(
18269    project: &Entity<Project>,
18270    buffers: impl IntoIterator<Item = Entity<Buffer>>,
18271    buffer: Entity<MultiBuffer>,
18272    cx: &mut App,
18273) -> Task<()> {
18274    let mut tasks = Vec::new();
18275    project.update(cx, |project, cx| {
18276        for buffer in buffers {
18277            if project::File::from_dyn(buffer.read(cx).file()).is_some() {
18278                tasks.push(project.open_uncommitted_diff(buffer.clone(), cx))
18279            }
18280        }
18281    });
18282    cx.spawn(async move |cx| {
18283        let diffs = future::join_all(tasks).await;
18284        buffer
18285            .update(cx, |buffer, cx| {
18286                for diff in diffs.into_iter().flatten() {
18287                    buffer.add_diff(diff, cx);
18288                }
18289            })
18290            .ok();
18291    })
18292}
18293
18294fn char_len_with_expanded_tabs(offset: usize, text: &str, tab_size: NonZeroU32) -> usize {
18295    let tab_size = tab_size.get() as usize;
18296    let mut width = offset;
18297
18298    for ch in text.chars() {
18299        width += if ch == '\t' {
18300            tab_size - (width % tab_size)
18301        } else {
18302            1
18303        };
18304    }
18305
18306    width - offset
18307}
18308
18309#[cfg(test)]
18310mod tests {
18311    use super::*;
18312
18313    #[test]
18314    fn test_string_size_with_expanded_tabs() {
18315        let nz = |val| NonZeroU32::new(val).unwrap();
18316        assert_eq!(char_len_with_expanded_tabs(0, "", nz(4)), 0);
18317        assert_eq!(char_len_with_expanded_tabs(0, "hello", nz(4)), 5);
18318        assert_eq!(char_len_with_expanded_tabs(0, "\thello", nz(4)), 9);
18319        assert_eq!(char_len_with_expanded_tabs(0, "abc\tab", nz(4)), 6);
18320        assert_eq!(char_len_with_expanded_tabs(0, "hello\t", nz(4)), 8);
18321        assert_eq!(char_len_with_expanded_tabs(0, "\t\t", nz(8)), 16);
18322        assert_eq!(char_len_with_expanded_tabs(0, "x\t", nz(8)), 8);
18323        assert_eq!(char_len_with_expanded_tabs(7, "x\t", nz(8)), 9);
18324    }
18325}
18326
18327/// Tokenizes a string into runs of text that should stick together, or that is whitespace.
18328struct WordBreakingTokenizer<'a> {
18329    input: &'a str,
18330}
18331
18332impl<'a> WordBreakingTokenizer<'a> {
18333    fn new(input: &'a str) -> Self {
18334        Self { input }
18335    }
18336}
18337
18338fn is_char_ideographic(ch: char) -> bool {
18339    use unicode_script::Script::*;
18340    use unicode_script::UnicodeScript;
18341    matches!(ch.script(), Han | Tangut | Yi)
18342}
18343
18344fn is_grapheme_ideographic(text: &str) -> bool {
18345    text.chars().any(is_char_ideographic)
18346}
18347
18348fn is_grapheme_whitespace(text: &str) -> bool {
18349    text.chars().any(|x| x.is_whitespace())
18350}
18351
18352fn should_stay_with_preceding_ideograph(text: &str) -> bool {
18353    text.chars().next().map_or(false, |ch| {
18354        matches!(ch, '。' | '、' | ',' | '?' | '!' | ':' | ';' | '…')
18355    })
18356}
18357
18358#[derive(PartialEq, Eq, Debug, Clone, Copy)]
18359enum WordBreakToken<'a> {
18360    Word { token: &'a str, grapheme_len: usize },
18361    InlineWhitespace { token: &'a str, grapheme_len: usize },
18362    Newline,
18363}
18364
18365impl<'a> Iterator for WordBreakingTokenizer<'a> {
18366    /// Yields a span, the count of graphemes in the token, and whether it was
18367    /// whitespace. Note that it also breaks at word boundaries.
18368    type Item = WordBreakToken<'a>;
18369
18370    fn next(&mut self) -> Option<Self::Item> {
18371        use unicode_segmentation::UnicodeSegmentation;
18372        if self.input.is_empty() {
18373            return None;
18374        }
18375
18376        let mut iter = self.input.graphemes(true).peekable();
18377        let mut offset = 0;
18378        let mut grapheme_len = 0;
18379        if let Some(first_grapheme) = iter.next() {
18380            let is_newline = first_grapheme == "\n";
18381            let is_whitespace = is_grapheme_whitespace(first_grapheme);
18382            offset += first_grapheme.len();
18383            grapheme_len += 1;
18384            if is_grapheme_ideographic(first_grapheme) && !is_whitespace {
18385                if let Some(grapheme) = iter.peek().copied() {
18386                    if should_stay_with_preceding_ideograph(grapheme) {
18387                        offset += grapheme.len();
18388                        grapheme_len += 1;
18389                    }
18390                }
18391            } else {
18392                let mut words = self.input[offset..].split_word_bound_indices().peekable();
18393                let mut next_word_bound = words.peek().copied();
18394                if next_word_bound.map_or(false, |(i, _)| i == 0) {
18395                    next_word_bound = words.next();
18396                }
18397                while let Some(grapheme) = iter.peek().copied() {
18398                    if next_word_bound.map_or(false, |(i, _)| i == offset) {
18399                        break;
18400                    };
18401                    if is_grapheme_whitespace(grapheme) != is_whitespace
18402                        || (grapheme == "\n") != is_newline
18403                    {
18404                        break;
18405                    };
18406                    offset += grapheme.len();
18407                    grapheme_len += 1;
18408                    iter.next();
18409                }
18410            }
18411            let token = &self.input[..offset];
18412            self.input = &self.input[offset..];
18413            if token == "\n" {
18414                Some(WordBreakToken::Newline)
18415            } else if is_whitespace {
18416                Some(WordBreakToken::InlineWhitespace {
18417                    token,
18418                    grapheme_len,
18419                })
18420            } else {
18421                Some(WordBreakToken::Word {
18422                    token,
18423                    grapheme_len,
18424                })
18425            }
18426        } else {
18427            None
18428        }
18429    }
18430}
18431
18432#[test]
18433fn test_word_breaking_tokenizer() {
18434    let tests: &[(&str, &[WordBreakToken<'static>])] = &[
18435        ("", &[]),
18436        ("  ", &[whitespace("  ", 2)]),
18437        ("Ʒ", &[word("Ʒ", 1)]),
18438        ("Ǽ", &[word("Ǽ", 1)]),
18439        ("", &[word("", 1)]),
18440        ("⋑⋑", &[word("⋑⋑", 2)]),
18441        (
18442            "原理,进而",
18443            &[word("", 1), word("理,", 2), word("", 1), word("", 1)],
18444        ),
18445        (
18446            "hello world",
18447            &[word("hello", 5), whitespace(" ", 1), word("world", 5)],
18448        ),
18449        (
18450            "hello, world",
18451            &[word("hello,", 6), whitespace(" ", 1), word("world", 5)],
18452        ),
18453        (
18454            "  hello world",
18455            &[
18456                whitespace("  ", 2),
18457                word("hello", 5),
18458                whitespace(" ", 1),
18459                word("world", 5),
18460            ],
18461        ),
18462        (
18463            "这是什么 \n 钢笔",
18464            &[
18465                word("", 1),
18466                word("", 1),
18467                word("", 1),
18468                word("", 1),
18469                whitespace(" ", 1),
18470                newline(),
18471                whitespace(" ", 1),
18472                word("", 1),
18473                word("", 1),
18474            ],
18475        ),
18476        (" mutton", &[whitespace("", 1), word("mutton", 6)]),
18477    ];
18478
18479    fn word(token: &'static str, grapheme_len: usize) -> WordBreakToken<'static> {
18480        WordBreakToken::Word {
18481            token,
18482            grapheme_len,
18483        }
18484    }
18485
18486    fn whitespace(token: &'static str, grapheme_len: usize) -> WordBreakToken<'static> {
18487        WordBreakToken::InlineWhitespace {
18488            token,
18489            grapheme_len,
18490        }
18491    }
18492
18493    fn newline() -> WordBreakToken<'static> {
18494        WordBreakToken::Newline
18495    }
18496
18497    for (input, result) in tests {
18498        assert_eq!(
18499            WordBreakingTokenizer::new(input)
18500                .collect::<Vec<_>>()
18501                .as_slice(),
18502            *result,
18503        );
18504    }
18505}
18506
18507fn wrap_with_prefix(
18508    line_prefix: String,
18509    unwrapped_text: String,
18510    wrap_column: usize,
18511    tab_size: NonZeroU32,
18512    preserve_existing_whitespace: bool,
18513) -> String {
18514    let line_prefix_len = char_len_with_expanded_tabs(0, &line_prefix, tab_size);
18515    let mut wrapped_text = String::new();
18516    let mut current_line = line_prefix.clone();
18517
18518    let tokenizer = WordBreakingTokenizer::new(&unwrapped_text);
18519    let mut current_line_len = line_prefix_len;
18520    let mut in_whitespace = false;
18521    for token in tokenizer {
18522        let have_preceding_whitespace = in_whitespace;
18523        match token {
18524            WordBreakToken::Word {
18525                token,
18526                grapheme_len,
18527            } => {
18528                in_whitespace = false;
18529                if current_line_len + grapheme_len > wrap_column
18530                    && current_line_len != line_prefix_len
18531                {
18532                    wrapped_text.push_str(current_line.trim_end());
18533                    wrapped_text.push('\n');
18534                    current_line.truncate(line_prefix.len());
18535                    current_line_len = line_prefix_len;
18536                }
18537                current_line.push_str(token);
18538                current_line_len += grapheme_len;
18539            }
18540            WordBreakToken::InlineWhitespace {
18541                mut token,
18542                mut grapheme_len,
18543            } => {
18544                in_whitespace = true;
18545                if have_preceding_whitespace && !preserve_existing_whitespace {
18546                    continue;
18547                }
18548                if !preserve_existing_whitespace {
18549                    token = " ";
18550                    grapheme_len = 1;
18551                }
18552                if current_line_len + grapheme_len > wrap_column {
18553                    wrapped_text.push_str(current_line.trim_end());
18554                    wrapped_text.push('\n');
18555                    current_line.truncate(line_prefix.len());
18556                    current_line_len = line_prefix_len;
18557                } else if current_line_len != line_prefix_len || preserve_existing_whitespace {
18558                    current_line.push_str(token);
18559                    current_line_len += grapheme_len;
18560                }
18561            }
18562            WordBreakToken::Newline => {
18563                in_whitespace = true;
18564                if preserve_existing_whitespace {
18565                    wrapped_text.push_str(current_line.trim_end());
18566                    wrapped_text.push('\n');
18567                    current_line.truncate(line_prefix.len());
18568                    current_line_len = line_prefix_len;
18569                } else if have_preceding_whitespace {
18570                    continue;
18571                } else if current_line_len + 1 > wrap_column && current_line_len != line_prefix_len
18572                {
18573                    wrapped_text.push_str(current_line.trim_end());
18574                    wrapped_text.push('\n');
18575                    current_line.truncate(line_prefix.len());
18576                    current_line_len = line_prefix_len;
18577                } else if current_line_len != line_prefix_len {
18578                    current_line.push(' ');
18579                    current_line_len += 1;
18580                }
18581            }
18582        }
18583    }
18584
18585    if !current_line.is_empty() {
18586        wrapped_text.push_str(&current_line);
18587    }
18588    wrapped_text
18589}
18590
18591#[test]
18592fn test_wrap_with_prefix() {
18593    assert_eq!(
18594        wrap_with_prefix(
18595            "# ".to_string(),
18596            "abcdefg".to_string(),
18597            4,
18598            NonZeroU32::new(4).unwrap(),
18599            false,
18600        ),
18601        "# abcdefg"
18602    );
18603    assert_eq!(
18604        wrap_with_prefix(
18605            "".to_string(),
18606            "\thello world".to_string(),
18607            8,
18608            NonZeroU32::new(4).unwrap(),
18609            false,
18610        ),
18611        "hello\nworld"
18612    );
18613    assert_eq!(
18614        wrap_with_prefix(
18615            "// ".to_string(),
18616            "xx \nyy zz aa bb cc".to_string(),
18617            12,
18618            NonZeroU32::new(4).unwrap(),
18619            false,
18620        ),
18621        "// xx yy zz\n// aa bb cc"
18622    );
18623    assert_eq!(
18624        wrap_with_prefix(
18625            String::new(),
18626            "这是什么 \n 钢笔".to_string(),
18627            3,
18628            NonZeroU32::new(4).unwrap(),
18629            false,
18630        ),
18631        "这是什\n么 钢\n"
18632    );
18633}
18634
18635pub trait CollaborationHub {
18636    fn collaborators<'a>(&self, cx: &'a App) -> &'a HashMap<PeerId, Collaborator>;
18637    fn user_participant_indices<'a>(&self, cx: &'a App) -> &'a HashMap<u64, ParticipantIndex>;
18638    fn user_names(&self, cx: &App) -> HashMap<u64, SharedString>;
18639}
18640
18641impl CollaborationHub for Entity<Project> {
18642    fn collaborators<'a>(&self, cx: &'a App) -> &'a HashMap<PeerId, Collaborator> {
18643        self.read(cx).collaborators()
18644    }
18645
18646    fn user_participant_indices<'a>(&self, cx: &'a App) -> &'a HashMap<u64, ParticipantIndex> {
18647        self.read(cx).user_store().read(cx).participant_indices()
18648    }
18649
18650    fn user_names(&self, cx: &App) -> HashMap<u64, SharedString> {
18651        let this = self.read(cx);
18652        let user_ids = this.collaborators().values().map(|c| c.user_id);
18653        this.user_store().read_with(cx, |user_store, cx| {
18654            user_store.participant_names(user_ids, cx)
18655        })
18656    }
18657}
18658
18659pub trait SemanticsProvider {
18660    fn hover(
18661        &self,
18662        buffer: &Entity<Buffer>,
18663        position: text::Anchor,
18664        cx: &mut App,
18665    ) -> Option<Task<Vec<project::Hover>>>;
18666
18667    fn inlay_hints(
18668        &self,
18669        buffer_handle: Entity<Buffer>,
18670        range: Range<text::Anchor>,
18671        cx: &mut App,
18672    ) -> Option<Task<anyhow::Result<Vec<InlayHint>>>>;
18673
18674    fn resolve_inlay_hint(
18675        &self,
18676        hint: InlayHint,
18677        buffer_handle: Entity<Buffer>,
18678        server_id: LanguageServerId,
18679        cx: &mut App,
18680    ) -> Option<Task<anyhow::Result<InlayHint>>>;
18681
18682    fn supports_inlay_hints(&self, buffer: &Entity<Buffer>, cx: &mut App) -> bool;
18683
18684    fn document_highlights(
18685        &self,
18686        buffer: &Entity<Buffer>,
18687        position: text::Anchor,
18688        cx: &mut App,
18689    ) -> Option<Task<Result<Vec<DocumentHighlight>>>>;
18690
18691    fn definitions(
18692        &self,
18693        buffer: &Entity<Buffer>,
18694        position: text::Anchor,
18695        kind: GotoDefinitionKind,
18696        cx: &mut App,
18697    ) -> Option<Task<Result<Vec<LocationLink>>>>;
18698
18699    fn range_for_rename(
18700        &self,
18701        buffer: &Entity<Buffer>,
18702        position: text::Anchor,
18703        cx: &mut App,
18704    ) -> Option<Task<Result<Option<Range<text::Anchor>>>>>;
18705
18706    fn perform_rename(
18707        &self,
18708        buffer: &Entity<Buffer>,
18709        position: text::Anchor,
18710        new_name: String,
18711        cx: &mut App,
18712    ) -> Option<Task<Result<ProjectTransaction>>>;
18713}
18714
18715pub trait CompletionProvider {
18716    fn completions(
18717        &self,
18718        excerpt_id: ExcerptId,
18719        buffer: &Entity<Buffer>,
18720        buffer_position: text::Anchor,
18721        trigger: CompletionContext,
18722        window: &mut Window,
18723        cx: &mut Context<Editor>,
18724    ) -> Task<Result<Option<Vec<Completion>>>>;
18725
18726    fn resolve_completions(
18727        &self,
18728        buffer: Entity<Buffer>,
18729        completion_indices: Vec<usize>,
18730        completions: Rc<RefCell<Box<[Completion]>>>,
18731        cx: &mut Context<Editor>,
18732    ) -> Task<Result<bool>>;
18733
18734    fn apply_additional_edits_for_completion(
18735        &self,
18736        _buffer: Entity<Buffer>,
18737        _completions: Rc<RefCell<Box<[Completion]>>>,
18738        _completion_index: usize,
18739        _push_to_history: bool,
18740        _cx: &mut Context<Editor>,
18741    ) -> Task<Result<Option<language::Transaction>>> {
18742        Task::ready(Ok(None))
18743    }
18744
18745    fn is_completion_trigger(
18746        &self,
18747        buffer: &Entity<Buffer>,
18748        position: language::Anchor,
18749        text: &str,
18750        trigger_in_words: bool,
18751        cx: &mut Context<Editor>,
18752    ) -> bool;
18753
18754    fn sort_completions(&self) -> bool {
18755        true
18756    }
18757
18758    fn filter_completions(&self) -> bool {
18759        true
18760    }
18761}
18762
18763pub trait CodeActionProvider {
18764    fn id(&self) -> Arc<str>;
18765
18766    fn code_actions(
18767        &self,
18768        buffer: &Entity<Buffer>,
18769        range: Range<text::Anchor>,
18770        window: &mut Window,
18771        cx: &mut App,
18772    ) -> Task<Result<Vec<CodeAction>>>;
18773
18774    fn apply_code_action(
18775        &self,
18776        buffer_handle: Entity<Buffer>,
18777        action: CodeAction,
18778        excerpt_id: ExcerptId,
18779        push_to_history: bool,
18780        window: &mut Window,
18781        cx: &mut App,
18782    ) -> Task<Result<ProjectTransaction>>;
18783}
18784
18785impl CodeActionProvider for Entity<Project> {
18786    fn id(&self) -> Arc<str> {
18787        "project".into()
18788    }
18789
18790    fn code_actions(
18791        &self,
18792        buffer: &Entity<Buffer>,
18793        range: Range<text::Anchor>,
18794        _window: &mut Window,
18795        cx: &mut App,
18796    ) -> Task<Result<Vec<CodeAction>>> {
18797        self.update(cx, |project, cx| {
18798            let code_lens = project.code_lens(buffer, range.clone(), cx);
18799            let code_actions = project.code_actions(buffer, range, None, cx);
18800            cx.background_spawn(async move {
18801                let (code_lens, code_actions) = join(code_lens, code_actions).await;
18802                Ok(code_lens
18803                    .context("code lens fetch")?
18804                    .into_iter()
18805                    .chain(code_actions.context("code action fetch")?)
18806                    .collect())
18807            })
18808        })
18809    }
18810
18811    fn apply_code_action(
18812        &self,
18813        buffer_handle: Entity<Buffer>,
18814        action: CodeAction,
18815        _excerpt_id: ExcerptId,
18816        push_to_history: bool,
18817        _window: &mut Window,
18818        cx: &mut App,
18819    ) -> Task<Result<ProjectTransaction>> {
18820        self.update(cx, |project, cx| {
18821            project.apply_code_action(buffer_handle, action, push_to_history, cx)
18822        })
18823    }
18824}
18825
18826fn snippet_completions(
18827    project: &Project,
18828    buffer: &Entity<Buffer>,
18829    buffer_position: text::Anchor,
18830    cx: &mut App,
18831) -> Task<Result<Vec<Completion>>> {
18832    let languages = buffer.read(cx).languages_at(buffer_position);
18833    let snippet_store = project.snippets().read(cx);
18834
18835    let scopes: Vec<_> = languages
18836        .iter()
18837        .filter_map(|language| {
18838            let language_name = language.lsp_id();
18839            let snippets = snippet_store.snippets_for(Some(language_name), cx);
18840
18841            if snippets.is_empty() {
18842                None
18843            } else {
18844                Some((language.default_scope(), snippets))
18845            }
18846        })
18847        .collect();
18848
18849    if scopes.is_empty() {
18850        return Task::ready(Ok(vec![]));
18851    }
18852
18853    let snapshot = buffer.read(cx).text_snapshot();
18854    let chars: String = snapshot
18855        .reversed_chars_for_range(text::Anchor::MIN..buffer_position)
18856        .collect();
18857    let executor = cx.background_executor().clone();
18858
18859    cx.background_spawn(async move {
18860        let mut all_results: Vec<Completion> = Vec::new();
18861        for (scope, snippets) in scopes.into_iter() {
18862            let classifier = CharClassifier::new(Some(scope)).for_completion(true);
18863            let mut last_word = chars
18864                .chars()
18865                .take_while(|c| classifier.is_word(*c))
18866                .collect::<String>();
18867            last_word = last_word.chars().rev().collect();
18868
18869            if last_word.is_empty() {
18870                return Ok(vec![]);
18871            }
18872
18873            let as_offset = text::ToOffset::to_offset(&buffer_position, &snapshot);
18874            let to_lsp = |point: &text::Anchor| {
18875                let end = text::ToPointUtf16::to_point_utf16(point, &snapshot);
18876                point_to_lsp(end)
18877            };
18878            let lsp_end = to_lsp(&buffer_position);
18879
18880            let candidates = snippets
18881                .iter()
18882                .enumerate()
18883                .flat_map(|(ix, snippet)| {
18884                    snippet
18885                        .prefix
18886                        .iter()
18887                        .map(move |prefix| StringMatchCandidate::new(ix, &prefix))
18888                })
18889                .collect::<Vec<StringMatchCandidate>>();
18890
18891            let mut matches = fuzzy::match_strings(
18892                &candidates,
18893                &last_word,
18894                last_word.chars().any(|c| c.is_uppercase()),
18895                100,
18896                &Default::default(),
18897                executor.clone(),
18898            )
18899            .await;
18900
18901            // Remove all candidates where the query's start does not match the start of any word in the candidate
18902            if let Some(query_start) = last_word.chars().next() {
18903                matches.retain(|string_match| {
18904                    split_words(&string_match.string).any(|word| {
18905                        // Check that the first codepoint of the word as lowercase matches the first
18906                        // codepoint of the query as lowercase
18907                        word.chars()
18908                            .flat_map(|codepoint| codepoint.to_lowercase())
18909                            .zip(query_start.to_lowercase())
18910                            .all(|(word_cp, query_cp)| word_cp == query_cp)
18911                    })
18912                });
18913            }
18914
18915            let matched_strings = matches
18916                .into_iter()
18917                .map(|m| m.string)
18918                .collect::<HashSet<_>>();
18919
18920            let mut result: Vec<Completion> = snippets
18921                .iter()
18922                .filter_map(|snippet| {
18923                    let matching_prefix = snippet
18924                        .prefix
18925                        .iter()
18926                        .find(|prefix| matched_strings.contains(*prefix))?;
18927                    let start = as_offset - last_word.len();
18928                    let start = snapshot.anchor_before(start);
18929                    let range = start..buffer_position;
18930                    let lsp_start = to_lsp(&start);
18931                    let lsp_range = lsp::Range {
18932                        start: lsp_start,
18933                        end: lsp_end,
18934                    };
18935                    Some(Completion {
18936                        replace_range: range,
18937                        new_text: snippet.body.clone(),
18938                        source: CompletionSource::Lsp {
18939                            insert_range: None,
18940                            server_id: LanguageServerId(usize::MAX),
18941                            resolved: true,
18942                            lsp_completion: Box::new(lsp::CompletionItem {
18943                                label: snippet.prefix.first().unwrap().clone(),
18944                                kind: Some(CompletionItemKind::SNIPPET),
18945                                label_details: snippet.description.as_ref().map(|description| {
18946                                    lsp::CompletionItemLabelDetails {
18947                                        detail: Some(description.clone()),
18948                                        description: None,
18949                                    }
18950                                }),
18951                                insert_text_format: Some(InsertTextFormat::SNIPPET),
18952                                text_edit: Some(lsp::CompletionTextEdit::InsertAndReplace(
18953                                    lsp::InsertReplaceEdit {
18954                                        new_text: snippet.body.clone(),
18955                                        insert: lsp_range,
18956                                        replace: lsp_range,
18957                                    },
18958                                )),
18959                                filter_text: Some(snippet.body.clone()),
18960                                sort_text: Some(char::MAX.to_string()),
18961                                ..lsp::CompletionItem::default()
18962                            }),
18963                            lsp_defaults: None,
18964                        },
18965                        label: CodeLabel {
18966                            text: matching_prefix.clone(),
18967                            runs: Vec::new(),
18968                            filter_range: 0..matching_prefix.len(),
18969                        },
18970                        icon_path: None,
18971                        documentation: snippet.description.clone().map(|description| {
18972                            CompletionDocumentation::SingleLine(description.into())
18973                        }),
18974                        insert_text_mode: None,
18975                        confirm: None,
18976                    })
18977                })
18978                .collect();
18979
18980            all_results.append(&mut result);
18981        }
18982
18983        Ok(all_results)
18984    })
18985}
18986
18987impl CompletionProvider for Entity<Project> {
18988    fn completions(
18989        &self,
18990        _excerpt_id: ExcerptId,
18991        buffer: &Entity<Buffer>,
18992        buffer_position: text::Anchor,
18993        options: CompletionContext,
18994        _window: &mut Window,
18995        cx: &mut Context<Editor>,
18996    ) -> Task<Result<Option<Vec<Completion>>>> {
18997        self.update(cx, |project, cx| {
18998            let snippets = snippet_completions(project, buffer, buffer_position, cx);
18999            let project_completions = project.completions(buffer, buffer_position, options, cx);
19000            cx.background_spawn(async move {
19001                let snippets_completions = snippets.await?;
19002                match project_completions.await? {
19003                    Some(mut completions) => {
19004                        completions.extend(snippets_completions);
19005                        Ok(Some(completions))
19006                    }
19007                    None => {
19008                        if snippets_completions.is_empty() {
19009                            Ok(None)
19010                        } else {
19011                            Ok(Some(snippets_completions))
19012                        }
19013                    }
19014                }
19015            })
19016        })
19017    }
19018
19019    fn resolve_completions(
19020        &self,
19021        buffer: Entity<Buffer>,
19022        completion_indices: Vec<usize>,
19023        completions: Rc<RefCell<Box<[Completion]>>>,
19024        cx: &mut Context<Editor>,
19025    ) -> Task<Result<bool>> {
19026        self.update(cx, |project, cx| {
19027            project.lsp_store().update(cx, |lsp_store, cx| {
19028                lsp_store.resolve_completions(buffer, completion_indices, completions, cx)
19029            })
19030        })
19031    }
19032
19033    fn apply_additional_edits_for_completion(
19034        &self,
19035        buffer: Entity<Buffer>,
19036        completions: Rc<RefCell<Box<[Completion]>>>,
19037        completion_index: usize,
19038        push_to_history: bool,
19039        cx: &mut Context<Editor>,
19040    ) -> Task<Result<Option<language::Transaction>>> {
19041        self.update(cx, |project, cx| {
19042            project.lsp_store().update(cx, |lsp_store, cx| {
19043                lsp_store.apply_additional_edits_for_completion(
19044                    buffer,
19045                    completions,
19046                    completion_index,
19047                    push_to_history,
19048                    cx,
19049                )
19050            })
19051        })
19052    }
19053
19054    fn is_completion_trigger(
19055        &self,
19056        buffer: &Entity<Buffer>,
19057        position: language::Anchor,
19058        text: &str,
19059        trigger_in_words: bool,
19060        cx: &mut Context<Editor>,
19061    ) -> bool {
19062        let mut chars = text.chars();
19063        let char = if let Some(char) = chars.next() {
19064            char
19065        } else {
19066            return false;
19067        };
19068        if chars.next().is_some() {
19069            return false;
19070        }
19071
19072        let buffer = buffer.read(cx);
19073        let snapshot = buffer.snapshot();
19074        if !snapshot.settings_at(position, cx).show_completions_on_input {
19075            return false;
19076        }
19077        let classifier = snapshot.char_classifier_at(position).for_completion(true);
19078        if trigger_in_words && classifier.is_word(char) {
19079            return true;
19080        }
19081
19082        buffer.completion_triggers().contains(text)
19083    }
19084}
19085
19086impl SemanticsProvider for Entity<Project> {
19087    fn hover(
19088        &self,
19089        buffer: &Entity<Buffer>,
19090        position: text::Anchor,
19091        cx: &mut App,
19092    ) -> Option<Task<Vec<project::Hover>>> {
19093        Some(self.update(cx, |project, cx| project.hover(buffer, position, cx)))
19094    }
19095
19096    fn document_highlights(
19097        &self,
19098        buffer: &Entity<Buffer>,
19099        position: text::Anchor,
19100        cx: &mut App,
19101    ) -> Option<Task<Result<Vec<DocumentHighlight>>>> {
19102        Some(self.update(cx, |project, cx| {
19103            project.document_highlights(buffer, position, cx)
19104        }))
19105    }
19106
19107    fn definitions(
19108        &self,
19109        buffer: &Entity<Buffer>,
19110        position: text::Anchor,
19111        kind: GotoDefinitionKind,
19112        cx: &mut App,
19113    ) -> Option<Task<Result<Vec<LocationLink>>>> {
19114        Some(self.update(cx, |project, cx| match kind {
19115            GotoDefinitionKind::Symbol => project.definition(&buffer, position, cx),
19116            GotoDefinitionKind::Declaration => project.declaration(&buffer, position, cx),
19117            GotoDefinitionKind::Type => project.type_definition(&buffer, position, cx),
19118            GotoDefinitionKind::Implementation => project.implementation(&buffer, position, cx),
19119        }))
19120    }
19121
19122    fn supports_inlay_hints(&self, buffer: &Entity<Buffer>, cx: &mut App) -> bool {
19123        // TODO: make this work for remote projects
19124        self.update(cx, |this, cx| {
19125            buffer.update(cx, |buffer, cx| {
19126                this.any_language_server_supports_inlay_hints(buffer, cx)
19127            })
19128        })
19129    }
19130
19131    fn inlay_hints(
19132        &self,
19133        buffer_handle: Entity<Buffer>,
19134        range: Range<text::Anchor>,
19135        cx: &mut App,
19136    ) -> Option<Task<anyhow::Result<Vec<InlayHint>>>> {
19137        Some(self.update(cx, |project, cx| {
19138            project.inlay_hints(buffer_handle, range, cx)
19139        }))
19140    }
19141
19142    fn resolve_inlay_hint(
19143        &self,
19144        hint: InlayHint,
19145        buffer_handle: Entity<Buffer>,
19146        server_id: LanguageServerId,
19147        cx: &mut App,
19148    ) -> Option<Task<anyhow::Result<InlayHint>>> {
19149        Some(self.update(cx, |project, cx| {
19150            project.resolve_inlay_hint(hint, buffer_handle, server_id, cx)
19151        }))
19152    }
19153
19154    fn range_for_rename(
19155        &self,
19156        buffer: &Entity<Buffer>,
19157        position: text::Anchor,
19158        cx: &mut App,
19159    ) -> Option<Task<Result<Option<Range<text::Anchor>>>>> {
19160        Some(self.update(cx, |project, cx| {
19161            let buffer = buffer.clone();
19162            let task = project.prepare_rename(buffer.clone(), position, cx);
19163            cx.spawn(async move |_, cx| {
19164                Ok(match task.await? {
19165                    PrepareRenameResponse::Success(range) => Some(range),
19166                    PrepareRenameResponse::InvalidPosition => None,
19167                    PrepareRenameResponse::OnlyUnpreparedRenameSupported => {
19168                        // Fallback on using TreeSitter info to determine identifier range
19169                        buffer.update(cx, |buffer, _| {
19170                            let snapshot = buffer.snapshot();
19171                            let (range, kind) = snapshot.surrounding_word(position);
19172                            if kind != Some(CharKind::Word) {
19173                                return None;
19174                            }
19175                            Some(
19176                                snapshot.anchor_before(range.start)
19177                                    ..snapshot.anchor_after(range.end),
19178                            )
19179                        })?
19180                    }
19181                })
19182            })
19183        }))
19184    }
19185
19186    fn perform_rename(
19187        &self,
19188        buffer: &Entity<Buffer>,
19189        position: text::Anchor,
19190        new_name: String,
19191        cx: &mut App,
19192    ) -> Option<Task<Result<ProjectTransaction>>> {
19193        Some(self.update(cx, |project, cx| {
19194            project.perform_rename(buffer.clone(), position, new_name, cx)
19195        }))
19196    }
19197}
19198
19199fn inlay_hint_settings(
19200    location: Anchor,
19201    snapshot: &MultiBufferSnapshot,
19202    cx: &mut Context<Editor>,
19203) -> InlayHintSettings {
19204    let file = snapshot.file_at(location);
19205    let language = snapshot.language_at(location).map(|l| l.name());
19206    language_settings(language, file, cx).inlay_hints
19207}
19208
19209fn consume_contiguous_rows(
19210    contiguous_row_selections: &mut Vec<Selection<Point>>,
19211    selection: &Selection<Point>,
19212    display_map: &DisplaySnapshot,
19213    selections: &mut Peekable<std::slice::Iter<Selection<Point>>>,
19214) -> (MultiBufferRow, MultiBufferRow) {
19215    contiguous_row_selections.push(selection.clone());
19216    let start_row = MultiBufferRow(selection.start.row);
19217    let mut end_row = ending_row(selection, display_map);
19218
19219    while let Some(next_selection) = selections.peek() {
19220        if next_selection.start.row <= end_row.0 {
19221            end_row = ending_row(next_selection, display_map);
19222            contiguous_row_selections.push(selections.next().unwrap().clone());
19223        } else {
19224            break;
19225        }
19226    }
19227    (start_row, end_row)
19228}
19229
19230fn ending_row(next_selection: &Selection<Point>, display_map: &DisplaySnapshot) -> MultiBufferRow {
19231    if next_selection.end.column > 0 || next_selection.is_empty() {
19232        MultiBufferRow(display_map.next_line_boundary(next_selection.end).0.row + 1)
19233    } else {
19234        MultiBufferRow(next_selection.end.row)
19235    }
19236}
19237
19238impl EditorSnapshot {
19239    pub fn remote_selections_in_range<'a>(
19240        &'a self,
19241        range: &'a Range<Anchor>,
19242        collaboration_hub: &dyn CollaborationHub,
19243        cx: &'a App,
19244    ) -> impl 'a + Iterator<Item = RemoteSelection> {
19245        let participant_names = collaboration_hub.user_names(cx);
19246        let participant_indices = collaboration_hub.user_participant_indices(cx);
19247        let collaborators_by_peer_id = collaboration_hub.collaborators(cx);
19248        let collaborators_by_replica_id = collaborators_by_peer_id
19249            .iter()
19250            .map(|(_, collaborator)| (collaborator.replica_id, collaborator))
19251            .collect::<HashMap<_, _>>();
19252        self.buffer_snapshot
19253            .selections_in_range(range, false)
19254            .filter_map(move |(replica_id, line_mode, cursor_shape, selection)| {
19255                let collaborator = collaborators_by_replica_id.get(&replica_id)?;
19256                let participant_index = participant_indices.get(&collaborator.user_id).copied();
19257                let user_name = participant_names.get(&collaborator.user_id).cloned();
19258                Some(RemoteSelection {
19259                    replica_id,
19260                    selection,
19261                    cursor_shape,
19262                    line_mode,
19263                    participant_index,
19264                    peer_id: collaborator.peer_id,
19265                    user_name,
19266                })
19267            })
19268    }
19269
19270    pub fn hunks_for_ranges(
19271        &self,
19272        ranges: impl IntoIterator<Item = Range<Point>>,
19273    ) -> Vec<MultiBufferDiffHunk> {
19274        let mut hunks = Vec::new();
19275        let mut processed_buffer_rows: HashMap<BufferId, HashSet<Range<text::Anchor>>> =
19276            HashMap::default();
19277        for query_range in ranges {
19278            let query_rows =
19279                MultiBufferRow(query_range.start.row)..MultiBufferRow(query_range.end.row + 1);
19280            for hunk in self.buffer_snapshot.diff_hunks_in_range(
19281                Point::new(query_rows.start.0, 0)..Point::new(query_rows.end.0, 0),
19282            ) {
19283                // Include deleted hunks that are adjacent to the query range, because
19284                // otherwise they would be missed.
19285                let mut intersects_range = hunk.row_range.overlaps(&query_rows);
19286                if hunk.status().is_deleted() {
19287                    intersects_range |= hunk.row_range.start == query_rows.end;
19288                    intersects_range |= hunk.row_range.end == query_rows.start;
19289                }
19290                if intersects_range {
19291                    if !processed_buffer_rows
19292                        .entry(hunk.buffer_id)
19293                        .or_default()
19294                        .insert(hunk.buffer_range.start..hunk.buffer_range.end)
19295                    {
19296                        continue;
19297                    }
19298                    hunks.push(hunk);
19299                }
19300            }
19301        }
19302
19303        hunks
19304    }
19305
19306    fn display_diff_hunks_for_rows<'a>(
19307        &'a self,
19308        display_rows: Range<DisplayRow>,
19309        folded_buffers: &'a HashSet<BufferId>,
19310    ) -> impl 'a + Iterator<Item = DisplayDiffHunk> {
19311        let buffer_start = DisplayPoint::new(display_rows.start, 0).to_point(self);
19312        let buffer_end = DisplayPoint::new(display_rows.end, 0).to_point(self);
19313
19314        self.buffer_snapshot
19315            .diff_hunks_in_range(buffer_start..buffer_end)
19316            .filter_map(|hunk| {
19317                if folded_buffers.contains(&hunk.buffer_id) {
19318                    return None;
19319                }
19320
19321                let hunk_start_point = Point::new(hunk.row_range.start.0, 0);
19322                let hunk_end_point = Point::new(hunk.row_range.end.0, 0);
19323
19324                let hunk_display_start = self.point_to_display_point(hunk_start_point, Bias::Left);
19325                let hunk_display_end = self.point_to_display_point(hunk_end_point, Bias::Right);
19326
19327                let display_hunk = if hunk_display_start.column() != 0 {
19328                    DisplayDiffHunk::Folded {
19329                        display_row: hunk_display_start.row(),
19330                    }
19331                } else {
19332                    let mut end_row = hunk_display_end.row();
19333                    if hunk_display_end.column() > 0 {
19334                        end_row.0 += 1;
19335                    }
19336                    let is_created_file = hunk.is_created_file();
19337                    DisplayDiffHunk::Unfolded {
19338                        status: hunk.status(),
19339                        diff_base_byte_range: hunk.diff_base_byte_range,
19340                        display_row_range: hunk_display_start.row()..end_row,
19341                        multi_buffer_range: Anchor::range_in_buffer(
19342                            hunk.excerpt_id,
19343                            hunk.buffer_id,
19344                            hunk.buffer_range,
19345                        ),
19346                        is_created_file,
19347                    }
19348                };
19349
19350                Some(display_hunk)
19351            })
19352    }
19353
19354    pub fn language_at<T: ToOffset>(&self, position: T) -> Option<&Arc<Language>> {
19355        self.display_snapshot.buffer_snapshot.language_at(position)
19356    }
19357
19358    pub fn is_focused(&self) -> bool {
19359        self.is_focused
19360    }
19361
19362    pub fn placeholder_text(&self) -> Option<&Arc<str>> {
19363        self.placeholder_text.as_ref()
19364    }
19365
19366    pub fn scroll_position(&self) -> gpui::Point<f32> {
19367        self.scroll_anchor.scroll_position(&self.display_snapshot)
19368    }
19369
19370    fn gutter_dimensions(
19371        &self,
19372        font_id: FontId,
19373        font_size: Pixels,
19374        max_line_number_width: Pixels,
19375        cx: &App,
19376    ) -> Option<GutterDimensions> {
19377        if !self.show_gutter {
19378            return None;
19379        }
19380
19381        let descent = cx.text_system().descent(font_id, font_size);
19382        let em_width = cx.text_system().em_width(font_id, font_size).log_err()?;
19383        let em_advance = cx.text_system().em_advance(font_id, font_size).log_err()?;
19384
19385        let show_git_gutter = self.show_git_diff_gutter.unwrap_or_else(|| {
19386            matches!(
19387                ProjectSettings::get_global(cx).git.git_gutter,
19388                Some(GitGutterSetting::TrackedFiles)
19389            )
19390        });
19391        let gutter_settings = EditorSettings::get_global(cx).gutter;
19392        let show_line_numbers = self
19393            .show_line_numbers
19394            .unwrap_or(gutter_settings.line_numbers);
19395        let line_gutter_width = if show_line_numbers {
19396            // Avoid flicker-like gutter resizes when the line number gains another digit and only resize the gutter on files with N*10^5 lines.
19397            let min_width_for_number_on_gutter = em_advance * MIN_LINE_NUMBER_DIGITS as f32;
19398            max_line_number_width.max(min_width_for_number_on_gutter)
19399        } else {
19400            0.0.into()
19401        };
19402
19403        let show_code_actions = self
19404            .show_code_actions
19405            .unwrap_or(gutter_settings.code_actions);
19406
19407        let show_runnables = self.show_runnables.unwrap_or(gutter_settings.runnables);
19408        let show_breakpoints = self.show_breakpoints.unwrap_or(gutter_settings.breakpoints);
19409
19410        let git_blame_entries_width =
19411            self.git_blame_gutter_max_author_length
19412                .map(|max_author_length| {
19413                    let renderer = cx.global::<GlobalBlameRenderer>().0.clone();
19414                    const MAX_RELATIVE_TIMESTAMP: &str = "60 minutes ago";
19415
19416                    /// The number of characters to dedicate to gaps and margins.
19417                    const SPACING_WIDTH: usize = 4;
19418
19419                    let max_char_count = max_author_length.min(renderer.max_author_length())
19420                        + ::git::SHORT_SHA_LENGTH
19421                        + MAX_RELATIVE_TIMESTAMP.len()
19422                        + SPACING_WIDTH;
19423
19424                    em_advance * max_char_count
19425                });
19426
19427        let is_singleton = self.buffer_snapshot.is_singleton();
19428
19429        let mut left_padding = git_blame_entries_width.unwrap_or(Pixels::ZERO);
19430        left_padding += if !is_singleton {
19431            em_width * 4.0
19432        } else if show_code_actions || show_runnables || show_breakpoints {
19433            em_width * 3.0
19434        } else if show_git_gutter && show_line_numbers {
19435            em_width * 2.0
19436        } else if show_git_gutter || show_line_numbers {
19437            em_width
19438        } else {
19439            px(0.)
19440        };
19441
19442        let shows_folds = is_singleton && gutter_settings.folds;
19443
19444        let right_padding = if shows_folds && show_line_numbers {
19445            em_width * 4.0
19446        } else if shows_folds || (!is_singleton && show_line_numbers) {
19447            em_width * 3.0
19448        } else if show_line_numbers {
19449            em_width
19450        } else {
19451            px(0.)
19452        };
19453
19454        Some(GutterDimensions {
19455            left_padding,
19456            right_padding,
19457            width: line_gutter_width + left_padding + right_padding,
19458            margin: -descent,
19459            git_blame_entries_width,
19460        })
19461    }
19462
19463    pub fn render_crease_toggle(
19464        &self,
19465        buffer_row: MultiBufferRow,
19466        row_contains_cursor: bool,
19467        editor: Entity<Editor>,
19468        window: &mut Window,
19469        cx: &mut App,
19470    ) -> Option<AnyElement> {
19471        let folded = self.is_line_folded(buffer_row);
19472        let mut is_foldable = false;
19473
19474        if let Some(crease) = self
19475            .crease_snapshot
19476            .query_row(buffer_row, &self.buffer_snapshot)
19477        {
19478            is_foldable = true;
19479            match crease {
19480                Crease::Inline { render_toggle, .. } | Crease::Block { render_toggle, .. } => {
19481                    if let Some(render_toggle) = render_toggle {
19482                        let toggle_callback =
19483                            Arc::new(move |folded, window: &mut Window, cx: &mut App| {
19484                                if folded {
19485                                    editor.update(cx, |editor, cx| {
19486                                        editor.fold_at(buffer_row, window, cx)
19487                                    });
19488                                } else {
19489                                    editor.update(cx, |editor, cx| {
19490                                        editor.unfold_at(buffer_row, window, cx)
19491                                    });
19492                                }
19493                            });
19494                        return Some((render_toggle)(
19495                            buffer_row,
19496                            folded,
19497                            toggle_callback,
19498                            window,
19499                            cx,
19500                        ));
19501                    }
19502                }
19503            }
19504        }
19505
19506        is_foldable |= self.starts_indent(buffer_row);
19507
19508        if folded || (is_foldable && (row_contains_cursor || self.gutter_hovered)) {
19509            Some(
19510                Disclosure::new(("gutter_crease", buffer_row.0), !folded)
19511                    .toggle_state(folded)
19512                    .on_click(window.listener_for(&editor, move |this, _e, window, cx| {
19513                        if folded {
19514                            this.unfold_at(buffer_row, window, cx);
19515                        } else {
19516                            this.fold_at(buffer_row, window, cx);
19517                        }
19518                    }))
19519                    .into_any_element(),
19520            )
19521        } else {
19522            None
19523        }
19524    }
19525
19526    pub fn render_crease_trailer(
19527        &self,
19528        buffer_row: MultiBufferRow,
19529        window: &mut Window,
19530        cx: &mut App,
19531    ) -> Option<AnyElement> {
19532        let folded = self.is_line_folded(buffer_row);
19533        if let Crease::Inline { render_trailer, .. } = self
19534            .crease_snapshot
19535            .query_row(buffer_row, &self.buffer_snapshot)?
19536        {
19537            let render_trailer = render_trailer.as_ref()?;
19538            Some(render_trailer(buffer_row, folded, window, cx))
19539        } else {
19540            None
19541        }
19542    }
19543}
19544
19545impl Deref for EditorSnapshot {
19546    type Target = DisplaySnapshot;
19547
19548    fn deref(&self) -> &Self::Target {
19549        &self.display_snapshot
19550    }
19551}
19552
19553#[derive(Clone, Debug, PartialEq, Eq)]
19554pub enum EditorEvent {
19555    InputIgnored {
19556        text: Arc<str>,
19557    },
19558    InputHandled {
19559        utf16_range_to_replace: Option<Range<isize>>,
19560        text: Arc<str>,
19561    },
19562    ExcerptsAdded {
19563        buffer: Entity<Buffer>,
19564        predecessor: ExcerptId,
19565        excerpts: Vec<(ExcerptId, ExcerptRange<language::Anchor>)>,
19566    },
19567    ExcerptsRemoved {
19568        ids: Vec<ExcerptId>,
19569    },
19570    BufferFoldToggled {
19571        ids: Vec<ExcerptId>,
19572        folded: bool,
19573    },
19574    ExcerptsEdited {
19575        ids: Vec<ExcerptId>,
19576    },
19577    ExcerptsExpanded {
19578        ids: Vec<ExcerptId>,
19579    },
19580    BufferEdited,
19581    Edited {
19582        transaction_id: clock::Lamport,
19583    },
19584    Reparsed(BufferId),
19585    Focused,
19586    FocusedIn,
19587    Blurred,
19588    DirtyChanged,
19589    Saved,
19590    TitleChanged,
19591    DiffBaseChanged,
19592    SelectionsChanged {
19593        local: bool,
19594    },
19595    ScrollPositionChanged {
19596        local: bool,
19597        autoscroll: bool,
19598    },
19599    Closed,
19600    TransactionUndone {
19601        transaction_id: clock::Lamport,
19602    },
19603    TransactionBegun {
19604        transaction_id: clock::Lamport,
19605    },
19606    Reloaded,
19607    CursorShapeChanged,
19608    PushedToNavHistory {
19609        anchor: Anchor,
19610        is_deactivate: bool,
19611    },
19612}
19613
19614impl EventEmitter<EditorEvent> for Editor {}
19615
19616impl Focusable for Editor {
19617    fn focus_handle(&self, _cx: &App) -> FocusHandle {
19618        self.focus_handle.clone()
19619    }
19620}
19621
19622impl Render for Editor {
19623    fn render(&mut self, _: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
19624        let settings = ThemeSettings::get_global(cx);
19625
19626        let mut text_style = match self.mode {
19627            EditorMode::SingleLine { .. } | EditorMode::AutoHeight { .. } => TextStyle {
19628                color: cx.theme().colors().editor_foreground,
19629                font_family: settings.ui_font.family.clone(),
19630                font_features: settings.ui_font.features.clone(),
19631                font_fallbacks: settings.ui_font.fallbacks.clone(),
19632                font_size: rems(0.875).into(),
19633                font_weight: settings.ui_font.weight,
19634                line_height: relative(settings.buffer_line_height.value()),
19635                ..Default::default()
19636            },
19637            EditorMode::Full { .. } => TextStyle {
19638                color: cx.theme().colors().editor_foreground,
19639                font_family: settings.buffer_font.family.clone(),
19640                font_features: settings.buffer_font.features.clone(),
19641                font_fallbacks: settings.buffer_font.fallbacks.clone(),
19642                font_size: settings.buffer_font_size(cx).into(),
19643                font_weight: settings.buffer_font.weight,
19644                line_height: relative(settings.buffer_line_height.value()),
19645                ..Default::default()
19646            },
19647        };
19648        if let Some(text_style_refinement) = &self.text_style_refinement {
19649            text_style.refine(text_style_refinement)
19650        }
19651
19652        let background = match self.mode {
19653            EditorMode::SingleLine { .. } => cx.theme().system().transparent,
19654            EditorMode::AutoHeight { max_lines: _ } => cx.theme().system().transparent,
19655            EditorMode::Full { .. } => cx.theme().colors().editor_background,
19656        };
19657
19658        EditorElement::new(
19659            &cx.entity(),
19660            EditorStyle {
19661                background,
19662                local_player: cx.theme().players().local(),
19663                text: text_style,
19664                scrollbar_width: EditorElement::SCROLLBAR_WIDTH,
19665                syntax: cx.theme().syntax().clone(),
19666                status: cx.theme().status().clone(),
19667                inlay_hints_style: make_inlay_hints_style(cx),
19668                inline_completion_styles: make_suggestion_styles(cx),
19669                unnecessary_code_fade: ThemeSettings::get_global(cx).unnecessary_code_fade,
19670            },
19671        )
19672    }
19673}
19674
19675impl EntityInputHandler for Editor {
19676    fn text_for_range(
19677        &mut self,
19678        range_utf16: Range<usize>,
19679        adjusted_range: &mut Option<Range<usize>>,
19680        _: &mut Window,
19681        cx: &mut Context<Self>,
19682    ) -> Option<String> {
19683        let snapshot = self.buffer.read(cx).read(cx);
19684        let start = snapshot.clip_offset_utf16(OffsetUtf16(range_utf16.start), Bias::Left);
19685        let end = snapshot.clip_offset_utf16(OffsetUtf16(range_utf16.end), Bias::Right);
19686        if (start.0..end.0) != range_utf16 {
19687            adjusted_range.replace(start.0..end.0);
19688        }
19689        Some(snapshot.text_for_range(start..end).collect())
19690    }
19691
19692    fn selected_text_range(
19693        &mut self,
19694        ignore_disabled_input: bool,
19695        _: &mut Window,
19696        cx: &mut Context<Self>,
19697    ) -> Option<UTF16Selection> {
19698        // Prevent the IME menu from appearing when holding down an alphabetic key
19699        // while input is disabled.
19700        if !ignore_disabled_input && !self.input_enabled {
19701            return None;
19702        }
19703
19704        let selection = self.selections.newest::<OffsetUtf16>(cx);
19705        let range = selection.range();
19706
19707        Some(UTF16Selection {
19708            range: range.start.0..range.end.0,
19709            reversed: selection.reversed,
19710        })
19711    }
19712
19713    fn marked_text_range(&self, _: &mut Window, cx: &mut Context<Self>) -> Option<Range<usize>> {
19714        let snapshot = self.buffer.read(cx).read(cx);
19715        let range = self.text_highlights::<InputComposition>(cx)?.1.first()?;
19716        Some(range.start.to_offset_utf16(&snapshot).0..range.end.to_offset_utf16(&snapshot).0)
19717    }
19718
19719    fn unmark_text(&mut self, _: &mut Window, cx: &mut Context<Self>) {
19720        self.clear_highlights::<InputComposition>(cx);
19721        self.ime_transaction.take();
19722    }
19723
19724    fn replace_text_in_range(
19725        &mut self,
19726        range_utf16: Option<Range<usize>>,
19727        text: &str,
19728        window: &mut Window,
19729        cx: &mut Context<Self>,
19730    ) {
19731        if !self.input_enabled {
19732            cx.emit(EditorEvent::InputIgnored { text: text.into() });
19733            return;
19734        }
19735
19736        self.transact(window, cx, |this, window, cx| {
19737            let new_selected_ranges = if let Some(range_utf16) = range_utf16 {
19738                let range_utf16 = OffsetUtf16(range_utf16.start)..OffsetUtf16(range_utf16.end);
19739                Some(this.selection_replacement_ranges(range_utf16, cx))
19740            } else {
19741                this.marked_text_ranges(cx)
19742            };
19743
19744            let range_to_replace = new_selected_ranges.as_ref().and_then(|ranges_to_replace| {
19745                let newest_selection_id = this.selections.newest_anchor().id;
19746                this.selections
19747                    .all::<OffsetUtf16>(cx)
19748                    .iter()
19749                    .zip(ranges_to_replace.iter())
19750                    .find_map(|(selection, range)| {
19751                        if selection.id == newest_selection_id {
19752                            Some(
19753                                (range.start.0 as isize - selection.head().0 as isize)
19754                                    ..(range.end.0 as isize - selection.head().0 as isize),
19755                            )
19756                        } else {
19757                            None
19758                        }
19759                    })
19760            });
19761
19762            cx.emit(EditorEvent::InputHandled {
19763                utf16_range_to_replace: range_to_replace,
19764                text: text.into(),
19765            });
19766
19767            if let Some(new_selected_ranges) = new_selected_ranges {
19768                this.change_selections(None, window, cx, |selections| {
19769                    selections.select_ranges(new_selected_ranges)
19770                });
19771                this.backspace(&Default::default(), window, cx);
19772            }
19773
19774            this.handle_input(text, window, cx);
19775        });
19776
19777        if let Some(transaction) = self.ime_transaction {
19778            self.buffer.update(cx, |buffer, cx| {
19779                buffer.group_until_transaction(transaction, cx);
19780            });
19781        }
19782
19783        self.unmark_text(window, cx);
19784    }
19785
19786    fn replace_and_mark_text_in_range(
19787        &mut self,
19788        range_utf16: Option<Range<usize>>,
19789        text: &str,
19790        new_selected_range_utf16: Option<Range<usize>>,
19791        window: &mut Window,
19792        cx: &mut Context<Self>,
19793    ) {
19794        if !self.input_enabled {
19795            return;
19796        }
19797
19798        let transaction = self.transact(window, cx, |this, window, cx| {
19799            let ranges_to_replace = if let Some(mut marked_ranges) = this.marked_text_ranges(cx) {
19800                let snapshot = this.buffer.read(cx).read(cx);
19801                if let Some(relative_range_utf16) = range_utf16.as_ref() {
19802                    for marked_range in &mut marked_ranges {
19803                        marked_range.end.0 = marked_range.start.0 + relative_range_utf16.end;
19804                        marked_range.start.0 += relative_range_utf16.start;
19805                        marked_range.start =
19806                            snapshot.clip_offset_utf16(marked_range.start, Bias::Left);
19807                        marked_range.end =
19808                            snapshot.clip_offset_utf16(marked_range.end, Bias::Right);
19809                    }
19810                }
19811                Some(marked_ranges)
19812            } else if let Some(range_utf16) = range_utf16 {
19813                let range_utf16 = OffsetUtf16(range_utf16.start)..OffsetUtf16(range_utf16.end);
19814                Some(this.selection_replacement_ranges(range_utf16, cx))
19815            } else {
19816                None
19817            };
19818
19819            let range_to_replace = ranges_to_replace.as_ref().and_then(|ranges_to_replace| {
19820                let newest_selection_id = this.selections.newest_anchor().id;
19821                this.selections
19822                    .all::<OffsetUtf16>(cx)
19823                    .iter()
19824                    .zip(ranges_to_replace.iter())
19825                    .find_map(|(selection, range)| {
19826                        if selection.id == newest_selection_id {
19827                            Some(
19828                                (range.start.0 as isize - selection.head().0 as isize)
19829                                    ..(range.end.0 as isize - selection.head().0 as isize),
19830                            )
19831                        } else {
19832                            None
19833                        }
19834                    })
19835            });
19836
19837            cx.emit(EditorEvent::InputHandled {
19838                utf16_range_to_replace: range_to_replace,
19839                text: text.into(),
19840            });
19841
19842            if let Some(ranges) = ranges_to_replace {
19843                this.change_selections(None, window, cx, |s| s.select_ranges(ranges));
19844            }
19845
19846            let marked_ranges = {
19847                let snapshot = this.buffer.read(cx).read(cx);
19848                this.selections
19849                    .disjoint_anchors()
19850                    .iter()
19851                    .map(|selection| {
19852                        selection.start.bias_left(&snapshot)..selection.end.bias_right(&snapshot)
19853                    })
19854                    .collect::<Vec<_>>()
19855            };
19856
19857            if text.is_empty() {
19858                this.unmark_text(window, cx);
19859            } else {
19860                this.highlight_text::<InputComposition>(
19861                    marked_ranges.clone(),
19862                    HighlightStyle {
19863                        underline: Some(UnderlineStyle {
19864                            thickness: px(1.),
19865                            color: None,
19866                            wavy: false,
19867                        }),
19868                        ..Default::default()
19869                    },
19870                    cx,
19871                );
19872            }
19873
19874            // Disable auto-closing when composing text (i.e. typing a `"` on a Brazilian keyboard)
19875            let use_autoclose = this.use_autoclose;
19876            let use_auto_surround = this.use_auto_surround;
19877            this.set_use_autoclose(false);
19878            this.set_use_auto_surround(false);
19879            this.handle_input(text, window, cx);
19880            this.set_use_autoclose(use_autoclose);
19881            this.set_use_auto_surround(use_auto_surround);
19882
19883            if let Some(new_selected_range) = new_selected_range_utf16 {
19884                let snapshot = this.buffer.read(cx).read(cx);
19885                let new_selected_ranges = marked_ranges
19886                    .into_iter()
19887                    .map(|marked_range| {
19888                        let insertion_start = marked_range.start.to_offset_utf16(&snapshot).0;
19889                        let new_start = OffsetUtf16(new_selected_range.start + insertion_start);
19890                        let new_end = OffsetUtf16(new_selected_range.end + insertion_start);
19891                        snapshot.clip_offset_utf16(new_start, Bias::Left)
19892                            ..snapshot.clip_offset_utf16(new_end, Bias::Right)
19893                    })
19894                    .collect::<Vec<_>>();
19895
19896                drop(snapshot);
19897                this.change_selections(None, window, cx, |selections| {
19898                    selections.select_ranges(new_selected_ranges)
19899                });
19900            }
19901        });
19902
19903        self.ime_transaction = self.ime_transaction.or(transaction);
19904        if let Some(transaction) = self.ime_transaction {
19905            self.buffer.update(cx, |buffer, cx| {
19906                buffer.group_until_transaction(transaction, cx);
19907            });
19908        }
19909
19910        if self.text_highlights::<InputComposition>(cx).is_none() {
19911            self.ime_transaction.take();
19912        }
19913    }
19914
19915    fn bounds_for_range(
19916        &mut self,
19917        range_utf16: Range<usize>,
19918        element_bounds: gpui::Bounds<Pixels>,
19919        window: &mut Window,
19920        cx: &mut Context<Self>,
19921    ) -> Option<gpui::Bounds<Pixels>> {
19922        let text_layout_details = self.text_layout_details(window);
19923        let gpui::Size {
19924            width: em_width,
19925            height: line_height,
19926        } = self.character_size(window);
19927
19928        let snapshot = self.snapshot(window, cx);
19929        let scroll_position = snapshot.scroll_position();
19930        let scroll_left = scroll_position.x * em_width;
19931
19932        let start = OffsetUtf16(range_utf16.start).to_display_point(&snapshot);
19933        let x = snapshot.x_for_display_point(start, &text_layout_details) - scroll_left
19934            + self.gutter_dimensions.width
19935            + self.gutter_dimensions.margin;
19936        let y = line_height * (start.row().as_f32() - scroll_position.y);
19937
19938        Some(Bounds {
19939            origin: element_bounds.origin + point(x, y),
19940            size: size(em_width, line_height),
19941        })
19942    }
19943
19944    fn character_index_for_point(
19945        &mut self,
19946        point: gpui::Point<Pixels>,
19947        _window: &mut Window,
19948        _cx: &mut Context<Self>,
19949    ) -> Option<usize> {
19950        let position_map = self.last_position_map.as_ref()?;
19951        if !position_map.text_hitbox.contains(&point) {
19952            return None;
19953        }
19954        let display_point = position_map.point_for_position(point).previous_valid;
19955        let anchor = position_map
19956            .snapshot
19957            .display_point_to_anchor(display_point, Bias::Left);
19958        let utf16_offset = anchor.to_offset_utf16(&position_map.snapshot.buffer_snapshot);
19959        Some(utf16_offset.0)
19960    }
19961}
19962
19963trait SelectionExt {
19964    fn display_range(&self, map: &DisplaySnapshot) -> Range<DisplayPoint>;
19965    fn spanned_rows(
19966        &self,
19967        include_end_if_at_line_start: bool,
19968        map: &DisplaySnapshot,
19969    ) -> Range<MultiBufferRow>;
19970}
19971
19972impl<T: ToPoint + ToOffset> SelectionExt for Selection<T> {
19973    fn display_range(&self, map: &DisplaySnapshot) -> Range<DisplayPoint> {
19974        let start = self
19975            .start
19976            .to_point(&map.buffer_snapshot)
19977            .to_display_point(map);
19978        let end = self
19979            .end
19980            .to_point(&map.buffer_snapshot)
19981            .to_display_point(map);
19982        if self.reversed {
19983            end..start
19984        } else {
19985            start..end
19986        }
19987    }
19988
19989    fn spanned_rows(
19990        &self,
19991        include_end_if_at_line_start: bool,
19992        map: &DisplaySnapshot,
19993    ) -> Range<MultiBufferRow> {
19994        let start = self.start.to_point(&map.buffer_snapshot);
19995        let mut end = self.end.to_point(&map.buffer_snapshot);
19996        if !include_end_if_at_line_start && start.row != end.row && end.column == 0 {
19997            end.row -= 1;
19998        }
19999
20000        let buffer_start = map.prev_line_boundary(start).0;
20001        let buffer_end = map.next_line_boundary(end).0;
20002        MultiBufferRow(buffer_start.row)..MultiBufferRow(buffer_end.row + 1)
20003    }
20004}
20005
20006impl<T: InvalidationRegion> InvalidationStack<T> {
20007    fn invalidate<S>(&mut self, selections: &[Selection<S>], buffer: &MultiBufferSnapshot)
20008    where
20009        S: Clone + ToOffset,
20010    {
20011        while let Some(region) = self.last() {
20012            let all_selections_inside_invalidation_ranges =
20013                if selections.len() == region.ranges().len() {
20014                    selections
20015                        .iter()
20016                        .zip(region.ranges().iter().map(|r| r.to_offset(buffer)))
20017                        .all(|(selection, invalidation_range)| {
20018                            let head = selection.head().to_offset(buffer);
20019                            invalidation_range.start <= head && invalidation_range.end >= head
20020                        })
20021                } else {
20022                    false
20023                };
20024
20025            if all_selections_inside_invalidation_ranges {
20026                break;
20027            } else {
20028                self.pop();
20029            }
20030        }
20031    }
20032}
20033
20034impl<T> Default for InvalidationStack<T> {
20035    fn default() -> Self {
20036        Self(Default::default())
20037    }
20038}
20039
20040impl<T> Deref for InvalidationStack<T> {
20041    type Target = Vec<T>;
20042
20043    fn deref(&self) -> &Self::Target {
20044        &self.0
20045    }
20046}
20047
20048impl<T> DerefMut for InvalidationStack<T> {
20049    fn deref_mut(&mut self) -> &mut Self::Target {
20050        &mut self.0
20051    }
20052}
20053
20054impl InvalidationRegion for SnippetState {
20055    fn ranges(&self) -> &[Range<Anchor>] {
20056        &self.ranges[self.active_index]
20057    }
20058}
20059
20060fn inline_completion_edit_text(
20061    current_snapshot: &BufferSnapshot,
20062    edits: &[(Range<Anchor>, String)],
20063    edit_preview: &EditPreview,
20064    include_deletions: bool,
20065    cx: &App,
20066) -> HighlightedText {
20067    let edits = edits
20068        .iter()
20069        .map(|(anchor, text)| {
20070            (
20071                anchor.start.text_anchor..anchor.end.text_anchor,
20072                text.clone(),
20073            )
20074        })
20075        .collect::<Vec<_>>();
20076
20077    edit_preview.highlight_edits(current_snapshot, &edits, include_deletions, cx)
20078}
20079
20080pub fn diagnostic_style(severity: DiagnosticSeverity, colors: &StatusColors) -> Hsla {
20081    match severity {
20082        DiagnosticSeverity::ERROR => colors.error,
20083        DiagnosticSeverity::WARNING => colors.warning,
20084        DiagnosticSeverity::INFORMATION => colors.info,
20085        DiagnosticSeverity::HINT => colors.info,
20086        _ => colors.ignored,
20087    }
20088}
20089
20090pub fn styled_runs_for_code_label<'a>(
20091    label: &'a CodeLabel,
20092    syntax_theme: &'a theme::SyntaxTheme,
20093) -> impl 'a + Iterator<Item = (Range<usize>, HighlightStyle)> {
20094    let fade_out = HighlightStyle {
20095        fade_out: Some(0.35),
20096        ..Default::default()
20097    };
20098
20099    let mut prev_end = label.filter_range.end;
20100    label
20101        .runs
20102        .iter()
20103        .enumerate()
20104        .flat_map(move |(ix, (range, highlight_id))| {
20105            let style = if let Some(style) = highlight_id.style(syntax_theme) {
20106                style
20107            } else {
20108                return Default::default();
20109            };
20110            let mut muted_style = style;
20111            muted_style.highlight(fade_out);
20112
20113            let mut runs = SmallVec::<[(Range<usize>, HighlightStyle); 3]>::new();
20114            if range.start >= label.filter_range.end {
20115                if range.start > prev_end {
20116                    runs.push((prev_end..range.start, fade_out));
20117                }
20118                runs.push((range.clone(), muted_style));
20119            } else if range.end <= label.filter_range.end {
20120                runs.push((range.clone(), style));
20121            } else {
20122                runs.push((range.start..label.filter_range.end, style));
20123                runs.push((label.filter_range.end..range.end, muted_style));
20124            }
20125            prev_end = cmp::max(prev_end, range.end);
20126
20127            if ix + 1 == label.runs.len() && label.text.len() > prev_end {
20128                runs.push((prev_end..label.text.len(), fade_out));
20129            }
20130
20131            runs
20132        })
20133}
20134
20135pub(crate) fn split_words(text: &str) -> impl std::iter::Iterator<Item = &str> + '_ {
20136    let mut prev_index = 0;
20137    let mut prev_codepoint: Option<char> = None;
20138    text.char_indices()
20139        .chain([(text.len(), '\0')])
20140        .filter_map(move |(index, codepoint)| {
20141            let prev_codepoint = prev_codepoint.replace(codepoint)?;
20142            let is_boundary = index == text.len()
20143                || !prev_codepoint.is_uppercase() && codepoint.is_uppercase()
20144                || !prev_codepoint.is_alphanumeric() && codepoint.is_alphanumeric();
20145            if is_boundary {
20146                let chunk = &text[prev_index..index];
20147                prev_index = index;
20148                Some(chunk)
20149            } else {
20150                None
20151            }
20152        })
20153}
20154
20155pub trait RangeToAnchorExt: Sized {
20156    fn to_anchors(self, snapshot: &MultiBufferSnapshot) -> Range<Anchor>;
20157
20158    fn to_display_points(self, snapshot: &EditorSnapshot) -> Range<DisplayPoint> {
20159        let anchor_range = self.to_anchors(&snapshot.buffer_snapshot);
20160        anchor_range.start.to_display_point(snapshot)..anchor_range.end.to_display_point(snapshot)
20161    }
20162}
20163
20164impl<T: ToOffset> RangeToAnchorExt for Range<T> {
20165    fn to_anchors(self, snapshot: &MultiBufferSnapshot) -> Range<Anchor> {
20166        let start_offset = self.start.to_offset(snapshot);
20167        let end_offset = self.end.to_offset(snapshot);
20168        if start_offset == end_offset {
20169            snapshot.anchor_before(start_offset)..snapshot.anchor_before(end_offset)
20170        } else {
20171            snapshot.anchor_after(self.start)..snapshot.anchor_before(self.end)
20172        }
20173    }
20174}
20175
20176pub trait RowExt {
20177    fn as_f32(&self) -> f32;
20178
20179    fn next_row(&self) -> Self;
20180
20181    fn previous_row(&self) -> Self;
20182
20183    fn minus(&self, other: Self) -> u32;
20184}
20185
20186impl RowExt for DisplayRow {
20187    fn as_f32(&self) -> f32 {
20188        self.0 as f32
20189    }
20190
20191    fn next_row(&self) -> Self {
20192        Self(self.0 + 1)
20193    }
20194
20195    fn previous_row(&self) -> Self {
20196        Self(self.0.saturating_sub(1))
20197    }
20198
20199    fn minus(&self, other: Self) -> u32 {
20200        self.0 - other.0
20201    }
20202}
20203
20204impl RowExt for MultiBufferRow {
20205    fn as_f32(&self) -> f32 {
20206        self.0 as f32
20207    }
20208
20209    fn next_row(&self) -> Self {
20210        Self(self.0 + 1)
20211    }
20212
20213    fn previous_row(&self) -> Self {
20214        Self(self.0.saturating_sub(1))
20215    }
20216
20217    fn minus(&self, other: Self) -> u32 {
20218        self.0 - other.0
20219    }
20220}
20221
20222trait RowRangeExt {
20223    type Row;
20224
20225    fn len(&self) -> usize;
20226
20227    fn iter_rows(&self) -> impl DoubleEndedIterator<Item = Self::Row>;
20228}
20229
20230impl RowRangeExt for Range<MultiBufferRow> {
20231    type Row = MultiBufferRow;
20232
20233    fn len(&self) -> usize {
20234        (self.end.0 - self.start.0) as usize
20235    }
20236
20237    fn iter_rows(&self) -> impl DoubleEndedIterator<Item = MultiBufferRow> {
20238        (self.start.0..self.end.0).map(MultiBufferRow)
20239    }
20240}
20241
20242impl RowRangeExt for Range<DisplayRow> {
20243    type Row = DisplayRow;
20244
20245    fn len(&self) -> usize {
20246        (self.end.0 - self.start.0) as usize
20247    }
20248
20249    fn iter_rows(&self) -> impl DoubleEndedIterator<Item = DisplayRow> {
20250        (self.start.0..self.end.0).map(DisplayRow)
20251    }
20252}
20253
20254/// If select range has more than one line, we
20255/// just point the cursor to range.start.
20256fn collapse_multiline_range(range: Range<Point>) -> Range<Point> {
20257    if range.start.row == range.end.row {
20258        range
20259    } else {
20260        range.start..range.start
20261    }
20262}
20263pub struct KillRing(ClipboardItem);
20264impl Global for KillRing {}
20265
20266const UPDATE_DEBOUNCE: Duration = Duration::from_millis(50);
20267
20268enum BreakpointPromptEditAction {
20269    Log,
20270    Condition,
20271    HitCondition,
20272}
20273
20274struct BreakpointPromptEditor {
20275    pub(crate) prompt: Entity<Editor>,
20276    editor: WeakEntity<Editor>,
20277    breakpoint_anchor: Anchor,
20278    breakpoint: Breakpoint,
20279    edit_action: BreakpointPromptEditAction,
20280    block_ids: HashSet<CustomBlockId>,
20281    gutter_dimensions: Arc<Mutex<GutterDimensions>>,
20282    _subscriptions: Vec<Subscription>,
20283}
20284
20285impl BreakpointPromptEditor {
20286    const MAX_LINES: u8 = 4;
20287
20288    fn new(
20289        editor: WeakEntity<Editor>,
20290        breakpoint_anchor: Anchor,
20291        breakpoint: Breakpoint,
20292        edit_action: BreakpointPromptEditAction,
20293        window: &mut Window,
20294        cx: &mut Context<Self>,
20295    ) -> Self {
20296        let base_text = match edit_action {
20297            BreakpointPromptEditAction::Log => breakpoint.message.as_ref(),
20298            BreakpointPromptEditAction::Condition => breakpoint.condition.as_ref(),
20299            BreakpointPromptEditAction::HitCondition => breakpoint.hit_condition.as_ref(),
20300        }
20301        .map(|msg| msg.to_string())
20302        .unwrap_or_default();
20303
20304        let buffer = cx.new(|cx| Buffer::local(base_text, cx));
20305        let buffer = cx.new(|cx| MultiBuffer::singleton(buffer, cx));
20306
20307        let prompt = cx.new(|cx| {
20308            let mut prompt = Editor::new(
20309                EditorMode::AutoHeight {
20310                    max_lines: Self::MAX_LINES as usize,
20311                },
20312                buffer,
20313                None,
20314                window,
20315                cx,
20316            );
20317            prompt.set_soft_wrap_mode(language::language_settings::SoftWrap::EditorWidth, cx);
20318            prompt.set_show_cursor_when_unfocused(false, cx);
20319            prompt.set_placeholder_text(
20320                match edit_action {
20321                    BreakpointPromptEditAction::Log => "Message to log when a breakpoint is hit. Expressions within {} are interpolated.",
20322                    BreakpointPromptEditAction::Condition => "Condition when a breakpoint is hit. Expressions within {} are interpolated.",
20323                    BreakpointPromptEditAction::HitCondition => "How many breakpoint hits to ignore",
20324                },
20325                cx,
20326            );
20327
20328            prompt
20329        });
20330
20331        Self {
20332            prompt,
20333            editor,
20334            breakpoint_anchor,
20335            breakpoint,
20336            edit_action,
20337            gutter_dimensions: Arc::new(Mutex::new(GutterDimensions::default())),
20338            block_ids: Default::default(),
20339            _subscriptions: vec![],
20340        }
20341    }
20342
20343    pub(crate) fn add_block_ids(&mut self, block_ids: Vec<CustomBlockId>) {
20344        self.block_ids.extend(block_ids)
20345    }
20346
20347    fn confirm(&mut self, _: &menu::Confirm, window: &mut Window, cx: &mut Context<Self>) {
20348        if let Some(editor) = self.editor.upgrade() {
20349            let message = self
20350                .prompt
20351                .read(cx)
20352                .buffer
20353                .read(cx)
20354                .as_singleton()
20355                .expect("A multi buffer in breakpoint prompt isn't possible")
20356                .read(cx)
20357                .as_rope()
20358                .to_string();
20359
20360            editor.update(cx, |editor, cx| {
20361                editor.edit_breakpoint_at_anchor(
20362                    self.breakpoint_anchor,
20363                    self.breakpoint.clone(),
20364                    match self.edit_action {
20365                        BreakpointPromptEditAction::Log => {
20366                            BreakpointEditAction::EditLogMessage(message.into())
20367                        }
20368                        BreakpointPromptEditAction::Condition => {
20369                            BreakpointEditAction::EditCondition(message.into())
20370                        }
20371                        BreakpointPromptEditAction::HitCondition => {
20372                            BreakpointEditAction::EditHitCondition(message.into())
20373                        }
20374                    },
20375                    cx,
20376                );
20377
20378                editor.remove_blocks(self.block_ids.clone(), None, cx);
20379                cx.focus_self(window);
20380            });
20381        }
20382    }
20383
20384    fn cancel(&mut self, _: &menu::Cancel, window: &mut Window, cx: &mut Context<Self>) {
20385        self.editor
20386            .update(cx, |editor, cx| {
20387                editor.remove_blocks(self.block_ids.clone(), None, cx);
20388                window.focus(&editor.focus_handle);
20389            })
20390            .log_err();
20391    }
20392
20393    fn render_prompt_editor(&self, cx: &mut Context<Self>) -> impl IntoElement {
20394        let settings = ThemeSettings::get_global(cx);
20395        let text_style = TextStyle {
20396            color: if self.prompt.read(cx).read_only(cx) {
20397                cx.theme().colors().text_disabled
20398            } else {
20399                cx.theme().colors().text
20400            },
20401            font_family: settings.buffer_font.family.clone(),
20402            font_fallbacks: settings.buffer_font.fallbacks.clone(),
20403            font_size: settings.buffer_font_size(cx).into(),
20404            font_weight: settings.buffer_font.weight,
20405            line_height: relative(settings.buffer_line_height.value()),
20406            ..Default::default()
20407        };
20408        EditorElement::new(
20409            &self.prompt,
20410            EditorStyle {
20411                background: cx.theme().colors().editor_background,
20412                local_player: cx.theme().players().local(),
20413                text: text_style,
20414                ..Default::default()
20415            },
20416        )
20417    }
20418}
20419
20420impl Render for BreakpointPromptEditor {
20421    fn render(&mut self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
20422        let gutter_dimensions = *self.gutter_dimensions.lock();
20423        h_flex()
20424            .key_context("Editor")
20425            .bg(cx.theme().colors().editor_background)
20426            .border_y_1()
20427            .border_color(cx.theme().status().info_border)
20428            .size_full()
20429            .py(window.line_height() / 2.5)
20430            .on_action(cx.listener(Self::confirm))
20431            .on_action(cx.listener(Self::cancel))
20432            .child(h_flex().w(gutter_dimensions.full_width() + (gutter_dimensions.margin / 2.0)))
20433            .child(div().flex_1().child(self.render_prompt_editor(cx)))
20434    }
20435}
20436
20437impl Focusable for BreakpointPromptEditor {
20438    fn focus_handle(&self, cx: &App) -> FocusHandle {
20439        self.prompt.focus_handle(cx)
20440    }
20441}
20442
20443fn all_edits_insertions_or_deletions(
20444    edits: &Vec<(Range<Anchor>, String)>,
20445    snapshot: &MultiBufferSnapshot,
20446) -> bool {
20447    let mut all_insertions = true;
20448    let mut all_deletions = true;
20449
20450    for (range, new_text) in edits.iter() {
20451        let range_is_empty = range.to_offset(&snapshot).is_empty();
20452        let text_is_empty = new_text.is_empty();
20453
20454        if range_is_empty != text_is_empty {
20455            if range_is_empty {
20456                all_deletions = false;
20457            } else {
20458                all_insertions = false;
20459            }
20460        } else {
20461            return false;
20462        }
20463
20464        if !all_insertions && !all_deletions {
20465            return false;
20466        }
20467    }
20468    all_insertions || all_deletions
20469}
20470
20471struct MissingEditPredictionKeybindingTooltip;
20472
20473impl Render for MissingEditPredictionKeybindingTooltip {
20474    fn render(&mut self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
20475        ui::tooltip_container(window, cx, |container, _, cx| {
20476            container
20477                .flex_shrink_0()
20478                .max_w_80()
20479                .min_h(rems_from_px(124.))
20480                .justify_between()
20481                .child(
20482                    v_flex()
20483                        .flex_1()
20484                        .text_ui_sm(cx)
20485                        .child(Label::new("Conflict with Accept Keybinding"))
20486                        .child("Your keymap currently overrides the default accept keybinding. To continue, assign one keybinding for the `editor::AcceptEditPrediction` action.")
20487                )
20488                .child(
20489                    h_flex()
20490                        .pb_1()
20491                        .gap_1()
20492                        .items_end()
20493                        .w_full()
20494                        .child(Button::new("open-keymap", "Assign Keybinding").size(ButtonSize::Compact).on_click(|_ev, window, cx| {
20495                            window.dispatch_action(zed_actions::OpenKeymap.boxed_clone(), cx)
20496                        }))
20497                        .child(Button::new("see-docs", "See Docs").size(ButtonSize::Compact).on_click(|_ev, _window, cx| {
20498                            cx.open_url("https://zed.dev/docs/completions#edit-predictions-missing-keybinding");
20499                        })),
20500                )
20501        })
20502    }
20503}
20504
20505#[derive(Debug, Clone, Copy, PartialEq)]
20506pub struct LineHighlight {
20507    pub background: Background,
20508    pub border: Option<gpui::Hsla>,
20509}
20510
20511impl From<Hsla> for LineHighlight {
20512    fn from(hsla: Hsla) -> Self {
20513        Self {
20514            background: hsla.into(),
20515            border: None,
20516        }
20517    }
20518}
20519
20520impl From<Background> for LineHighlight {
20521    fn from(background: Background) -> Self {
20522        Self {
20523            background,
20524            border: None,
20525        }
20526    }
20527}
20528
20529fn render_diff_hunk_controls(
20530    row: u32,
20531    status: &DiffHunkStatus,
20532    hunk_range: Range<Anchor>,
20533    is_created_file: bool,
20534    line_height: Pixels,
20535    editor: &Entity<Editor>,
20536    _window: &mut Window,
20537    cx: &mut App,
20538) -> AnyElement {
20539    h_flex()
20540        .h(line_height)
20541        .mr_1()
20542        .gap_1()
20543        .px_0p5()
20544        .pb_1()
20545        .border_x_1()
20546        .border_b_1()
20547        .border_color(cx.theme().colors().border_variant)
20548        .rounded_b_lg()
20549        .bg(cx.theme().colors().editor_background)
20550        .gap_1()
20551        .occlude()
20552        .shadow_md()
20553        .child(if status.has_secondary_hunk() {
20554            Button::new(("stage", row as u64), "Stage")
20555                .alpha(if status.is_pending() { 0.66 } else { 1.0 })
20556                .tooltip({
20557                    let focus_handle = editor.focus_handle(cx);
20558                    move |window, cx| {
20559                        Tooltip::for_action_in(
20560                            "Stage Hunk",
20561                            &::git::ToggleStaged,
20562                            &focus_handle,
20563                            window,
20564                            cx,
20565                        )
20566                    }
20567                })
20568                .on_click({
20569                    let editor = editor.clone();
20570                    move |_event, _window, cx| {
20571                        editor.update(cx, |editor, cx| {
20572                            editor.stage_or_unstage_diff_hunks(
20573                                true,
20574                                vec![hunk_range.start..hunk_range.start],
20575                                cx,
20576                            );
20577                        });
20578                    }
20579                })
20580        } else {
20581            Button::new(("unstage", row as u64), "Unstage")
20582                .alpha(if status.is_pending() { 0.66 } else { 1.0 })
20583                .tooltip({
20584                    let focus_handle = editor.focus_handle(cx);
20585                    move |window, cx| {
20586                        Tooltip::for_action_in(
20587                            "Unstage Hunk",
20588                            &::git::ToggleStaged,
20589                            &focus_handle,
20590                            window,
20591                            cx,
20592                        )
20593                    }
20594                })
20595                .on_click({
20596                    let editor = editor.clone();
20597                    move |_event, _window, cx| {
20598                        editor.update(cx, |editor, cx| {
20599                            editor.stage_or_unstage_diff_hunks(
20600                                false,
20601                                vec![hunk_range.start..hunk_range.start],
20602                                cx,
20603                            );
20604                        });
20605                    }
20606                })
20607        })
20608        .child(
20609            Button::new(("restore", row as u64), "Restore")
20610                .tooltip({
20611                    let focus_handle = editor.focus_handle(cx);
20612                    move |window, cx| {
20613                        Tooltip::for_action_in(
20614                            "Restore Hunk",
20615                            &::git::Restore,
20616                            &focus_handle,
20617                            window,
20618                            cx,
20619                        )
20620                    }
20621                })
20622                .on_click({
20623                    let editor = editor.clone();
20624                    move |_event, window, cx| {
20625                        editor.update(cx, |editor, cx| {
20626                            let snapshot = editor.snapshot(window, cx);
20627                            let point = hunk_range.start.to_point(&snapshot.buffer_snapshot);
20628                            editor.restore_hunks_in_ranges(vec![point..point], window, cx);
20629                        });
20630                    }
20631                })
20632                .disabled(is_created_file),
20633        )
20634        .when(
20635            !editor.read(cx).buffer().read(cx).all_diff_hunks_expanded(),
20636            |el| {
20637                el.child(
20638                    IconButton::new(("next-hunk", row as u64), IconName::ArrowDown)
20639                        .shape(IconButtonShape::Square)
20640                        .icon_size(IconSize::Small)
20641                        // .disabled(!has_multiple_hunks)
20642                        .tooltip({
20643                            let focus_handle = editor.focus_handle(cx);
20644                            move |window, cx| {
20645                                Tooltip::for_action_in(
20646                                    "Next Hunk",
20647                                    &GoToHunk,
20648                                    &focus_handle,
20649                                    window,
20650                                    cx,
20651                                )
20652                            }
20653                        })
20654                        .on_click({
20655                            let editor = editor.clone();
20656                            move |_event, window, cx| {
20657                                editor.update(cx, |editor, cx| {
20658                                    let snapshot = editor.snapshot(window, cx);
20659                                    let position =
20660                                        hunk_range.end.to_point(&snapshot.buffer_snapshot);
20661                                    editor.go_to_hunk_before_or_after_position(
20662                                        &snapshot,
20663                                        position,
20664                                        Direction::Next,
20665                                        window,
20666                                        cx,
20667                                    );
20668                                    editor.expand_selected_diff_hunks(cx);
20669                                });
20670                            }
20671                        }),
20672                )
20673                .child(
20674                    IconButton::new(("prev-hunk", row as u64), IconName::ArrowUp)
20675                        .shape(IconButtonShape::Square)
20676                        .icon_size(IconSize::Small)
20677                        // .disabled(!has_multiple_hunks)
20678                        .tooltip({
20679                            let focus_handle = editor.focus_handle(cx);
20680                            move |window, cx| {
20681                                Tooltip::for_action_in(
20682                                    "Previous Hunk",
20683                                    &GoToPreviousHunk,
20684                                    &focus_handle,
20685                                    window,
20686                                    cx,
20687                                )
20688                            }
20689                        })
20690                        .on_click({
20691                            let editor = editor.clone();
20692                            move |_event, window, cx| {
20693                                editor.update(cx, |editor, cx| {
20694                                    let snapshot = editor.snapshot(window, cx);
20695                                    let point =
20696                                        hunk_range.start.to_point(&snapshot.buffer_snapshot);
20697                                    editor.go_to_hunk_before_or_after_position(
20698                                        &snapshot,
20699                                        point,
20700                                        Direction::Prev,
20701                                        window,
20702                                        cx,
20703                                    );
20704                                    editor.expand_selected_diff_hunks(cx);
20705                                });
20706                            }
20707                        }),
20708                )
20709            },
20710        )
20711        .into_any_element()
20712}