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 edits = Vec::new();
 4748        let mut linked_edits = HashMap::<_, Vec<_>>::default();
 4749
 4750        for selection in &selections {
 4751            let edit = if selection.id == newest_anchor.id {
 4752                (replace_range_multibuffer.clone(), new_text.as_str())
 4753            } else {
 4754                let mut range = selection.range();
 4755                let mut text = new_text.as_str();
 4756
 4757                // if prefix is present, don't duplicate it
 4758                if snapshot.contains_str_at(range.start.saturating_sub(lookbehind), prefix) {
 4759                    text = &new_text[lookbehind.min(new_text.len())..];
 4760
 4761                    // if suffix is also present, mimic the newest cursor and replace it
 4762                    if selection.id != newest_anchor.id
 4763                        && snapshot.contains_str_at(range.end, suffix)
 4764                    {
 4765                        range.end += lookahead;
 4766                    }
 4767                }
 4768                (range, text)
 4769            };
 4770
 4771            edits.push(edit);
 4772
 4773            if !self.linked_edit_ranges.is_empty() {
 4774                let start_anchor = snapshot.anchor_before(selection.head());
 4775                let end_anchor = snapshot.anchor_after(selection.tail());
 4776                if let Some(ranges) = self
 4777                    .linked_editing_ranges_for(start_anchor.text_anchor..end_anchor.text_anchor, cx)
 4778                {
 4779                    for (buffer, edits) in ranges {
 4780                        linked_edits
 4781                            .entry(buffer.clone())
 4782                            .or_default()
 4783                            .extend(edits.into_iter().map(|range| (range, new_text.to_owned())));
 4784                    }
 4785                }
 4786            }
 4787        }
 4788
 4789        cx.emit(EditorEvent::InputHandled {
 4790            utf16_range_to_replace: None,
 4791            text: new_text.clone().into(),
 4792        });
 4793
 4794        self.transact(window, cx, |this, window, cx| {
 4795            if let Some(mut snippet) = snippet {
 4796                snippet.text = new_text.to_string();
 4797                let ranges = edits
 4798                    .iter()
 4799                    .map(|(range, _)| range.clone())
 4800                    .collect::<Vec<_>>();
 4801                this.insert_snippet(&ranges, snippet, window, cx).log_err();
 4802            } else {
 4803                this.buffer.update(cx, |buffer, cx| {
 4804                    let auto_indent = if completion.insert_text_mode == Some(InsertTextMode::AS_IS)
 4805                    {
 4806                        None
 4807                    } else {
 4808                        this.autoindent_mode.clone()
 4809                    };
 4810                    buffer.edit(edits, auto_indent, cx);
 4811                });
 4812            }
 4813            for (buffer, edits) in linked_edits {
 4814                buffer.update(cx, |buffer, cx| {
 4815                    let snapshot = buffer.snapshot();
 4816                    let edits = edits
 4817                        .into_iter()
 4818                        .map(|(range, text)| {
 4819                            use text::ToPoint as TP;
 4820                            let end_point = TP::to_point(&range.end, &snapshot);
 4821                            let start_point = TP::to_point(&range.start, &snapshot);
 4822                            (start_point..end_point, text)
 4823                        })
 4824                        .sorted_by_key(|(range, _)| range.start);
 4825                    buffer.edit(edits, None, cx);
 4826                })
 4827            }
 4828
 4829            this.refresh_inline_completion(true, false, window, cx);
 4830        });
 4831
 4832        let show_new_completions_on_confirm = completion
 4833            .confirm
 4834            .as_ref()
 4835            .map_or(false, |confirm| confirm(intent, window, cx));
 4836        if show_new_completions_on_confirm {
 4837            self.show_completions(&ShowCompletions { trigger: None }, window, cx);
 4838        }
 4839
 4840        let provider = self.completion_provider.as_ref()?;
 4841        drop(completion);
 4842        let apply_edits = provider.apply_additional_edits_for_completion(
 4843            buffer_handle,
 4844            completions_menu.completions.clone(),
 4845            candidate_id,
 4846            true,
 4847            cx,
 4848        );
 4849
 4850        let editor_settings = EditorSettings::get_global(cx);
 4851        if editor_settings.show_signature_help_after_edits || editor_settings.auto_signature_help {
 4852            // After the code completion is finished, users often want to know what signatures are needed.
 4853            // so we should automatically call signature_help
 4854            self.show_signature_help(&ShowSignatureHelp, window, cx);
 4855        }
 4856
 4857        Some(cx.foreground_executor().spawn(async move {
 4858            apply_edits.await?;
 4859            Ok(())
 4860        }))
 4861    }
 4862
 4863    fn prepare_code_actions_task(
 4864        &mut self,
 4865        action: &ToggleCodeActions,
 4866        window: &mut Window,
 4867        cx: &mut Context<Self>,
 4868    ) -> Task<Option<(Entity<Buffer>, CodeActionContents)>> {
 4869        let snapshot = self.snapshot(window, cx);
 4870        let multibuffer_point = action
 4871            .deployed_from_indicator
 4872            .map(|row| DisplayPoint::new(row, 0).to_point(&snapshot))
 4873            .unwrap_or_else(|| self.selections.newest::<Point>(cx).head());
 4874
 4875        let Some((buffer, buffer_row)) = snapshot
 4876            .buffer_snapshot
 4877            .buffer_line_for_row(MultiBufferRow(multibuffer_point.row))
 4878            .and_then(|(buffer_snapshot, range)| {
 4879                self.buffer
 4880                    .read(cx)
 4881                    .buffer(buffer_snapshot.remote_id())
 4882                    .map(|buffer| (buffer, range.start.row))
 4883            })
 4884        else {
 4885            return Task::ready(None);
 4886        };
 4887
 4888        let (_, code_actions) = self
 4889            .available_code_actions
 4890            .clone()
 4891            .and_then(|(location, code_actions)| {
 4892                let snapshot = location.buffer.read(cx).snapshot();
 4893                let point_range = location.range.to_point(&snapshot);
 4894                let point_range = point_range.start.row..=point_range.end.row;
 4895                if point_range.contains(&buffer_row) {
 4896                    Some((location, code_actions))
 4897                } else {
 4898                    None
 4899                }
 4900            })
 4901            .unzip();
 4902
 4903        let buffer_id = buffer.read(cx).remote_id();
 4904        let tasks = self
 4905            .tasks
 4906            .get(&(buffer_id, buffer_row))
 4907            .map(|t| Arc::new(t.to_owned()));
 4908
 4909        if tasks.is_none() && code_actions.is_none() {
 4910            return Task::ready(None);
 4911        }
 4912
 4913        self.completion_tasks.clear();
 4914        self.discard_inline_completion(false, cx);
 4915
 4916        let task_context = tasks
 4917            .as_ref()
 4918            .zip(self.project.clone())
 4919            .map(|(tasks, project)| {
 4920                Self::build_tasks_context(&project, &buffer, buffer_row, tasks, cx)
 4921            });
 4922
 4923        cx.spawn_in(window, async move |_, _| {
 4924            let task_context = match task_context {
 4925                Some(task_context) => task_context.await,
 4926                None => None,
 4927            };
 4928            let resolved_tasks = tasks.zip(task_context).map(|(tasks, task_context)| {
 4929                Rc::new(ResolvedTasks {
 4930                    templates: tasks.resolve(&task_context).collect(),
 4931                    position: snapshot
 4932                        .buffer_snapshot
 4933                        .anchor_before(Point::new(multibuffer_point.row, tasks.column)),
 4934                })
 4935            });
 4936            Some((
 4937                buffer,
 4938                CodeActionContents {
 4939                    actions: code_actions,
 4940                    tasks: resolved_tasks,
 4941                },
 4942            ))
 4943        })
 4944    }
 4945
 4946    pub fn toggle_code_actions(
 4947        &mut self,
 4948        action: &ToggleCodeActions,
 4949        window: &mut Window,
 4950        cx: &mut Context<Self>,
 4951    ) {
 4952        let mut context_menu = self.context_menu.borrow_mut();
 4953        if let Some(CodeContextMenu::CodeActions(code_actions)) = context_menu.as_ref() {
 4954            if code_actions.deployed_from_indicator == action.deployed_from_indicator {
 4955                // Toggle if we're selecting the same one
 4956                *context_menu = None;
 4957                cx.notify();
 4958                return;
 4959            } else {
 4960                // Otherwise, clear it and start a new one
 4961                *context_menu = None;
 4962                cx.notify();
 4963            }
 4964        }
 4965        drop(context_menu);
 4966
 4967        let deployed_from_indicator = action.deployed_from_indicator;
 4968        let mut task = self.code_actions_task.take();
 4969        let action = action.clone();
 4970
 4971        cx.spawn_in(window, async move |editor, cx| {
 4972            while let Some(prev_task) = task {
 4973                prev_task.await.log_err();
 4974                task = editor.update(cx, |this, _| this.code_actions_task.take())?;
 4975            }
 4976
 4977            let context_menu_task = editor.update_in(cx, |editor, window, cx| {
 4978                if !editor.focus_handle.is_focused(window) {
 4979                    return Some(Task::ready(Ok(())));
 4980                }
 4981                let debugger_flag = cx.has_flag::<Debugger>();
 4982                let code_actions_task = editor.prepare_code_actions_task(&action, window, cx);
 4983                Some(cx.spawn_in(window, async move |editor, cx| {
 4984                    if let Some((buffer, code_action_contents)) = code_actions_task.await {
 4985                        let spawn_straight_away =
 4986                            code_action_contents.tasks.as_ref().map_or(false, |tasks| {
 4987                                tasks
 4988                                    .templates
 4989                                    .iter()
 4990                                    .filter(|task| {
 4991                                        if matches!(task.1.task_type(), task::TaskType::Debug(_)) {
 4992                                            debugger_flag
 4993                                        } else {
 4994                                            true
 4995                                        }
 4996                                    })
 4997                                    .count()
 4998                                    == 1
 4999                            }) && code_action_contents
 5000                                .actions
 5001                                .as_ref()
 5002                                .map_or(true, |actions| actions.is_empty());
 5003                        if let Ok(task) = editor.update_in(cx, |editor, window, cx| {
 5004                            *editor.context_menu.borrow_mut() =
 5005                                Some(CodeContextMenu::CodeActions(CodeActionsMenu {
 5006                                    buffer,
 5007                                    actions: code_action_contents,
 5008                                    selected_item: Default::default(),
 5009                                    scroll_handle: UniformListScrollHandle::default(),
 5010                                    deployed_from_indicator,
 5011                                }));
 5012                            if spawn_straight_away {
 5013                                if let Some(task) = editor.confirm_code_action(
 5014                                    &ConfirmCodeAction {
 5015                                        item_ix: Some(0),
 5016                                        from_mouse_context_menu: false,
 5017                                    },
 5018                                    window,
 5019                                    cx,
 5020                                ) {
 5021                                    cx.notify();
 5022                                    return task;
 5023                                }
 5024                            }
 5025                            cx.notify();
 5026                            Task::ready(Ok(()))
 5027                        }) {
 5028                            task.await
 5029                        } else {
 5030                            Ok(())
 5031                        }
 5032                    } else {
 5033                        Ok(())
 5034                    }
 5035                }))
 5036            })?;
 5037            if let Some(task) = context_menu_task {
 5038                task.await?;
 5039            }
 5040
 5041            Ok::<_, anyhow::Error>(())
 5042        })
 5043        .detach_and_log_err(cx);
 5044    }
 5045
 5046    pub fn confirm_code_action(
 5047        &mut self,
 5048        action: &ConfirmCodeAction,
 5049        window: &mut Window,
 5050        cx: &mut Context<Self>,
 5051    ) -> Option<Task<Result<()>>> {
 5052        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
 5053
 5054        let (action, buffer) = if action.from_mouse_context_menu {
 5055            if let Some(menu) = self.mouse_context_menu.take() {
 5056                let code_action = menu.code_action?;
 5057                let index = action.item_ix?;
 5058                let action = code_action.actions.get(index)?;
 5059                (action, code_action.buffer)
 5060            } else {
 5061                return None;
 5062            }
 5063        } else {
 5064            if let CodeContextMenu::CodeActions(menu) = self.hide_context_menu(window, cx)? {
 5065                let action_ix = action.item_ix.unwrap_or(menu.selected_item);
 5066                let action = menu.actions.get(action_ix)?;
 5067                let buffer = menu.buffer;
 5068                (action, buffer)
 5069            } else {
 5070                return None;
 5071            }
 5072        };
 5073
 5074        let title = action.label();
 5075        let workspace = self.workspace()?;
 5076
 5077        match action {
 5078            CodeActionsItem::Task(task_source_kind, resolved_task) => {
 5079                match resolved_task.task_type() {
 5080                    task::TaskType::Script => workspace.update(cx, |workspace, cx| {
 5081                        workspace::tasks::schedule_resolved_task(
 5082                            workspace,
 5083                            task_source_kind,
 5084                            resolved_task,
 5085                            false,
 5086                            cx,
 5087                        );
 5088
 5089                        Some(Task::ready(Ok(())))
 5090                    }),
 5091                    task::TaskType::Debug(debug_args) => {
 5092                        if debug_args.locator.is_some() {
 5093                            workspace.update(cx, |workspace, cx| {
 5094                                workspace::tasks::schedule_resolved_task(
 5095                                    workspace,
 5096                                    task_source_kind,
 5097                                    resolved_task,
 5098                                    false,
 5099                                    cx,
 5100                                );
 5101                            });
 5102
 5103                            return Some(Task::ready(Ok(())));
 5104                        }
 5105
 5106                        if let Some(project) = self.project.as_ref() {
 5107                            project
 5108                                .update(cx, |project, cx| {
 5109                                    project.start_debug_session(
 5110                                        resolved_task.resolved_debug_adapter_config().unwrap(),
 5111                                        cx,
 5112                                    )
 5113                                })
 5114                                .detach_and_log_err(cx);
 5115                            Some(Task::ready(Ok(())))
 5116                        } else {
 5117                            Some(Task::ready(Ok(())))
 5118                        }
 5119                    }
 5120                }
 5121            }
 5122            CodeActionsItem::CodeAction {
 5123                excerpt_id,
 5124                action,
 5125                provider,
 5126            } => {
 5127                let apply_code_action =
 5128                    provider.apply_code_action(buffer, action, excerpt_id, true, window, cx);
 5129                let workspace = workspace.downgrade();
 5130                Some(cx.spawn_in(window, async move |editor, cx| {
 5131                    let project_transaction = apply_code_action.await?;
 5132                    Self::open_project_transaction(
 5133                        &editor,
 5134                        workspace,
 5135                        project_transaction,
 5136                        title,
 5137                        cx,
 5138                    )
 5139                    .await
 5140                }))
 5141            }
 5142        }
 5143    }
 5144
 5145    pub async fn open_project_transaction(
 5146        this: &WeakEntity<Editor>,
 5147        workspace: WeakEntity<Workspace>,
 5148        transaction: ProjectTransaction,
 5149        title: String,
 5150        cx: &mut AsyncWindowContext,
 5151    ) -> Result<()> {
 5152        let mut entries = transaction.0.into_iter().collect::<Vec<_>>();
 5153        cx.update(|_, cx| {
 5154            entries.sort_unstable_by_key(|(buffer, _)| {
 5155                buffer.read(cx).file().map(|f| f.path().clone())
 5156            });
 5157        })?;
 5158
 5159        // If the project transaction's edits are all contained within this editor, then
 5160        // avoid opening a new editor to display them.
 5161
 5162        if let Some((buffer, transaction)) = entries.first() {
 5163            if entries.len() == 1 {
 5164                let excerpt = this.update(cx, |editor, cx| {
 5165                    editor
 5166                        .buffer()
 5167                        .read(cx)
 5168                        .excerpt_containing(editor.selections.newest_anchor().head(), cx)
 5169                })?;
 5170                if let Some((_, excerpted_buffer, excerpt_range)) = excerpt {
 5171                    if excerpted_buffer == *buffer {
 5172                        let all_edits_within_excerpt = buffer.read_with(cx, |buffer, _| {
 5173                            let excerpt_range = excerpt_range.to_offset(buffer);
 5174                            buffer
 5175                                .edited_ranges_for_transaction::<usize>(transaction)
 5176                                .all(|range| {
 5177                                    excerpt_range.start <= range.start
 5178                                        && excerpt_range.end >= range.end
 5179                                })
 5180                        })?;
 5181
 5182                        if all_edits_within_excerpt {
 5183                            return Ok(());
 5184                        }
 5185                    }
 5186                }
 5187            }
 5188        } else {
 5189            return Ok(());
 5190        }
 5191
 5192        let mut ranges_to_highlight = Vec::new();
 5193        let excerpt_buffer = cx.new(|cx| {
 5194            let mut multibuffer = MultiBuffer::new(Capability::ReadWrite).with_title(title);
 5195            for (buffer_handle, transaction) in &entries {
 5196                let edited_ranges = buffer_handle
 5197                    .read(cx)
 5198                    .edited_ranges_for_transaction::<Point>(transaction)
 5199                    .collect::<Vec<_>>();
 5200                let (ranges, _) = multibuffer.set_excerpts_for_path(
 5201                    PathKey::for_buffer(buffer_handle, cx),
 5202                    buffer_handle.clone(),
 5203                    edited_ranges,
 5204                    DEFAULT_MULTIBUFFER_CONTEXT,
 5205                    cx,
 5206                );
 5207
 5208                ranges_to_highlight.extend(ranges);
 5209            }
 5210            multibuffer.push_transaction(entries.iter().map(|(b, t)| (b, t)), cx);
 5211            multibuffer
 5212        })?;
 5213
 5214        workspace.update_in(cx, |workspace, window, cx| {
 5215            let project = workspace.project().clone();
 5216            let editor =
 5217                cx.new(|cx| Editor::for_multibuffer(excerpt_buffer, Some(project), window, cx));
 5218            workspace.add_item_to_active_pane(Box::new(editor.clone()), None, true, window, cx);
 5219            editor.update(cx, |editor, cx| {
 5220                editor.highlight_background::<Self>(
 5221                    &ranges_to_highlight,
 5222                    |theme| theme.editor_highlighted_line_background,
 5223                    cx,
 5224                );
 5225            });
 5226        })?;
 5227
 5228        Ok(())
 5229    }
 5230
 5231    pub fn clear_code_action_providers(&mut self) {
 5232        self.code_action_providers.clear();
 5233        self.available_code_actions.take();
 5234    }
 5235
 5236    pub fn add_code_action_provider(
 5237        &mut self,
 5238        provider: Rc<dyn CodeActionProvider>,
 5239        window: &mut Window,
 5240        cx: &mut Context<Self>,
 5241    ) {
 5242        if self
 5243            .code_action_providers
 5244            .iter()
 5245            .any(|existing_provider| existing_provider.id() == provider.id())
 5246        {
 5247            return;
 5248        }
 5249
 5250        self.code_action_providers.push(provider);
 5251        self.refresh_code_actions(window, cx);
 5252    }
 5253
 5254    pub fn remove_code_action_provider(
 5255        &mut self,
 5256        id: Arc<str>,
 5257        window: &mut Window,
 5258        cx: &mut Context<Self>,
 5259    ) {
 5260        self.code_action_providers
 5261            .retain(|provider| provider.id() != id);
 5262        self.refresh_code_actions(window, cx);
 5263    }
 5264
 5265    fn refresh_code_actions(&mut self, window: &mut Window, cx: &mut Context<Self>) -> Option<()> {
 5266        let newest_selection = self.selections.newest_anchor().clone();
 5267        let newest_selection_adjusted = self.selections.newest_adjusted(cx).clone();
 5268        let buffer = self.buffer.read(cx);
 5269        if newest_selection.head().diff_base_anchor.is_some() {
 5270            return None;
 5271        }
 5272        let (start_buffer, start) =
 5273            buffer.text_anchor_for_position(newest_selection_adjusted.start, cx)?;
 5274        let (end_buffer, end) =
 5275            buffer.text_anchor_for_position(newest_selection_adjusted.end, cx)?;
 5276        if start_buffer != end_buffer {
 5277            return None;
 5278        }
 5279
 5280        self.code_actions_task = Some(cx.spawn_in(window, async move |this, cx| {
 5281            cx.background_executor()
 5282                .timer(CODE_ACTIONS_DEBOUNCE_TIMEOUT)
 5283                .await;
 5284
 5285            let (providers, tasks) = this.update_in(cx, |this, window, cx| {
 5286                let providers = this.code_action_providers.clone();
 5287                let tasks = this
 5288                    .code_action_providers
 5289                    .iter()
 5290                    .map(|provider| provider.code_actions(&start_buffer, start..end, window, cx))
 5291                    .collect::<Vec<_>>();
 5292                (providers, tasks)
 5293            })?;
 5294
 5295            let mut actions = Vec::new();
 5296            for (provider, provider_actions) in
 5297                providers.into_iter().zip(future::join_all(tasks).await)
 5298            {
 5299                if let Some(provider_actions) = provider_actions.log_err() {
 5300                    actions.extend(provider_actions.into_iter().map(|action| {
 5301                        AvailableCodeAction {
 5302                            excerpt_id: newest_selection.start.excerpt_id,
 5303                            action,
 5304                            provider: provider.clone(),
 5305                        }
 5306                    }));
 5307                }
 5308            }
 5309
 5310            this.update(cx, |this, cx| {
 5311                this.available_code_actions = if actions.is_empty() {
 5312                    None
 5313                } else {
 5314                    Some((
 5315                        Location {
 5316                            buffer: start_buffer,
 5317                            range: start..end,
 5318                        },
 5319                        actions.into(),
 5320                    ))
 5321                };
 5322                cx.notify();
 5323            })
 5324        }));
 5325        None
 5326    }
 5327
 5328    fn start_inline_blame_timer(&mut self, window: &mut Window, cx: &mut Context<Self>) {
 5329        if let Some(delay) = ProjectSettings::get_global(cx).git.inline_blame_delay() {
 5330            self.show_git_blame_inline = false;
 5331
 5332            self.show_git_blame_inline_delay_task =
 5333                Some(cx.spawn_in(window, async move |this, cx| {
 5334                    cx.background_executor().timer(delay).await;
 5335
 5336                    this.update(cx, |this, cx| {
 5337                        this.show_git_blame_inline = true;
 5338                        cx.notify();
 5339                    })
 5340                    .log_err();
 5341                }));
 5342        }
 5343    }
 5344
 5345    fn refresh_document_highlights(&mut self, cx: &mut Context<Self>) -> Option<()> {
 5346        if self.pending_rename.is_some() {
 5347            return None;
 5348        }
 5349
 5350        let provider = self.semantics_provider.clone()?;
 5351        let buffer = self.buffer.read(cx);
 5352        let newest_selection = self.selections.newest_anchor().clone();
 5353        let cursor_position = newest_selection.head();
 5354        let (cursor_buffer, cursor_buffer_position) =
 5355            buffer.text_anchor_for_position(cursor_position, cx)?;
 5356        let (tail_buffer, _) = buffer.text_anchor_for_position(newest_selection.tail(), cx)?;
 5357        if cursor_buffer != tail_buffer {
 5358            return None;
 5359        }
 5360        let debounce = EditorSettings::get_global(cx).lsp_highlight_debounce;
 5361        self.document_highlights_task = Some(cx.spawn(async move |this, cx| {
 5362            cx.background_executor()
 5363                .timer(Duration::from_millis(debounce))
 5364                .await;
 5365
 5366            let highlights = if let Some(highlights) = cx
 5367                .update(|cx| {
 5368                    provider.document_highlights(&cursor_buffer, cursor_buffer_position, cx)
 5369                })
 5370                .ok()
 5371                .flatten()
 5372            {
 5373                highlights.await.log_err()
 5374            } else {
 5375                None
 5376            };
 5377
 5378            if let Some(highlights) = highlights {
 5379                this.update(cx, |this, cx| {
 5380                    if this.pending_rename.is_some() {
 5381                        return;
 5382                    }
 5383
 5384                    let buffer_id = cursor_position.buffer_id;
 5385                    let buffer = this.buffer.read(cx);
 5386                    if !buffer
 5387                        .text_anchor_for_position(cursor_position, cx)
 5388                        .map_or(false, |(buffer, _)| buffer == cursor_buffer)
 5389                    {
 5390                        return;
 5391                    }
 5392
 5393                    let cursor_buffer_snapshot = cursor_buffer.read(cx);
 5394                    let mut write_ranges = Vec::new();
 5395                    let mut read_ranges = Vec::new();
 5396                    for highlight in highlights {
 5397                        for (excerpt_id, excerpt_range) in
 5398                            buffer.excerpts_for_buffer(cursor_buffer.read(cx).remote_id(), cx)
 5399                        {
 5400                            let start = highlight
 5401                                .range
 5402                                .start
 5403                                .max(&excerpt_range.context.start, cursor_buffer_snapshot);
 5404                            let end = highlight
 5405                                .range
 5406                                .end
 5407                                .min(&excerpt_range.context.end, cursor_buffer_snapshot);
 5408                            if start.cmp(&end, cursor_buffer_snapshot).is_ge() {
 5409                                continue;
 5410                            }
 5411
 5412                            let range = Anchor {
 5413                                buffer_id,
 5414                                excerpt_id,
 5415                                text_anchor: start,
 5416                                diff_base_anchor: None,
 5417                            }..Anchor {
 5418                                buffer_id,
 5419                                excerpt_id,
 5420                                text_anchor: end,
 5421                                diff_base_anchor: None,
 5422                            };
 5423                            if highlight.kind == lsp::DocumentHighlightKind::WRITE {
 5424                                write_ranges.push(range);
 5425                            } else {
 5426                                read_ranges.push(range);
 5427                            }
 5428                        }
 5429                    }
 5430
 5431                    this.highlight_background::<DocumentHighlightRead>(
 5432                        &read_ranges,
 5433                        |theme| theme.editor_document_highlight_read_background,
 5434                        cx,
 5435                    );
 5436                    this.highlight_background::<DocumentHighlightWrite>(
 5437                        &write_ranges,
 5438                        |theme| theme.editor_document_highlight_write_background,
 5439                        cx,
 5440                    );
 5441                    cx.notify();
 5442                })
 5443                .log_err();
 5444            }
 5445        }));
 5446        None
 5447    }
 5448
 5449    pub fn refresh_selected_text_highlights(
 5450        &mut self,
 5451        window: &mut Window,
 5452        cx: &mut Context<Editor>,
 5453    ) {
 5454        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 5455            return;
 5456        }
 5457        self.selection_highlight_task.take();
 5458        if !EditorSettings::get_global(cx).selection_highlight {
 5459            self.clear_background_highlights::<SelectedTextHighlight>(cx);
 5460            return;
 5461        }
 5462        if self.selections.count() != 1 || self.selections.line_mode {
 5463            self.clear_background_highlights::<SelectedTextHighlight>(cx);
 5464            return;
 5465        }
 5466        let selection = self.selections.newest::<Point>(cx);
 5467        if selection.is_empty() || selection.start.row != selection.end.row {
 5468            self.clear_background_highlights::<SelectedTextHighlight>(cx);
 5469            return;
 5470        }
 5471        let debounce = EditorSettings::get_global(cx).selection_highlight_debounce;
 5472        self.selection_highlight_task = Some(cx.spawn_in(window, async move |editor, cx| {
 5473            cx.background_executor()
 5474                .timer(Duration::from_millis(debounce))
 5475                .await;
 5476            let Some(Some(matches_task)) = editor
 5477                .update_in(cx, |editor, _, cx| {
 5478                    if editor.selections.count() != 1 || editor.selections.line_mode {
 5479                        editor.clear_background_highlights::<SelectedTextHighlight>(cx);
 5480                        return None;
 5481                    }
 5482                    let selection = editor.selections.newest::<Point>(cx);
 5483                    if selection.is_empty() || selection.start.row != selection.end.row {
 5484                        editor.clear_background_highlights::<SelectedTextHighlight>(cx);
 5485                        return None;
 5486                    }
 5487                    let buffer = editor.buffer().read(cx).snapshot(cx);
 5488                    let query = buffer.text_for_range(selection.range()).collect::<String>();
 5489                    if query.trim().is_empty() {
 5490                        editor.clear_background_highlights::<SelectedTextHighlight>(cx);
 5491                        return None;
 5492                    }
 5493                    Some(cx.background_spawn(async move {
 5494                        let mut ranges = Vec::new();
 5495                        let selection_anchors = selection.range().to_anchors(&buffer);
 5496                        for range in [buffer.anchor_before(0)..buffer.anchor_after(buffer.len())] {
 5497                            for (search_buffer, search_range, excerpt_id) in
 5498                                buffer.range_to_buffer_ranges(range)
 5499                            {
 5500                                ranges.extend(
 5501                                    project::search::SearchQuery::text(
 5502                                        query.clone(),
 5503                                        false,
 5504                                        false,
 5505                                        false,
 5506                                        Default::default(),
 5507                                        Default::default(),
 5508                                        None,
 5509                                    )
 5510                                    .unwrap()
 5511                                    .search(search_buffer, Some(search_range.clone()))
 5512                                    .await
 5513                                    .into_iter()
 5514                                    .filter_map(
 5515                                        |match_range| {
 5516                                            let start = search_buffer.anchor_after(
 5517                                                search_range.start + match_range.start,
 5518                                            );
 5519                                            let end = search_buffer.anchor_before(
 5520                                                search_range.start + match_range.end,
 5521                                            );
 5522                                            let range = Anchor::range_in_buffer(
 5523                                                excerpt_id,
 5524                                                search_buffer.remote_id(),
 5525                                                start..end,
 5526                                            );
 5527                                            (range != selection_anchors).then_some(range)
 5528                                        },
 5529                                    ),
 5530                                );
 5531                            }
 5532                        }
 5533                        ranges
 5534                    }))
 5535                })
 5536                .log_err()
 5537            else {
 5538                return;
 5539            };
 5540            let matches = matches_task.await;
 5541            editor
 5542                .update_in(cx, |editor, _, cx| {
 5543                    editor.clear_background_highlights::<SelectedTextHighlight>(cx);
 5544                    if !matches.is_empty() {
 5545                        editor.highlight_background::<SelectedTextHighlight>(
 5546                            &matches,
 5547                            |theme| theme.editor_document_highlight_bracket_background,
 5548                            cx,
 5549                        )
 5550                    }
 5551                })
 5552                .log_err();
 5553        }));
 5554    }
 5555
 5556    pub fn refresh_inline_completion(
 5557        &mut self,
 5558        debounce: bool,
 5559        user_requested: bool,
 5560        window: &mut Window,
 5561        cx: &mut Context<Self>,
 5562    ) -> Option<()> {
 5563        let provider = self.edit_prediction_provider()?;
 5564        let cursor = self.selections.newest_anchor().head();
 5565        let (buffer, cursor_buffer_position) =
 5566            self.buffer.read(cx).text_anchor_for_position(cursor, cx)?;
 5567
 5568        if !self.edit_predictions_enabled_in_buffer(&buffer, cursor_buffer_position, cx) {
 5569            self.discard_inline_completion(false, cx);
 5570            return None;
 5571        }
 5572
 5573        if !user_requested
 5574            && (!self.should_show_edit_predictions()
 5575                || !self.is_focused(window)
 5576                || buffer.read(cx).is_empty())
 5577        {
 5578            self.discard_inline_completion(false, cx);
 5579            return None;
 5580        }
 5581
 5582        self.update_visible_inline_completion(window, cx);
 5583        provider.refresh(
 5584            self.project.clone(),
 5585            buffer,
 5586            cursor_buffer_position,
 5587            debounce,
 5588            cx,
 5589        );
 5590        Some(())
 5591    }
 5592
 5593    fn show_edit_predictions_in_menu(&self) -> bool {
 5594        match self.edit_prediction_settings {
 5595            EditPredictionSettings::Disabled => false,
 5596            EditPredictionSettings::Enabled { show_in_menu, .. } => show_in_menu,
 5597        }
 5598    }
 5599
 5600    pub fn edit_predictions_enabled(&self) -> bool {
 5601        match self.edit_prediction_settings {
 5602            EditPredictionSettings::Disabled => false,
 5603            EditPredictionSettings::Enabled { .. } => true,
 5604        }
 5605    }
 5606
 5607    fn edit_prediction_requires_modifier(&self) -> bool {
 5608        match self.edit_prediction_settings {
 5609            EditPredictionSettings::Disabled => false,
 5610            EditPredictionSettings::Enabled {
 5611                preview_requires_modifier,
 5612                ..
 5613            } => preview_requires_modifier,
 5614        }
 5615    }
 5616
 5617    pub fn update_edit_prediction_settings(&mut self, cx: &mut Context<Self>) {
 5618        if self.edit_prediction_provider.is_none() {
 5619            self.edit_prediction_settings = EditPredictionSettings::Disabled;
 5620        } else {
 5621            let selection = self.selections.newest_anchor();
 5622            let cursor = selection.head();
 5623
 5624            if let Some((buffer, cursor_buffer_position)) =
 5625                self.buffer.read(cx).text_anchor_for_position(cursor, cx)
 5626            {
 5627                self.edit_prediction_settings =
 5628                    self.edit_prediction_settings_at_position(&buffer, cursor_buffer_position, cx);
 5629            }
 5630        }
 5631    }
 5632
 5633    fn edit_prediction_settings_at_position(
 5634        &self,
 5635        buffer: &Entity<Buffer>,
 5636        buffer_position: language::Anchor,
 5637        cx: &App,
 5638    ) -> EditPredictionSettings {
 5639        if !self.mode.is_full()
 5640            || !self.show_inline_completions_override.unwrap_or(true)
 5641            || self.inline_completions_disabled_in_scope(buffer, buffer_position, cx)
 5642        {
 5643            return EditPredictionSettings::Disabled;
 5644        }
 5645
 5646        let buffer = buffer.read(cx);
 5647
 5648        let file = buffer.file();
 5649
 5650        if !language_settings(buffer.language().map(|l| l.name()), file, cx).show_edit_predictions {
 5651            return EditPredictionSettings::Disabled;
 5652        };
 5653
 5654        let by_provider = matches!(
 5655            self.menu_inline_completions_policy,
 5656            MenuInlineCompletionsPolicy::ByProvider
 5657        );
 5658
 5659        let show_in_menu = by_provider
 5660            && self
 5661                .edit_prediction_provider
 5662                .as_ref()
 5663                .map_or(false, |provider| {
 5664                    provider.provider.show_completions_in_menu()
 5665                });
 5666
 5667        let preview_requires_modifier =
 5668            all_language_settings(file, cx).edit_predictions_mode() == EditPredictionsMode::Subtle;
 5669
 5670        EditPredictionSettings::Enabled {
 5671            show_in_menu,
 5672            preview_requires_modifier,
 5673        }
 5674    }
 5675
 5676    fn should_show_edit_predictions(&self) -> bool {
 5677        self.snippet_stack.is_empty() && self.edit_predictions_enabled()
 5678    }
 5679
 5680    pub fn edit_prediction_preview_is_active(&self) -> bool {
 5681        matches!(
 5682            self.edit_prediction_preview,
 5683            EditPredictionPreview::Active { .. }
 5684        )
 5685    }
 5686
 5687    pub fn edit_predictions_enabled_at_cursor(&self, cx: &App) -> bool {
 5688        let cursor = self.selections.newest_anchor().head();
 5689        if let Some((buffer, cursor_position)) =
 5690            self.buffer.read(cx).text_anchor_for_position(cursor, cx)
 5691        {
 5692            self.edit_predictions_enabled_in_buffer(&buffer, cursor_position, cx)
 5693        } else {
 5694            false
 5695        }
 5696    }
 5697
 5698    fn edit_predictions_enabled_in_buffer(
 5699        &self,
 5700        buffer: &Entity<Buffer>,
 5701        buffer_position: language::Anchor,
 5702        cx: &App,
 5703    ) -> bool {
 5704        maybe!({
 5705            if self.read_only(cx) {
 5706                return Some(false);
 5707            }
 5708            let provider = self.edit_prediction_provider()?;
 5709            if !provider.is_enabled(&buffer, buffer_position, cx) {
 5710                return Some(false);
 5711            }
 5712            let buffer = buffer.read(cx);
 5713            let Some(file) = buffer.file() else {
 5714                return Some(true);
 5715            };
 5716            let settings = all_language_settings(Some(file), cx);
 5717            Some(settings.edit_predictions_enabled_for_file(file, cx))
 5718        })
 5719        .unwrap_or(false)
 5720    }
 5721
 5722    fn cycle_inline_completion(
 5723        &mut self,
 5724        direction: Direction,
 5725        window: &mut Window,
 5726        cx: &mut Context<Self>,
 5727    ) -> Option<()> {
 5728        let provider = self.edit_prediction_provider()?;
 5729        let cursor = self.selections.newest_anchor().head();
 5730        let (buffer, cursor_buffer_position) =
 5731            self.buffer.read(cx).text_anchor_for_position(cursor, cx)?;
 5732        if self.inline_completions_hidden_for_vim_mode || !self.should_show_edit_predictions() {
 5733            return None;
 5734        }
 5735
 5736        provider.cycle(buffer, cursor_buffer_position, direction, cx);
 5737        self.update_visible_inline_completion(window, cx);
 5738
 5739        Some(())
 5740    }
 5741
 5742    pub fn show_inline_completion(
 5743        &mut self,
 5744        _: &ShowEditPrediction,
 5745        window: &mut Window,
 5746        cx: &mut Context<Self>,
 5747    ) {
 5748        if !self.has_active_inline_completion() {
 5749            self.refresh_inline_completion(false, true, window, cx);
 5750            return;
 5751        }
 5752
 5753        self.update_visible_inline_completion(window, cx);
 5754    }
 5755
 5756    pub fn display_cursor_names(
 5757        &mut self,
 5758        _: &DisplayCursorNames,
 5759        window: &mut Window,
 5760        cx: &mut Context<Self>,
 5761    ) {
 5762        self.show_cursor_names(window, cx);
 5763    }
 5764
 5765    fn show_cursor_names(&mut self, window: &mut Window, cx: &mut Context<Self>) {
 5766        self.show_cursor_names = true;
 5767        cx.notify();
 5768        cx.spawn_in(window, async move |this, cx| {
 5769            cx.background_executor().timer(CURSORS_VISIBLE_FOR).await;
 5770            this.update(cx, |this, cx| {
 5771                this.show_cursor_names = false;
 5772                cx.notify()
 5773            })
 5774            .ok()
 5775        })
 5776        .detach();
 5777    }
 5778
 5779    pub fn next_edit_prediction(
 5780        &mut self,
 5781        _: &NextEditPrediction,
 5782        window: &mut Window,
 5783        cx: &mut Context<Self>,
 5784    ) {
 5785        if self.has_active_inline_completion() {
 5786            self.cycle_inline_completion(Direction::Next, window, cx);
 5787        } else {
 5788            let is_copilot_disabled = self
 5789                .refresh_inline_completion(false, true, window, cx)
 5790                .is_none();
 5791            if is_copilot_disabled {
 5792                cx.propagate();
 5793            }
 5794        }
 5795    }
 5796
 5797    pub fn previous_edit_prediction(
 5798        &mut self,
 5799        _: &PreviousEditPrediction,
 5800        window: &mut Window,
 5801        cx: &mut Context<Self>,
 5802    ) {
 5803        if self.has_active_inline_completion() {
 5804            self.cycle_inline_completion(Direction::Prev, window, cx);
 5805        } else {
 5806            let is_copilot_disabled = self
 5807                .refresh_inline_completion(false, true, window, cx)
 5808                .is_none();
 5809            if is_copilot_disabled {
 5810                cx.propagate();
 5811            }
 5812        }
 5813    }
 5814
 5815    pub fn accept_edit_prediction(
 5816        &mut self,
 5817        _: &AcceptEditPrediction,
 5818        window: &mut Window,
 5819        cx: &mut Context<Self>,
 5820    ) {
 5821        if self.show_edit_predictions_in_menu() {
 5822            self.hide_context_menu(window, cx);
 5823        }
 5824
 5825        let Some(active_inline_completion) = self.active_inline_completion.as_ref() else {
 5826            return;
 5827        };
 5828
 5829        self.report_inline_completion_event(
 5830            active_inline_completion.completion_id.clone(),
 5831            true,
 5832            cx,
 5833        );
 5834
 5835        match &active_inline_completion.completion {
 5836            InlineCompletion::Move { target, .. } => {
 5837                let target = *target;
 5838
 5839                if let Some(position_map) = &self.last_position_map {
 5840                    if position_map
 5841                        .visible_row_range
 5842                        .contains(&target.to_display_point(&position_map.snapshot).row())
 5843                        || !self.edit_prediction_requires_modifier()
 5844                    {
 5845                        self.unfold_ranges(&[target..target], true, false, cx);
 5846                        // Note that this is also done in vim's handler of the Tab action.
 5847                        self.change_selections(
 5848                            Some(Autoscroll::newest()),
 5849                            window,
 5850                            cx,
 5851                            |selections| {
 5852                                selections.select_anchor_ranges([target..target]);
 5853                            },
 5854                        );
 5855                        self.clear_row_highlights::<EditPredictionPreview>();
 5856
 5857                        self.edit_prediction_preview
 5858                            .set_previous_scroll_position(None);
 5859                    } else {
 5860                        self.edit_prediction_preview
 5861                            .set_previous_scroll_position(Some(
 5862                                position_map.snapshot.scroll_anchor,
 5863                            ));
 5864
 5865                        self.highlight_rows::<EditPredictionPreview>(
 5866                            target..target,
 5867                            cx.theme().colors().editor_highlighted_line_background,
 5868                            true,
 5869                            cx,
 5870                        );
 5871                        self.request_autoscroll(Autoscroll::fit(), cx);
 5872                    }
 5873                }
 5874            }
 5875            InlineCompletion::Edit { edits, .. } => {
 5876                if let Some(provider) = self.edit_prediction_provider() {
 5877                    provider.accept(cx);
 5878                }
 5879
 5880                let snapshot = self.buffer.read(cx).snapshot(cx);
 5881                let last_edit_end = edits.last().unwrap().0.end.bias_right(&snapshot);
 5882
 5883                self.buffer.update(cx, |buffer, cx| {
 5884                    buffer.edit(edits.iter().cloned(), None, cx)
 5885                });
 5886
 5887                self.change_selections(None, window, cx, |s| {
 5888                    s.select_anchor_ranges([last_edit_end..last_edit_end])
 5889                });
 5890
 5891                self.update_visible_inline_completion(window, cx);
 5892                if self.active_inline_completion.is_none() {
 5893                    self.refresh_inline_completion(true, true, window, cx);
 5894                }
 5895
 5896                cx.notify();
 5897            }
 5898        }
 5899
 5900        self.edit_prediction_requires_modifier_in_indent_conflict = false;
 5901    }
 5902
 5903    pub fn accept_partial_inline_completion(
 5904        &mut self,
 5905        _: &AcceptPartialEditPrediction,
 5906        window: &mut Window,
 5907        cx: &mut Context<Self>,
 5908    ) {
 5909        let Some(active_inline_completion) = self.active_inline_completion.as_ref() else {
 5910            return;
 5911        };
 5912        if self.selections.count() != 1 {
 5913            return;
 5914        }
 5915
 5916        self.report_inline_completion_event(
 5917            active_inline_completion.completion_id.clone(),
 5918            true,
 5919            cx,
 5920        );
 5921
 5922        match &active_inline_completion.completion {
 5923            InlineCompletion::Move { target, .. } => {
 5924                let target = *target;
 5925                self.change_selections(Some(Autoscroll::newest()), window, cx, |selections| {
 5926                    selections.select_anchor_ranges([target..target]);
 5927                });
 5928            }
 5929            InlineCompletion::Edit { edits, .. } => {
 5930                // Find an insertion that starts at the cursor position.
 5931                let snapshot = self.buffer.read(cx).snapshot(cx);
 5932                let cursor_offset = self.selections.newest::<usize>(cx).head();
 5933                let insertion = edits.iter().find_map(|(range, text)| {
 5934                    let range = range.to_offset(&snapshot);
 5935                    if range.is_empty() && range.start == cursor_offset {
 5936                        Some(text)
 5937                    } else {
 5938                        None
 5939                    }
 5940                });
 5941
 5942                if let Some(text) = insertion {
 5943                    let mut partial_completion = text
 5944                        .chars()
 5945                        .by_ref()
 5946                        .take_while(|c| c.is_alphabetic())
 5947                        .collect::<String>();
 5948                    if partial_completion.is_empty() {
 5949                        partial_completion = text
 5950                            .chars()
 5951                            .by_ref()
 5952                            .take_while(|c| c.is_whitespace() || !c.is_alphabetic())
 5953                            .collect::<String>();
 5954                    }
 5955
 5956                    cx.emit(EditorEvent::InputHandled {
 5957                        utf16_range_to_replace: None,
 5958                        text: partial_completion.clone().into(),
 5959                    });
 5960
 5961                    self.insert_with_autoindent_mode(&partial_completion, None, window, cx);
 5962
 5963                    self.refresh_inline_completion(true, true, window, cx);
 5964                    cx.notify();
 5965                } else {
 5966                    self.accept_edit_prediction(&Default::default(), window, cx);
 5967                }
 5968            }
 5969        }
 5970    }
 5971
 5972    fn discard_inline_completion(
 5973        &mut self,
 5974        should_report_inline_completion_event: bool,
 5975        cx: &mut Context<Self>,
 5976    ) -> bool {
 5977        if should_report_inline_completion_event {
 5978            let completion_id = self
 5979                .active_inline_completion
 5980                .as_ref()
 5981                .and_then(|active_completion| active_completion.completion_id.clone());
 5982
 5983            self.report_inline_completion_event(completion_id, false, cx);
 5984        }
 5985
 5986        if let Some(provider) = self.edit_prediction_provider() {
 5987            provider.discard(cx);
 5988        }
 5989
 5990        self.take_active_inline_completion(cx)
 5991    }
 5992
 5993    fn report_inline_completion_event(&self, id: Option<SharedString>, accepted: bool, cx: &App) {
 5994        let Some(provider) = self.edit_prediction_provider() else {
 5995            return;
 5996        };
 5997
 5998        let Some((_, buffer, _)) = self
 5999            .buffer
 6000            .read(cx)
 6001            .excerpt_containing(self.selections.newest_anchor().head(), cx)
 6002        else {
 6003            return;
 6004        };
 6005
 6006        let extension = buffer
 6007            .read(cx)
 6008            .file()
 6009            .and_then(|file| Some(file.path().extension()?.to_string_lossy().to_string()));
 6010
 6011        let event_type = match accepted {
 6012            true => "Edit Prediction Accepted",
 6013            false => "Edit Prediction Discarded",
 6014        };
 6015        telemetry::event!(
 6016            event_type,
 6017            provider = provider.name(),
 6018            prediction_id = id,
 6019            suggestion_accepted = accepted,
 6020            file_extension = extension,
 6021        );
 6022    }
 6023
 6024    pub fn has_active_inline_completion(&self) -> bool {
 6025        self.active_inline_completion.is_some()
 6026    }
 6027
 6028    fn take_active_inline_completion(&mut self, cx: &mut Context<Self>) -> bool {
 6029        let Some(active_inline_completion) = self.active_inline_completion.take() else {
 6030            return false;
 6031        };
 6032
 6033        self.splice_inlays(&active_inline_completion.inlay_ids, Default::default(), cx);
 6034        self.clear_highlights::<InlineCompletionHighlight>(cx);
 6035        self.stale_inline_completion_in_menu = Some(active_inline_completion);
 6036        true
 6037    }
 6038
 6039    /// Returns true when we're displaying the edit prediction popover below the cursor
 6040    /// like we are not previewing and the LSP autocomplete menu is visible
 6041    /// or we are in `when_holding_modifier` mode.
 6042    pub fn edit_prediction_visible_in_cursor_popover(&self, has_completion: bool) -> bool {
 6043        if self.edit_prediction_preview_is_active()
 6044            || !self.show_edit_predictions_in_menu()
 6045            || !self.edit_predictions_enabled()
 6046        {
 6047            return false;
 6048        }
 6049
 6050        if self.has_visible_completions_menu() {
 6051            return true;
 6052        }
 6053
 6054        has_completion && self.edit_prediction_requires_modifier()
 6055    }
 6056
 6057    fn handle_modifiers_changed(
 6058        &mut self,
 6059        modifiers: Modifiers,
 6060        position_map: &PositionMap,
 6061        window: &mut Window,
 6062        cx: &mut Context<Self>,
 6063    ) {
 6064        if self.show_edit_predictions_in_menu() {
 6065            self.update_edit_prediction_preview(&modifiers, window, cx);
 6066        }
 6067
 6068        self.update_selection_mode(&modifiers, position_map, window, cx);
 6069
 6070        let mouse_position = window.mouse_position();
 6071        if !position_map.text_hitbox.is_hovered(window) {
 6072            return;
 6073        }
 6074
 6075        self.update_hovered_link(
 6076            position_map.point_for_position(mouse_position),
 6077            &position_map.snapshot,
 6078            modifiers,
 6079            window,
 6080            cx,
 6081        )
 6082    }
 6083
 6084    fn update_selection_mode(
 6085        &mut self,
 6086        modifiers: &Modifiers,
 6087        position_map: &PositionMap,
 6088        window: &mut Window,
 6089        cx: &mut Context<Self>,
 6090    ) {
 6091        if modifiers != &COLUMNAR_SELECTION_MODIFIERS || self.selections.pending.is_none() {
 6092            return;
 6093        }
 6094
 6095        let mouse_position = window.mouse_position();
 6096        let point_for_position = position_map.point_for_position(mouse_position);
 6097        let position = point_for_position.previous_valid;
 6098
 6099        self.select(
 6100            SelectPhase::BeginColumnar {
 6101                position,
 6102                reset: false,
 6103                goal_column: point_for_position.exact_unclipped.column(),
 6104            },
 6105            window,
 6106            cx,
 6107        );
 6108    }
 6109
 6110    fn update_edit_prediction_preview(
 6111        &mut self,
 6112        modifiers: &Modifiers,
 6113        window: &mut Window,
 6114        cx: &mut Context<Self>,
 6115    ) {
 6116        let accept_keybind = self.accept_edit_prediction_keybind(window, cx);
 6117        let Some(accept_keystroke) = accept_keybind.keystroke() else {
 6118            return;
 6119        };
 6120
 6121        if &accept_keystroke.modifiers == modifiers && accept_keystroke.modifiers.modified() {
 6122            if matches!(
 6123                self.edit_prediction_preview,
 6124                EditPredictionPreview::Inactive { .. }
 6125            ) {
 6126                self.edit_prediction_preview = EditPredictionPreview::Active {
 6127                    previous_scroll_position: None,
 6128                    since: Instant::now(),
 6129                };
 6130
 6131                self.update_visible_inline_completion(window, cx);
 6132                cx.notify();
 6133            }
 6134        } else if let EditPredictionPreview::Active {
 6135            previous_scroll_position,
 6136            since,
 6137        } = self.edit_prediction_preview
 6138        {
 6139            if let (Some(previous_scroll_position), Some(position_map)) =
 6140                (previous_scroll_position, self.last_position_map.as_ref())
 6141            {
 6142                self.set_scroll_position(
 6143                    previous_scroll_position
 6144                        .scroll_position(&position_map.snapshot.display_snapshot),
 6145                    window,
 6146                    cx,
 6147                );
 6148            }
 6149
 6150            self.edit_prediction_preview = EditPredictionPreview::Inactive {
 6151                released_too_fast: since.elapsed() < Duration::from_millis(200),
 6152            };
 6153            self.clear_row_highlights::<EditPredictionPreview>();
 6154            self.update_visible_inline_completion(window, cx);
 6155            cx.notify();
 6156        }
 6157    }
 6158
 6159    fn update_visible_inline_completion(
 6160        &mut self,
 6161        _window: &mut Window,
 6162        cx: &mut Context<Self>,
 6163    ) -> Option<()> {
 6164        let selection = self.selections.newest_anchor();
 6165        let cursor = selection.head();
 6166        let multibuffer = self.buffer.read(cx).snapshot(cx);
 6167        let offset_selection = selection.map(|endpoint| endpoint.to_offset(&multibuffer));
 6168        let excerpt_id = cursor.excerpt_id;
 6169
 6170        let show_in_menu = self.show_edit_predictions_in_menu();
 6171        let completions_menu_has_precedence = !show_in_menu
 6172            && (self.context_menu.borrow().is_some()
 6173                || (!self.completion_tasks.is_empty() && !self.has_active_inline_completion()));
 6174
 6175        if completions_menu_has_precedence
 6176            || !offset_selection.is_empty()
 6177            || self
 6178                .active_inline_completion
 6179                .as_ref()
 6180                .map_or(false, |completion| {
 6181                    let invalidation_range = completion.invalidation_range.to_offset(&multibuffer);
 6182                    let invalidation_range = invalidation_range.start..=invalidation_range.end;
 6183                    !invalidation_range.contains(&offset_selection.head())
 6184                })
 6185        {
 6186            self.discard_inline_completion(false, cx);
 6187            return None;
 6188        }
 6189
 6190        self.take_active_inline_completion(cx);
 6191        let Some(provider) = self.edit_prediction_provider() else {
 6192            self.edit_prediction_settings = EditPredictionSettings::Disabled;
 6193            return None;
 6194        };
 6195
 6196        let (buffer, cursor_buffer_position) =
 6197            self.buffer.read(cx).text_anchor_for_position(cursor, cx)?;
 6198
 6199        self.edit_prediction_settings =
 6200            self.edit_prediction_settings_at_position(&buffer, cursor_buffer_position, cx);
 6201
 6202        self.edit_prediction_indent_conflict = multibuffer.is_line_whitespace_upto(cursor);
 6203
 6204        if self.edit_prediction_indent_conflict {
 6205            let cursor_point = cursor.to_point(&multibuffer);
 6206
 6207            let indents = multibuffer.suggested_indents(cursor_point.row..cursor_point.row + 1, cx);
 6208
 6209            if let Some((_, indent)) = indents.iter().next() {
 6210                if indent.len == cursor_point.column {
 6211                    self.edit_prediction_indent_conflict = false;
 6212                }
 6213            }
 6214        }
 6215
 6216        let inline_completion = provider.suggest(&buffer, cursor_buffer_position, cx)?;
 6217        let edits = inline_completion
 6218            .edits
 6219            .into_iter()
 6220            .flat_map(|(range, new_text)| {
 6221                let start = multibuffer.anchor_in_excerpt(excerpt_id, range.start)?;
 6222                let end = multibuffer.anchor_in_excerpt(excerpt_id, range.end)?;
 6223                Some((start..end, new_text))
 6224            })
 6225            .collect::<Vec<_>>();
 6226        if edits.is_empty() {
 6227            return None;
 6228        }
 6229
 6230        let first_edit_start = edits.first().unwrap().0.start;
 6231        let first_edit_start_point = first_edit_start.to_point(&multibuffer);
 6232        let edit_start_row = first_edit_start_point.row.saturating_sub(2);
 6233
 6234        let last_edit_end = edits.last().unwrap().0.end;
 6235        let last_edit_end_point = last_edit_end.to_point(&multibuffer);
 6236        let edit_end_row = cmp::min(multibuffer.max_point().row, last_edit_end_point.row + 2);
 6237
 6238        let cursor_row = cursor.to_point(&multibuffer).row;
 6239
 6240        let snapshot = multibuffer.buffer_for_excerpt(excerpt_id).cloned()?;
 6241
 6242        let mut inlay_ids = Vec::new();
 6243        let invalidation_row_range;
 6244        let move_invalidation_row_range = if cursor_row < edit_start_row {
 6245            Some(cursor_row..edit_end_row)
 6246        } else if cursor_row > edit_end_row {
 6247            Some(edit_start_row..cursor_row)
 6248        } else {
 6249            None
 6250        };
 6251        let is_move =
 6252            move_invalidation_row_range.is_some() || self.inline_completions_hidden_for_vim_mode;
 6253        let completion = if is_move {
 6254            invalidation_row_range =
 6255                move_invalidation_row_range.unwrap_or(edit_start_row..edit_end_row);
 6256            let target = first_edit_start;
 6257            InlineCompletion::Move { target, snapshot }
 6258        } else {
 6259            let show_completions_in_buffer = !self.edit_prediction_visible_in_cursor_popover(true)
 6260                && !self.inline_completions_hidden_for_vim_mode;
 6261
 6262            if show_completions_in_buffer {
 6263                if edits
 6264                    .iter()
 6265                    .all(|(range, _)| range.to_offset(&multibuffer).is_empty())
 6266                {
 6267                    let mut inlays = Vec::new();
 6268                    for (range, new_text) in &edits {
 6269                        let inlay = Inlay::inline_completion(
 6270                            post_inc(&mut self.next_inlay_id),
 6271                            range.start,
 6272                            new_text.as_str(),
 6273                        );
 6274                        inlay_ids.push(inlay.id);
 6275                        inlays.push(inlay);
 6276                    }
 6277
 6278                    self.splice_inlays(&[], inlays, cx);
 6279                } else {
 6280                    let background_color = cx.theme().status().deleted_background;
 6281                    self.highlight_text::<InlineCompletionHighlight>(
 6282                        edits.iter().map(|(range, _)| range.clone()).collect(),
 6283                        HighlightStyle {
 6284                            background_color: Some(background_color),
 6285                            ..Default::default()
 6286                        },
 6287                        cx,
 6288                    );
 6289                }
 6290            }
 6291
 6292            invalidation_row_range = edit_start_row..edit_end_row;
 6293
 6294            let display_mode = if all_edits_insertions_or_deletions(&edits, &multibuffer) {
 6295                if provider.show_tab_accept_marker() {
 6296                    EditDisplayMode::TabAccept
 6297                } else {
 6298                    EditDisplayMode::Inline
 6299                }
 6300            } else {
 6301                EditDisplayMode::DiffPopover
 6302            };
 6303
 6304            InlineCompletion::Edit {
 6305                edits,
 6306                edit_preview: inline_completion.edit_preview,
 6307                display_mode,
 6308                snapshot,
 6309            }
 6310        };
 6311
 6312        let invalidation_range = multibuffer
 6313            .anchor_before(Point::new(invalidation_row_range.start, 0))
 6314            ..multibuffer.anchor_after(Point::new(
 6315                invalidation_row_range.end,
 6316                multibuffer.line_len(MultiBufferRow(invalidation_row_range.end)),
 6317            ));
 6318
 6319        self.stale_inline_completion_in_menu = None;
 6320        self.active_inline_completion = Some(InlineCompletionState {
 6321            inlay_ids,
 6322            completion,
 6323            completion_id: inline_completion.id,
 6324            invalidation_range,
 6325        });
 6326
 6327        cx.notify();
 6328
 6329        Some(())
 6330    }
 6331
 6332    pub fn edit_prediction_provider(&self) -> Option<Arc<dyn InlineCompletionProviderHandle>> {
 6333        Some(self.edit_prediction_provider.as_ref()?.provider.clone())
 6334    }
 6335
 6336    fn render_code_actions_indicator(
 6337        &self,
 6338        _style: &EditorStyle,
 6339        row: DisplayRow,
 6340        is_active: bool,
 6341        breakpoint: Option<&(Anchor, Breakpoint)>,
 6342        cx: &mut Context<Self>,
 6343    ) -> Option<IconButton> {
 6344        let color = Color::Muted;
 6345        let position = breakpoint.as_ref().map(|(anchor, _)| *anchor);
 6346        let show_tooltip = !self.context_menu_visible();
 6347
 6348        if self.available_code_actions.is_some() {
 6349            Some(
 6350                IconButton::new("code_actions_indicator", ui::IconName::Bolt)
 6351                    .shape(ui::IconButtonShape::Square)
 6352                    .icon_size(IconSize::XSmall)
 6353                    .icon_color(color)
 6354                    .toggle_state(is_active)
 6355                    .when(show_tooltip, |this| {
 6356                        this.tooltip({
 6357                            let focus_handle = self.focus_handle.clone();
 6358                            move |window, cx| {
 6359                                Tooltip::for_action_in(
 6360                                    "Toggle Code Actions",
 6361                                    &ToggleCodeActions {
 6362                                        deployed_from_indicator: None,
 6363                                    },
 6364                                    &focus_handle,
 6365                                    window,
 6366                                    cx,
 6367                                )
 6368                            }
 6369                        })
 6370                    })
 6371                    .on_click(cx.listener(move |editor, _e, window, cx| {
 6372                        window.focus(&editor.focus_handle(cx));
 6373                        editor.toggle_code_actions(
 6374                            &ToggleCodeActions {
 6375                                deployed_from_indicator: Some(row),
 6376                            },
 6377                            window,
 6378                            cx,
 6379                        );
 6380                    }))
 6381                    .on_right_click(cx.listener(move |editor, event: &ClickEvent, window, cx| {
 6382                        editor.set_breakpoint_context_menu(
 6383                            row,
 6384                            position,
 6385                            event.down.position,
 6386                            window,
 6387                            cx,
 6388                        );
 6389                    })),
 6390            )
 6391        } else {
 6392            None
 6393        }
 6394    }
 6395
 6396    fn clear_tasks(&mut self) {
 6397        self.tasks.clear()
 6398    }
 6399
 6400    fn insert_tasks(&mut self, key: (BufferId, BufferRow), value: RunnableTasks) {
 6401        if self.tasks.insert(key, value).is_some() {
 6402            // This case should hopefully be rare, but just in case...
 6403            log::error!(
 6404                "multiple different run targets found on a single line, only the last target will be rendered"
 6405            )
 6406        }
 6407    }
 6408
 6409    /// Get all display points of breakpoints that will be rendered within editor
 6410    ///
 6411    /// This function is used to handle overlaps between breakpoints and Code action/runner symbol.
 6412    /// It's also used to set the color of line numbers with breakpoints to the breakpoint color.
 6413    /// TODO debugger: Use this function to color toggle symbols that house nested breakpoints
 6414    fn active_breakpoints(
 6415        &self,
 6416        range: Range<DisplayRow>,
 6417        window: &mut Window,
 6418        cx: &mut Context<Self>,
 6419    ) -> HashMap<DisplayRow, (Anchor, Breakpoint)> {
 6420        let mut breakpoint_display_points = HashMap::default();
 6421
 6422        let Some(breakpoint_store) = self.breakpoint_store.clone() else {
 6423            return breakpoint_display_points;
 6424        };
 6425
 6426        let snapshot = self.snapshot(window, cx);
 6427
 6428        let multi_buffer_snapshot = &snapshot.display_snapshot.buffer_snapshot;
 6429        let Some(project) = self.project.as_ref() else {
 6430            return breakpoint_display_points;
 6431        };
 6432
 6433        let range = snapshot.display_point_to_point(DisplayPoint::new(range.start, 0), Bias::Left)
 6434            ..snapshot.display_point_to_point(DisplayPoint::new(range.end, 0), Bias::Right);
 6435
 6436        for (buffer_snapshot, range, excerpt_id) in
 6437            multi_buffer_snapshot.range_to_buffer_ranges(range)
 6438        {
 6439            let Some(buffer) = project.read_with(cx, |this, cx| {
 6440                this.buffer_for_id(buffer_snapshot.remote_id(), cx)
 6441            }) else {
 6442                continue;
 6443            };
 6444            let breakpoints = breakpoint_store.read(cx).breakpoints(
 6445                &buffer,
 6446                Some(
 6447                    buffer_snapshot.anchor_before(range.start)
 6448                        ..buffer_snapshot.anchor_after(range.end),
 6449                ),
 6450                buffer_snapshot,
 6451                cx,
 6452            );
 6453            for (anchor, breakpoint) in breakpoints {
 6454                let multi_buffer_anchor =
 6455                    Anchor::in_buffer(excerpt_id, buffer_snapshot.remote_id(), *anchor);
 6456                let position = multi_buffer_anchor
 6457                    .to_point(&multi_buffer_snapshot)
 6458                    .to_display_point(&snapshot);
 6459
 6460                breakpoint_display_points
 6461                    .insert(position.row(), (multi_buffer_anchor, breakpoint.clone()));
 6462            }
 6463        }
 6464
 6465        breakpoint_display_points
 6466    }
 6467
 6468    fn breakpoint_context_menu(
 6469        &self,
 6470        anchor: Anchor,
 6471        window: &mut Window,
 6472        cx: &mut Context<Self>,
 6473    ) -> Entity<ui::ContextMenu> {
 6474        let weak_editor = cx.weak_entity();
 6475        let focus_handle = self.focus_handle(cx);
 6476
 6477        let row = self
 6478            .buffer
 6479            .read(cx)
 6480            .snapshot(cx)
 6481            .summary_for_anchor::<Point>(&anchor)
 6482            .row;
 6483
 6484        let breakpoint = self
 6485            .breakpoint_at_row(row, window, cx)
 6486            .map(|(anchor, bp)| (anchor, Arc::from(bp)));
 6487
 6488        let log_breakpoint_msg = if breakpoint.as_ref().is_some_and(|bp| bp.1.message.is_some()) {
 6489            "Edit Log Breakpoint"
 6490        } else {
 6491            "Set Log Breakpoint"
 6492        };
 6493
 6494        let condition_breakpoint_msg = if breakpoint
 6495            .as_ref()
 6496            .is_some_and(|bp| bp.1.condition.is_some())
 6497        {
 6498            "Edit Condition Breakpoint"
 6499        } else {
 6500            "Set Condition Breakpoint"
 6501        };
 6502
 6503        let hit_condition_breakpoint_msg = if breakpoint
 6504            .as_ref()
 6505            .is_some_and(|bp| bp.1.hit_condition.is_some())
 6506        {
 6507            "Edit Hit Condition Breakpoint"
 6508        } else {
 6509            "Set Hit Condition Breakpoint"
 6510        };
 6511
 6512        let set_breakpoint_msg = if breakpoint.as_ref().is_some() {
 6513            "Unset Breakpoint"
 6514        } else {
 6515            "Set Breakpoint"
 6516        };
 6517
 6518        let run_to_cursor = command_palette_hooks::CommandPaletteFilter::try_global(cx)
 6519            .map_or(false, |filter| !filter.is_hidden(&DebuggerRunToCursor));
 6520
 6521        let toggle_state_msg = breakpoint.as_ref().map_or(None, |bp| match bp.1.state {
 6522            BreakpointState::Enabled => Some("Disable"),
 6523            BreakpointState::Disabled => Some("Enable"),
 6524        });
 6525
 6526        let (anchor, breakpoint) =
 6527            breakpoint.unwrap_or_else(|| (anchor, Arc::new(Breakpoint::new_standard())));
 6528
 6529        ui::ContextMenu::build(window, cx, |menu, _, _cx| {
 6530            menu.on_blur_subscription(Subscription::new(|| {}))
 6531                .context(focus_handle)
 6532                .when(run_to_cursor, |this| {
 6533                    let weak_editor = weak_editor.clone();
 6534                    this.entry("Run to cursor", None, move |window, cx| {
 6535                        weak_editor
 6536                            .update(cx, |editor, cx| {
 6537                                editor.change_selections(None, window, cx, |s| {
 6538                                    s.select_ranges([Point::new(row, 0)..Point::new(row, 0)])
 6539                                });
 6540                            })
 6541                            .ok();
 6542
 6543                        window.dispatch_action(Box::new(DebuggerRunToCursor), cx);
 6544                    })
 6545                    .separator()
 6546                })
 6547                .when_some(toggle_state_msg, |this, msg| {
 6548                    this.entry(msg, None, {
 6549                        let weak_editor = weak_editor.clone();
 6550                        let breakpoint = breakpoint.clone();
 6551                        move |_window, cx| {
 6552                            weak_editor
 6553                                .update(cx, |this, cx| {
 6554                                    this.edit_breakpoint_at_anchor(
 6555                                        anchor,
 6556                                        breakpoint.as_ref().clone(),
 6557                                        BreakpointEditAction::InvertState,
 6558                                        cx,
 6559                                    );
 6560                                })
 6561                                .log_err();
 6562                        }
 6563                    })
 6564                })
 6565                .entry(set_breakpoint_msg, None, {
 6566                    let weak_editor = weak_editor.clone();
 6567                    let breakpoint = breakpoint.clone();
 6568                    move |_window, cx| {
 6569                        weak_editor
 6570                            .update(cx, |this, cx| {
 6571                                this.edit_breakpoint_at_anchor(
 6572                                    anchor,
 6573                                    breakpoint.as_ref().clone(),
 6574                                    BreakpointEditAction::Toggle,
 6575                                    cx,
 6576                                );
 6577                            })
 6578                            .log_err();
 6579                    }
 6580                })
 6581                .entry(log_breakpoint_msg, None, {
 6582                    let breakpoint = breakpoint.clone();
 6583                    let weak_editor = weak_editor.clone();
 6584                    move |window, cx| {
 6585                        weak_editor
 6586                            .update(cx, |this, cx| {
 6587                                this.add_edit_breakpoint_block(
 6588                                    anchor,
 6589                                    breakpoint.as_ref(),
 6590                                    BreakpointPromptEditAction::Log,
 6591                                    window,
 6592                                    cx,
 6593                                );
 6594                            })
 6595                            .log_err();
 6596                    }
 6597                })
 6598                .entry(condition_breakpoint_msg, None, {
 6599                    let breakpoint = breakpoint.clone();
 6600                    let weak_editor = weak_editor.clone();
 6601                    move |window, cx| {
 6602                        weak_editor
 6603                            .update(cx, |this, cx| {
 6604                                this.add_edit_breakpoint_block(
 6605                                    anchor,
 6606                                    breakpoint.as_ref(),
 6607                                    BreakpointPromptEditAction::Condition,
 6608                                    window,
 6609                                    cx,
 6610                                );
 6611                            })
 6612                            .log_err();
 6613                    }
 6614                })
 6615                .entry(hit_condition_breakpoint_msg, None, move |window, cx| {
 6616                    weak_editor
 6617                        .update(cx, |this, cx| {
 6618                            this.add_edit_breakpoint_block(
 6619                                anchor,
 6620                                breakpoint.as_ref(),
 6621                                BreakpointPromptEditAction::HitCondition,
 6622                                window,
 6623                                cx,
 6624                            );
 6625                        })
 6626                        .log_err();
 6627                })
 6628        })
 6629    }
 6630
 6631    fn render_breakpoint(
 6632        &self,
 6633        position: Anchor,
 6634        row: DisplayRow,
 6635        breakpoint: &Breakpoint,
 6636        cx: &mut Context<Self>,
 6637    ) -> IconButton {
 6638        let (color, icon) = {
 6639            let icon = match (&breakpoint.message.is_some(), breakpoint.is_disabled()) {
 6640                (false, false) => ui::IconName::DebugBreakpoint,
 6641                (true, false) => ui::IconName::DebugLogBreakpoint,
 6642                (false, true) => ui::IconName::DebugDisabledBreakpoint,
 6643                (true, true) => ui::IconName::DebugDisabledLogBreakpoint,
 6644            };
 6645
 6646            let color = if self
 6647                .gutter_breakpoint_indicator
 6648                .0
 6649                .is_some_and(|(point, is_visible)| is_visible && point.row() == row)
 6650            {
 6651                Color::Hint
 6652            } else {
 6653                Color::Debugger
 6654            };
 6655
 6656            (color, icon)
 6657        };
 6658
 6659        let breakpoint = Arc::from(breakpoint.clone());
 6660
 6661        IconButton::new(("breakpoint_indicator", row.0 as usize), icon)
 6662            .icon_size(IconSize::XSmall)
 6663            .size(ui::ButtonSize::None)
 6664            .icon_color(color)
 6665            .style(ButtonStyle::Transparent)
 6666            .on_click(cx.listener({
 6667                let breakpoint = breakpoint.clone();
 6668
 6669                move |editor, event: &ClickEvent, window, cx| {
 6670                    let edit_action = if event.modifiers().platform || breakpoint.is_disabled() {
 6671                        BreakpointEditAction::InvertState
 6672                    } else {
 6673                        BreakpointEditAction::Toggle
 6674                    };
 6675
 6676                    window.focus(&editor.focus_handle(cx));
 6677                    editor.edit_breakpoint_at_anchor(
 6678                        position,
 6679                        breakpoint.as_ref().clone(),
 6680                        edit_action,
 6681                        cx,
 6682                    );
 6683                }
 6684            }))
 6685            .on_right_click(cx.listener(move |editor, event: &ClickEvent, window, cx| {
 6686                editor.set_breakpoint_context_menu(
 6687                    row,
 6688                    Some(position),
 6689                    event.down.position,
 6690                    window,
 6691                    cx,
 6692                );
 6693            }))
 6694    }
 6695
 6696    fn build_tasks_context(
 6697        project: &Entity<Project>,
 6698        buffer: &Entity<Buffer>,
 6699        buffer_row: u32,
 6700        tasks: &Arc<RunnableTasks>,
 6701        cx: &mut Context<Self>,
 6702    ) -> Task<Option<task::TaskContext>> {
 6703        let position = Point::new(buffer_row, tasks.column);
 6704        let range_start = buffer.read(cx).anchor_at(position, Bias::Right);
 6705        let location = Location {
 6706            buffer: buffer.clone(),
 6707            range: range_start..range_start,
 6708        };
 6709        // Fill in the environmental variables from the tree-sitter captures
 6710        let mut captured_task_variables = TaskVariables::default();
 6711        for (capture_name, value) in tasks.extra_variables.clone() {
 6712            captured_task_variables.insert(
 6713                task::VariableName::Custom(capture_name.into()),
 6714                value.clone(),
 6715            );
 6716        }
 6717        project.update(cx, |project, cx| {
 6718            project.task_store().update(cx, |task_store, cx| {
 6719                task_store.task_context_for_location(captured_task_variables, location, cx)
 6720            })
 6721        })
 6722    }
 6723
 6724    pub fn spawn_nearest_task(
 6725        &mut self,
 6726        action: &SpawnNearestTask,
 6727        window: &mut Window,
 6728        cx: &mut Context<Self>,
 6729    ) {
 6730        let Some((workspace, _)) = self.workspace.clone() else {
 6731            return;
 6732        };
 6733        let Some(project) = self.project.clone() else {
 6734            return;
 6735        };
 6736
 6737        // Try to find a closest, enclosing node using tree-sitter that has a
 6738        // task
 6739        let Some((buffer, buffer_row, tasks)) = self
 6740            .find_enclosing_node_task(cx)
 6741            // Or find the task that's closest in row-distance.
 6742            .or_else(|| self.find_closest_task(cx))
 6743        else {
 6744            return;
 6745        };
 6746
 6747        let reveal_strategy = action.reveal;
 6748        let task_context = Self::build_tasks_context(&project, &buffer, buffer_row, &tasks, cx);
 6749        cx.spawn_in(window, async move |_, cx| {
 6750            let context = task_context.await?;
 6751            let (task_source_kind, mut resolved_task) = tasks.resolve(&context).next()?;
 6752
 6753            let resolved = resolved_task.resolved.as_mut()?;
 6754            resolved.reveal = reveal_strategy;
 6755
 6756            workspace
 6757                .update(cx, |workspace, cx| {
 6758                    workspace::tasks::schedule_resolved_task(
 6759                        workspace,
 6760                        task_source_kind,
 6761                        resolved_task,
 6762                        false,
 6763                        cx,
 6764                    );
 6765                })
 6766                .ok()
 6767        })
 6768        .detach();
 6769    }
 6770
 6771    fn find_closest_task(
 6772        &mut self,
 6773        cx: &mut Context<Self>,
 6774    ) -> Option<(Entity<Buffer>, u32, Arc<RunnableTasks>)> {
 6775        let cursor_row = self.selections.newest_adjusted(cx).head().row;
 6776
 6777        let ((buffer_id, row), tasks) = self
 6778            .tasks
 6779            .iter()
 6780            .min_by_key(|((_, row), _)| cursor_row.abs_diff(*row))?;
 6781
 6782        let buffer = self.buffer.read(cx).buffer(*buffer_id)?;
 6783        let tasks = Arc::new(tasks.to_owned());
 6784        Some((buffer, *row, tasks))
 6785    }
 6786
 6787    fn find_enclosing_node_task(
 6788        &mut self,
 6789        cx: &mut Context<Self>,
 6790    ) -> Option<(Entity<Buffer>, u32, Arc<RunnableTasks>)> {
 6791        let snapshot = self.buffer.read(cx).snapshot(cx);
 6792        let offset = self.selections.newest::<usize>(cx).head();
 6793        let excerpt = snapshot.excerpt_containing(offset..offset)?;
 6794        let buffer_id = excerpt.buffer().remote_id();
 6795
 6796        let layer = excerpt.buffer().syntax_layer_at(offset)?;
 6797        let mut cursor = layer.node().walk();
 6798
 6799        while cursor.goto_first_child_for_byte(offset).is_some() {
 6800            if cursor.node().end_byte() == offset {
 6801                cursor.goto_next_sibling();
 6802            }
 6803        }
 6804
 6805        // Ascend to the smallest ancestor that contains the range and has a task.
 6806        loop {
 6807            let node = cursor.node();
 6808            let node_range = node.byte_range();
 6809            let symbol_start_row = excerpt.buffer().offset_to_point(node.start_byte()).row;
 6810
 6811            // Check if this node contains our offset
 6812            if node_range.start <= offset && node_range.end >= offset {
 6813                // If it contains offset, check for task
 6814                if let Some(tasks) = self.tasks.get(&(buffer_id, symbol_start_row)) {
 6815                    let buffer = self.buffer.read(cx).buffer(buffer_id)?;
 6816                    return Some((buffer, symbol_start_row, Arc::new(tasks.to_owned())));
 6817                }
 6818            }
 6819
 6820            if !cursor.goto_parent() {
 6821                break;
 6822            }
 6823        }
 6824        None
 6825    }
 6826
 6827    fn render_run_indicator(
 6828        &self,
 6829        _style: &EditorStyle,
 6830        is_active: bool,
 6831        row: DisplayRow,
 6832        breakpoint: Option<(Anchor, Breakpoint)>,
 6833        cx: &mut Context<Self>,
 6834    ) -> IconButton {
 6835        let color = Color::Muted;
 6836        let position = breakpoint.as_ref().map(|(anchor, _)| *anchor);
 6837
 6838        IconButton::new(("run_indicator", row.0 as usize), ui::IconName::Play)
 6839            .shape(ui::IconButtonShape::Square)
 6840            .icon_size(IconSize::XSmall)
 6841            .icon_color(color)
 6842            .toggle_state(is_active)
 6843            .on_click(cx.listener(move |editor, _e, window, cx| {
 6844                window.focus(&editor.focus_handle(cx));
 6845                editor.toggle_code_actions(
 6846                    &ToggleCodeActions {
 6847                        deployed_from_indicator: Some(row),
 6848                    },
 6849                    window,
 6850                    cx,
 6851                );
 6852            }))
 6853            .on_right_click(cx.listener(move |editor, event: &ClickEvent, window, cx| {
 6854                editor.set_breakpoint_context_menu(row, position, event.down.position, window, cx);
 6855            }))
 6856    }
 6857
 6858    pub fn context_menu_visible(&self) -> bool {
 6859        !self.edit_prediction_preview_is_active()
 6860            && self
 6861                .context_menu
 6862                .borrow()
 6863                .as_ref()
 6864                .map_or(false, |menu| menu.visible())
 6865    }
 6866
 6867    fn context_menu_origin(&self) -> Option<ContextMenuOrigin> {
 6868        self.context_menu
 6869            .borrow()
 6870            .as_ref()
 6871            .map(|menu| menu.origin())
 6872    }
 6873
 6874    pub fn set_context_menu_options(&mut self, options: ContextMenuOptions) {
 6875        self.context_menu_options = Some(options);
 6876    }
 6877
 6878    const EDIT_PREDICTION_POPOVER_PADDING_X: Pixels = Pixels(24.);
 6879    const EDIT_PREDICTION_POPOVER_PADDING_Y: Pixels = Pixels(2.);
 6880
 6881    fn render_edit_prediction_popover(
 6882        &mut self,
 6883        text_bounds: &Bounds<Pixels>,
 6884        content_origin: gpui::Point<Pixels>,
 6885        editor_snapshot: &EditorSnapshot,
 6886        visible_row_range: Range<DisplayRow>,
 6887        scroll_top: f32,
 6888        scroll_bottom: f32,
 6889        line_layouts: &[LineWithInvisibles],
 6890        line_height: Pixels,
 6891        scroll_pixel_position: gpui::Point<Pixels>,
 6892        newest_selection_head: Option<DisplayPoint>,
 6893        editor_width: Pixels,
 6894        style: &EditorStyle,
 6895        window: &mut Window,
 6896        cx: &mut App,
 6897    ) -> Option<(AnyElement, gpui::Point<Pixels>)> {
 6898        let active_inline_completion = self.active_inline_completion.as_ref()?;
 6899
 6900        if self.edit_prediction_visible_in_cursor_popover(true) {
 6901            return None;
 6902        }
 6903
 6904        match &active_inline_completion.completion {
 6905            InlineCompletion::Move { target, .. } => {
 6906                let target_display_point = target.to_display_point(editor_snapshot);
 6907
 6908                if self.edit_prediction_requires_modifier() {
 6909                    if !self.edit_prediction_preview_is_active() {
 6910                        return None;
 6911                    }
 6912
 6913                    self.render_edit_prediction_modifier_jump_popover(
 6914                        text_bounds,
 6915                        content_origin,
 6916                        visible_row_range,
 6917                        line_layouts,
 6918                        line_height,
 6919                        scroll_pixel_position,
 6920                        newest_selection_head,
 6921                        target_display_point,
 6922                        window,
 6923                        cx,
 6924                    )
 6925                } else {
 6926                    self.render_edit_prediction_eager_jump_popover(
 6927                        text_bounds,
 6928                        content_origin,
 6929                        editor_snapshot,
 6930                        visible_row_range,
 6931                        scroll_top,
 6932                        scroll_bottom,
 6933                        line_height,
 6934                        scroll_pixel_position,
 6935                        target_display_point,
 6936                        editor_width,
 6937                        window,
 6938                        cx,
 6939                    )
 6940                }
 6941            }
 6942            InlineCompletion::Edit {
 6943                display_mode: EditDisplayMode::Inline,
 6944                ..
 6945            } => None,
 6946            InlineCompletion::Edit {
 6947                display_mode: EditDisplayMode::TabAccept,
 6948                edits,
 6949                ..
 6950            } => {
 6951                let range = &edits.first()?.0;
 6952                let target_display_point = range.end.to_display_point(editor_snapshot);
 6953
 6954                self.render_edit_prediction_end_of_line_popover(
 6955                    "Accept",
 6956                    editor_snapshot,
 6957                    visible_row_range,
 6958                    target_display_point,
 6959                    line_height,
 6960                    scroll_pixel_position,
 6961                    content_origin,
 6962                    editor_width,
 6963                    window,
 6964                    cx,
 6965                )
 6966            }
 6967            InlineCompletion::Edit {
 6968                edits,
 6969                edit_preview,
 6970                display_mode: EditDisplayMode::DiffPopover,
 6971                snapshot,
 6972            } => self.render_edit_prediction_diff_popover(
 6973                text_bounds,
 6974                content_origin,
 6975                editor_snapshot,
 6976                visible_row_range,
 6977                line_layouts,
 6978                line_height,
 6979                scroll_pixel_position,
 6980                newest_selection_head,
 6981                editor_width,
 6982                style,
 6983                edits,
 6984                edit_preview,
 6985                snapshot,
 6986                window,
 6987                cx,
 6988            ),
 6989        }
 6990    }
 6991
 6992    fn render_edit_prediction_modifier_jump_popover(
 6993        &mut self,
 6994        text_bounds: &Bounds<Pixels>,
 6995        content_origin: gpui::Point<Pixels>,
 6996        visible_row_range: Range<DisplayRow>,
 6997        line_layouts: &[LineWithInvisibles],
 6998        line_height: Pixels,
 6999        scroll_pixel_position: gpui::Point<Pixels>,
 7000        newest_selection_head: Option<DisplayPoint>,
 7001        target_display_point: DisplayPoint,
 7002        window: &mut Window,
 7003        cx: &mut App,
 7004    ) -> Option<(AnyElement, gpui::Point<Pixels>)> {
 7005        let scrolled_content_origin =
 7006            content_origin - gpui::Point::new(scroll_pixel_position.x, Pixels(0.0));
 7007
 7008        const SCROLL_PADDING_Y: Pixels = px(12.);
 7009
 7010        if target_display_point.row() < visible_row_range.start {
 7011            return self.render_edit_prediction_scroll_popover(
 7012                |_| SCROLL_PADDING_Y,
 7013                IconName::ArrowUp,
 7014                visible_row_range,
 7015                line_layouts,
 7016                newest_selection_head,
 7017                scrolled_content_origin,
 7018                window,
 7019                cx,
 7020            );
 7021        } else if target_display_point.row() >= visible_row_range.end {
 7022            return self.render_edit_prediction_scroll_popover(
 7023                |size| text_bounds.size.height - size.height - SCROLL_PADDING_Y,
 7024                IconName::ArrowDown,
 7025                visible_row_range,
 7026                line_layouts,
 7027                newest_selection_head,
 7028                scrolled_content_origin,
 7029                window,
 7030                cx,
 7031            );
 7032        }
 7033
 7034        const POLE_WIDTH: Pixels = px(2.);
 7035
 7036        let line_layout =
 7037            line_layouts.get(target_display_point.row().minus(visible_row_range.start) as usize)?;
 7038        let target_column = target_display_point.column() as usize;
 7039
 7040        let target_x = line_layout.x_for_index(target_column);
 7041        let target_y =
 7042            (target_display_point.row().as_f32() * line_height) - scroll_pixel_position.y;
 7043
 7044        let flag_on_right = target_x < text_bounds.size.width / 2.;
 7045
 7046        let mut border_color = Self::edit_prediction_callout_popover_border_color(cx);
 7047        border_color.l += 0.001;
 7048
 7049        let mut element = v_flex()
 7050            .items_end()
 7051            .when(flag_on_right, |el| el.items_start())
 7052            .child(if flag_on_right {
 7053                self.render_edit_prediction_line_popover("Jump", None, window, cx)?
 7054                    .rounded_bl(px(0.))
 7055                    .rounded_tl(px(0.))
 7056                    .border_l_2()
 7057                    .border_color(border_color)
 7058            } else {
 7059                self.render_edit_prediction_line_popover("Jump", None, window, cx)?
 7060                    .rounded_br(px(0.))
 7061                    .rounded_tr(px(0.))
 7062                    .border_r_2()
 7063                    .border_color(border_color)
 7064            })
 7065            .child(div().w(POLE_WIDTH).bg(border_color).h(line_height))
 7066            .into_any();
 7067
 7068        let size = element.layout_as_root(AvailableSpace::min_size(), window, cx);
 7069
 7070        let mut origin = scrolled_content_origin + point(target_x, target_y)
 7071            - point(
 7072                if flag_on_right {
 7073                    POLE_WIDTH
 7074                } else {
 7075                    size.width - POLE_WIDTH
 7076                },
 7077                size.height - line_height,
 7078            );
 7079
 7080        origin.x = origin.x.max(content_origin.x);
 7081
 7082        element.prepaint_at(origin, window, cx);
 7083
 7084        Some((element, origin))
 7085    }
 7086
 7087    fn render_edit_prediction_scroll_popover(
 7088        &mut self,
 7089        to_y: impl Fn(Size<Pixels>) -> Pixels,
 7090        scroll_icon: IconName,
 7091        visible_row_range: Range<DisplayRow>,
 7092        line_layouts: &[LineWithInvisibles],
 7093        newest_selection_head: Option<DisplayPoint>,
 7094        scrolled_content_origin: gpui::Point<Pixels>,
 7095        window: &mut Window,
 7096        cx: &mut App,
 7097    ) -> Option<(AnyElement, gpui::Point<Pixels>)> {
 7098        let mut element = self
 7099            .render_edit_prediction_line_popover("Scroll", Some(scroll_icon), window, cx)?
 7100            .into_any();
 7101
 7102        let size = element.layout_as_root(AvailableSpace::min_size(), window, cx);
 7103
 7104        let cursor = newest_selection_head?;
 7105        let cursor_row_layout =
 7106            line_layouts.get(cursor.row().minus(visible_row_range.start) as usize)?;
 7107        let cursor_column = cursor.column() as usize;
 7108
 7109        let cursor_character_x = cursor_row_layout.x_for_index(cursor_column);
 7110
 7111        let origin = scrolled_content_origin + point(cursor_character_x, to_y(size));
 7112
 7113        element.prepaint_at(origin, window, cx);
 7114        Some((element, origin))
 7115    }
 7116
 7117    fn render_edit_prediction_eager_jump_popover(
 7118        &mut self,
 7119        text_bounds: &Bounds<Pixels>,
 7120        content_origin: gpui::Point<Pixels>,
 7121        editor_snapshot: &EditorSnapshot,
 7122        visible_row_range: Range<DisplayRow>,
 7123        scroll_top: f32,
 7124        scroll_bottom: f32,
 7125        line_height: Pixels,
 7126        scroll_pixel_position: gpui::Point<Pixels>,
 7127        target_display_point: DisplayPoint,
 7128        editor_width: Pixels,
 7129        window: &mut Window,
 7130        cx: &mut App,
 7131    ) -> Option<(AnyElement, gpui::Point<Pixels>)> {
 7132        if target_display_point.row().as_f32() < scroll_top {
 7133            let mut element = self
 7134                .render_edit_prediction_line_popover(
 7135                    "Jump to Edit",
 7136                    Some(IconName::ArrowUp),
 7137                    window,
 7138                    cx,
 7139                )?
 7140                .into_any();
 7141
 7142            let size = element.layout_as_root(AvailableSpace::min_size(), window, cx);
 7143            let offset = point(
 7144                (text_bounds.size.width - size.width) / 2.,
 7145                Self::EDIT_PREDICTION_POPOVER_PADDING_Y,
 7146            );
 7147
 7148            let origin = text_bounds.origin + offset;
 7149            element.prepaint_at(origin, window, cx);
 7150            Some((element, origin))
 7151        } else if (target_display_point.row().as_f32() + 1.) > scroll_bottom {
 7152            let mut element = self
 7153                .render_edit_prediction_line_popover(
 7154                    "Jump to Edit",
 7155                    Some(IconName::ArrowDown),
 7156                    window,
 7157                    cx,
 7158                )?
 7159                .into_any();
 7160
 7161            let size = element.layout_as_root(AvailableSpace::min_size(), window, cx);
 7162            let offset = point(
 7163                (text_bounds.size.width - size.width) / 2.,
 7164                text_bounds.size.height - size.height - Self::EDIT_PREDICTION_POPOVER_PADDING_Y,
 7165            );
 7166
 7167            let origin = text_bounds.origin + offset;
 7168            element.prepaint_at(origin, window, cx);
 7169            Some((element, origin))
 7170        } else {
 7171            self.render_edit_prediction_end_of_line_popover(
 7172                "Jump to Edit",
 7173                editor_snapshot,
 7174                visible_row_range,
 7175                target_display_point,
 7176                line_height,
 7177                scroll_pixel_position,
 7178                content_origin,
 7179                editor_width,
 7180                window,
 7181                cx,
 7182            )
 7183        }
 7184    }
 7185
 7186    fn render_edit_prediction_end_of_line_popover(
 7187        self: &mut Editor,
 7188        label: &'static str,
 7189        editor_snapshot: &EditorSnapshot,
 7190        visible_row_range: Range<DisplayRow>,
 7191        target_display_point: DisplayPoint,
 7192        line_height: Pixels,
 7193        scroll_pixel_position: gpui::Point<Pixels>,
 7194        content_origin: gpui::Point<Pixels>,
 7195        editor_width: Pixels,
 7196        window: &mut Window,
 7197        cx: &mut App,
 7198    ) -> Option<(AnyElement, gpui::Point<Pixels>)> {
 7199        let target_line_end = DisplayPoint::new(
 7200            target_display_point.row(),
 7201            editor_snapshot.line_len(target_display_point.row()),
 7202        );
 7203
 7204        let mut element = self
 7205            .render_edit_prediction_line_popover(label, None, window, cx)?
 7206            .into_any();
 7207
 7208        let size = element.layout_as_root(AvailableSpace::min_size(), window, cx);
 7209
 7210        let line_origin = self.display_to_pixel_point(target_line_end, editor_snapshot, window)?;
 7211
 7212        let start_point = content_origin - point(scroll_pixel_position.x, Pixels::ZERO);
 7213        let mut origin = start_point
 7214            + line_origin
 7215            + point(Self::EDIT_PREDICTION_POPOVER_PADDING_X, Pixels::ZERO);
 7216        origin.x = origin.x.max(content_origin.x);
 7217
 7218        let max_x = content_origin.x + editor_width - size.width;
 7219
 7220        if origin.x > max_x {
 7221            let offset = line_height + Self::EDIT_PREDICTION_POPOVER_PADDING_Y;
 7222
 7223            let icon = if visible_row_range.contains(&(target_display_point.row() + 2)) {
 7224                origin.y += offset;
 7225                IconName::ArrowUp
 7226            } else {
 7227                origin.y -= offset;
 7228                IconName::ArrowDown
 7229            };
 7230
 7231            element = self
 7232                .render_edit_prediction_line_popover(label, Some(icon), window, cx)?
 7233                .into_any();
 7234
 7235            let size = element.layout_as_root(AvailableSpace::min_size(), window, cx);
 7236
 7237            origin.x = content_origin.x + editor_width - size.width - px(2.);
 7238        }
 7239
 7240        element.prepaint_at(origin, window, cx);
 7241        Some((element, origin))
 7242    }
 7243
 7244    fn render_edit_prediction_diff_popover(
 7245        self: &Editor,
 7246        text_bounds: &Bounds<Pixels>,
 7247        content_origin: gpui::Point<Pixels>,
 7248        editor_snapshot: &EditorSnapshot,
 7249        visible_row_range: Range<DisplayRow>,
 7250        line_layouts: &[LineWithInvisibles],
 7251        line_height: Pixels,
 7252        scroll_pixel_position: gpui::Point<Pixels>,
 7253        newest_selection_head: Option<DisplayPoint>,
 7254        editor_width: Pixels,
 7255        style: &EditorStyle,
 7256        edits: &Vec<(Range<Anchor>, String)>,
 7257        edit_preview: &Option<language::EditPreview>,
 7258        snapshot: &language::BufferSnapshot,
 7259        window: &mut Window,
 7260        cx: &mut App,
 7261    ) -> Option<(AnyElement, gpui::Point<Pixels>)> {
 7262        let edit_start = edits
 7263            .first()
 7264            .unwrap()
 7265            .0
 7266            .start
 7267            .to_display_point(editor_snapshot);
 7268        let edit_end = edits
 7269            .last()
 7270            .unwrap()
 7271            .0
 7272            .end
 7273            .to_display_point(editor_snapshot);
 7274
 7275        let is_visible = visible_row_range.contains(&edit_start.row())
 7276            || visible_row_range.contains(&edit_end.row());
 7277        if !is_visible {
 7278            return None;
 7279        }
 7280
 7281        let highlighted_edits =
 7282            crate::inline_completion_edit_text(&snapshot, edits, edit_preview.as_ref()?, false, cx);
 7283
 7284        let styled_text = highlighted_edits.to_styled_text(&style.text);
 7285        let line_count = highlighted_edits.text.lines().count();
 7286
 7287        const BORDER_WIDTH: Pixels = px(1.);
 7288
 7289        let keybind = self.render_edit_prediction_accept_keybind(window, cx);
 7290        let has_keybind = keybind.is_some();
 7291
 7292        let mut element = h_flex()
 7293            .items_start()
 7294            .child(
 7295                h_flex()
 7296                    .bg(cx.theme().colors().editor_background)
 7297                    .border(BORDER_WIDTH)
 7298                    .shadow_sm()
 7299                    .border_color(cx.theme().colors().border)
 7300                    .rounded_l_lg()
 7301                    .when(line_count > 1, |el| el.rounded_br_lg())
 7302                    .pr_1()
 7303                    .child(styled_text),
 7304            )
 7305            .child(
 7306                h_flex()
 7307                    .h(line_height + BORDER_WIDTH * 2.)
 7308                    .px_1p5()
 7309                    .gap_1()
 7310                    // Workaround: For some reason, there's a gap if we don't do this
 7311                    .ml(-BORDER_WIDTH)
 7312                    .shadow(smallvec![gpui::BoxShadow {
 7313                        color: gpui::black().opacity(0.05),
 7314                        offset: point(px(1.), px(1.)),
 7315                        blur_radius: px(2.),
 7316                        spread_radius: px(0.),
 7317                    }])
 7318                    .bg(Editor::edit_prediction_line_popover_bg_color(cx))
 7319                    .border(BORDER_WIDTH)
 7320                    .border_color(cx.theme().colors().border)
 7321                    .rounded_r_lg()
 7322                    .id("edit_prediction_diff_popover_keybind")
 7323                    .when(!has_keybind, |el| {
 7324                        let status_colors = cx.theme().status();
 7325
 7326                        el.bg(status_colors.error_background)
 7327                            .border_color(status_colors.error.opacity(0.6))
 7328                            .child(Icon::new(IconName::Info).color(Color::Error))
 7329                            .cursor_default()
 7330                            .hoverable_tooltip(move |_window, cx| {
 7331                                cx.new(|_| MissingEditPredictionKeybindingTooltip).into()
 7332                            })
 7333                    })
 7334                    .children(keybind),
 7335            )
 7336            .into_any();
 7337
 7338        let longest_row =
 7339            editor_snapshot.longest_row_in_range(edit_start.row()..edit_end.row() + 1);
 7340        let longest_line_width = if visible_row_range.contains(&longest_row) {
 7341            line_layouts[(longest_row.0 - visible_row_range.start.0) as usize].width
 7342        } else {
 7343            layout_line(
 7344                longest_row,
 7345                editor_snapshot,
 7346                style,
 7347                editor_width,
 7348                |_| false,
 7349                window,
 7350                cx,
 7351            )
 7352            .width
 7353        };
 7354
 7355        let viewport_bounds =
 7356            Bounds::new(Default::default(), window.viewport_size()).extend(Edges {
 7357                right: -EditorElement::SCROLLBAR_WIDTH,
 7358                ..Default::default()
 7359            });
 7360
 7361        let x_after_longest =
 7362            text_bounds.origin.x + longest_line_width + Self::EDIT_PREDICTION_POPOVER_PADDING_X
 7363                - scroll_pixel_position.x;
 7364
 7365        let element_bounds = element.layout_as_root(AvailableSpace::min_size(), window, cx);
 7366
 7367        // Fully visible if it can be displayed within the window (allow overlapping other
 7368        // panes). However, this is only allowed if the popover starts within text_bounds.
 7369        let can_position_to_the_right = x_after_longest < text_bounds.right()
 7370            && x_after_longest + element_bounds.width < viewport_bounds.right();
 7371
 7372        let mut origin = if can_position_to_the_right {
 7373            point(
 7374                x_after_longest,
 7375                text_bounds.origin.y + edit_start.row().as_f32() * line_height
 7376                    - scroll_pixel_position.y,
 7377            )
 7378        } else {
 7379            let cursor_row = newest_selection_head.map(|head| head.row());
 7380            let above_edit = edit_start
 7381                .row()
 7382                .0
 7383                .checked_sub(line_count as u32)
 7384                .map(DisplayRow);
 7385            let below_edit = Some(edit_end.row() + 1);
 7386            let above_cursor =
 7387                cursor_row.and_then(|row| row.0.checked_sub(line_count as u32).map(DisplayRow));
 7388            let below_cursor = cursor_row.map(|cursor_row| cursor_row + 1);
 7389
 7390            // Place the edit popover adjacent to the edit if there is a location
 7391            // available that is onscreen and does not obscure the cursor. Otherwise,
 7392            // place it adjacent to the cursor.
 7393            let row_target = [above_edit, below_edit, above_cursor, below_cursor]
 7394                .into_iter()
 7395                .flatten()
 7396                .find(|&start_row| {
 7397                    let end_row = start_row + line_count as u32;
 7398                    visible_row_range.contains(&start_row)
 7399                        && visible_row_range.contains(&end_row)
 7400                        && cursor_row.map_or(true, |cursor_row| {
 7401                            !((start_row..end_row).contains(&cursor_row))
 7402                        })
 7403                })?;
 7404
 7405            content_origin
 7406                + point(
 7407                    -scroll_pixel_position.x,
 7408                    row_target.as_f32() * line_height - scroll_pixel_position.y,
 7409                )
 7410        };
 7411
 7412        origin.x -= BORDER_WIDTH;
 7413
 7414        window.defer_draw(element, origin, 1);
 7415
 7416        // Do not return an element, since it will already be drawn due to defer_draw.
 7417        None
 7418    }
 7419
 7420    fn edit_prediction_cursor_popover_height(&self) -> Pixels {
 7421        px(30.)
 7422    }
 7423
 7424    fn current_user_player_color(&self, cx: &mut App) -> PlayerColor {
 7425        if self.read_only(cx) {
 7426            cx.theme().players().read_only()
 7427        } else {
 7428            self.style.as_ref().unwrap().local_player
 7429        }
 7430    }
 7431
 7432    fn render_edit_prediction_accept_keybind(
 7433        &self,
 7434        window: &mut Window,
 7435        cx: &App,
 7436    ) -> Option<AnyElement> {
 7437        let accept_binding = self.accept_edit_prediction_keybind(window, cx);
 7438        let accept_keystroke = accept_binding.keystroke()?;
 7439
 7440        let is_platform_style_mac = PlatformStyle::platform() == PlatformStyle::Mac;
 7441
 7442        let modifiers_color = if accept_keystroke.modifiers == window.modifiers() {
 7443            Color::Accent
 7444        } else {
 7445            Color::Muted
 7446        };
 7447
 7448        h_flex()
 7449            .px_0p5()
 7450            .when(is_platform_style_mac, |parent| parent.gap_0p5())
 7451            .font(theme::ThemeSettings::get_global(cx).buffer_font.clone())
 7452            .text_size(TextSize::XSmall.rems(cx))
 7453            .child(h_flex().children(ui::render_modifiers(
 7454                &accept_keystroke.modifiers,
 7455                PlatformStyle::platform(),
 7456                Some(modifiers_color),
 7457                Some(IconSize::XSmall.rems().into()),
 7458                true,
 7459            )))
 7460            .when(is_platform_style_mac, |parent| {
 7461                parent.child(accept_keystroke.key.clone())
 7462            })
 7463            .when(!is_platform_style_mac, |parent| {
 7464                parent.child(
 7465                    Key::new(
 7466                        util::capitalize(&accept_keystroke.key),
 7467                        Some(Color::Default),
 7468                    )
 7469                    .size(Some(IconSize::XSmall.rems().into())),
 7470                )
 7471            })
 7472            .into_any()
 7473            .into()
 7474    }
 7475
 7476    fn render_edit_prediction_line_popover(
 7477        &self,
 7478        label: impl Into<SharedString>,
 7479        icon: Option<IconName>,
 7480        window: &mut Window,
 7481        cx: &App,
 7482    ) -> Option<Stateful<Div>> {
 7483        let padding_right = if icon.is_some() { px(4.) } else { px(8.) };
 7484
 7485        let keybind = self.render_edit_prediction_accept_keybind(window, cx);
 7486        let has_keybind = keybind.is_some();
 7487
 7488        let result = h_flex()
 7489            .id("ep-line-popover")
 7490            .py_0p5()
 7491            .pl_1()
 7492            .pr(padding_right)
 7493            .gap_1()
 7494            .rounded_md()
 7495            .border_1()
 7496            .bg(Self::edit_prediction_line_popover_bg_color(cx))
 7497            .border_color(Self::edit_prediction_callout_popover_border_color(cx))
 7498            .shadow_sm()
 7499            .when(!has_keybind, |el| {
 7500                let status_colors = cx.theme().status();
 7501
 7502                el.bg(status_colors.error_background)
 7503                    .border_color(status_colors.error.opacity(0.6))
 7504                    .pl_2()
 7505                    .child(Icon::new(IconName::ZedPredictError).color(Color::Error))
 7506                    .cursor_default()
 7507                    .hoverable_tooltip(move |_window, cx| {
 7508                        cx.new(|_| MissingEditPredictionKeybindingTooltip).into()
 7509                    })
 7510            })
 7511            .children(keybind)
 7512            .child(
 7513                Label::new(label)
 7514                    .size(LabelSize::Small)
 7515                    .when(!has_keybind, |el| {
 7516                        el.color(cx.theme().status().error.into()).strikethrough()
 7517                    }),
 7518            )
 7519            .when(!has_keybind, |el| {
 7520                el.child(
 7521                    h_flex().ml_1().child(
 7522                        Icon::new(IconName::Info)
 7523                            .size(IconSize::Small)
 7524                            .color(cx.theme().status().error.into()),
 7525                    ),
 7526                )
 7527            })
 7528            .when_some(icon, |element, icon| {
 7529                element.child(
 7530                    div()
 7531                        .mt(px(1.5))
 7532                        .child(Icon::new(icon).size(IconSize::Small)),
 7533                )
 7534            });
 7535
 7536        Some(result)
 7537    }
 7538
 7539    fn edit_prediction_line_popover_bg_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.1))
 7543    }
 7544
 7545    fn edit_prediction_callout_popover_border_color(cx: &App) -> Hsla {
 7546        let accent_color = cx.theme().colors().text_accent;
 7547        let editor_bg_color = cx.theme().colors().editor_background;
 7548        editor_bg_color.blend(accent_color.opacity(0.6))
 7549    }
 7550
 7551    fn render_edit_prediction_cursor_popover(
 7552        &self,
 7553        min_width: Pixels,
 7554        max_width: Pixels,
 7555        cursor_point: Point,
 7556        style: &EditorStyle,
 7557        accept_keystroke: Option<&gpui::Keystroke>,
 7558        _window: &Window,
 7559        cx: &mut Context<Editor>,
 7560    ) -> Option<AnyElement> {
 7561        let provider = self.edit_prediction_provider.as_ref()?;
 7562
 7563        if provider.provider.needs_terms_acceptance(cx) {
 7564            return Some(
 7565                h_flex()
 7566                    .min_w(min_width)
 7567                    .flex_1()
 7568                    .px_2()
 7569                    .py_1()
 7570                    .gap_3()
 7571                    .elevation_2(cx)
 7572                    .hover(|style| style.bg(cx.theme().colors().element_hover))
 7573                    .id("accept-terms")
 7574                    .cursor_pointer()
 7575                    .on_mouse_down(MouseButton::Left, |_, window, _| window.prevent_default())
 7576                    .on_click(cx.listener(|this, _event, window, cx| {
 7577                        cx.stop_propagation();
 7578                        this.report_editor_event("Edit Prediction Provider ToS Clicked", None, cx);
 7579                        window.dispatch_action(
 7580                            zed_actions::OpenZedPredictOnboarding.boxed_clone(),
 7581                            cx,
 7582                        );
 7583                    }))
 7584                    .child(
 7585                        h_flex()
 7586                            .flex_1()
 7587                            .gap_2()
 7588                            .child(Icon::new(IconName::ZedPredict))
 7589                            .child(Label::new("Accept Terms of Service"))
 7590                            .child(div().w_full())
 7591                            .child(
 7592                                Icon::new(IconName::ArrowUpRight)
 7593                                    .color(Color::Muted)
 7594                                    .size(IconSize::Small),
 7595                            )
 7596                            .into_any_element(),
 7597                    )
 7598                    .into_any(),
 7599            );
 7600        }
 7601
 7602        let is_refreshing = provider.provider.is_refreshing(cx);
 7603
 7604        fn pending_completion_container() -> Div {
 7605            h_flex()
 7606                .h_full()
 7607                .flex_1()
 7608                .gap_2()
 7609                .child(Icon::new(IconName::ZedPredict))
 7610        }
 7611
 7612        let completion = match &self.active_inline_completion {
 7613            Some(prediction) => {
 7614                if !self.has_visible_completions_menu() {
 7615                    const RADIUS: Pixels = px(6.);
 7616                    const BORDER_WIDTH: Pixels = px(1.);
 7617
 7618                    return Some(
 7619                        h_flex()
 7620                            .elevation_2(cx)
 7621                            .border(BORDER_WIDTH)
 7622                            .border_color(cx.theme().colors().border)
 7623                            .when(accept_keystroke.is_none(), |el| {
 7624                                el.border_color(cx.theme().status().error)
 7625                            })
 7626                            .rounded(RADIUS)
 7627                            .rounded_tl(px(0.))
 7628                            .overflow_hidden()
 7629                            .child(div().px_1p5().child(match &prediction.completion {
 7630                                InlineCompletion::Move { target, snapshot } => {
 7631                                    use text::ToPoint as _;
 7632                                    if target.text_anchor.to_point(&snapshot).row > cursor_point.row
 7633                                    {
 7634                                        Icon::new(IconName::ZedPredictDown)
 7635                                    } else {
 7636                                        Icon::new(IconName::ZedPredictUp)
 7637                                    }
 7638                                }
 7639                                InlineCompletion::Edit { .. } => Icon::new(IconName::ZedPredict),
 7640                            }))
 7641                            .child(
 7642                                h_flex()
 7643                                    .gap_1()
 7644                                    .py_1()
 7645                                    .px_2()
 7646                                    .rounded_r(RADIUS - BORDER_WIDTH)
 7647                                    .border_l_1()
 7648                                    .border_color(cx.theme().colors().border)
 7649                                    .bg(Self::edit_prediction_line_popover_bg_color(cx))
 7650                                    .when(self.edit_prediction_preview.released_too_fast(), |el| {
 7651                                        el.child(
 7652                                            Label::new("Hold")
 7653                                                .size(LabelSize::Small)
 7654                                                .when(accept_keystroke.is_none(), |el| {
 7655                                                    el.strikethrough()
 7656                                                })
 7657                                                .line_height_style(LineHeightStyle::UiLabel),
 7658                                        )
 7659                                    })
 7660                                    .id("edit_prediction_cursor_popover_keybind")
 7661                                    .when(accept_keystroke.is_none(), |el| {
 7662                                        let status_colors = cx.theme().status();
 7663
 7664                                        el.bg(status_colors.error_background)
 7665                                            .border_color(status_colors.error.opacity(0.6))
 7666                                            .child(Icon::new(IconName::Info).color(Color::Error))
 7667                                            .cursor_default()
 7668                                            .hoverable_tooltip(move |_window, cx| {
 7669                                                cx.new(|_| MissingEditPredictionKeybindingTooltip)
 7670                                                    .into()
 7671                                            })
 7672                                    })
 7673                                    .when_some(
 7674                                        accept_keystroke.as_ref(),
 7675                                        |el, accept_keystroke| {
 7676                                            el.child(h_flex().children(ui::render_modifiers(
 7677                                                &accept_keystroke.modifiers,
 7678                                                PlatformStyle::platform(),
 7679                                                Some(Color::Default),
 7680                                                Some(IconSize::XSmall.rems().into()),
 7681                                                false,
 7682                                            )))
 7683                                        },
 7684                                    ),
 7685                            )
 7686                            .into_any(),
 7687                    );
 7688                }
 7689
 7690                self.render_edit_prediction_cursor_popover_preview(
 7691                    prediction,
 7692                    cursor_point,
 7693                    style,
 7694                    cx,
 7695                )?
 7696            }
 7697
 7698            None if is_refreshing => match &self.stale_inline_completion_in_menu {
 7699                Some(stale_completion) => self.render_edit_prediction_cursor_popover_preview(
 7700                    stale_completion,
 7701                    cursor_point,
 7702                    style,
 7703                    cx,
 7704                )?,
 7705
 7706                None => {
 7707                    pending_completion_container().child(Label::new("...").size(LabelSize::Small))
 7708                }
 7709            },
 7710
 7711            None => pending_completion_container().child(Label::new("No Prediction")),
 7712        };
 7713
 7714        let completion = if is_refreshing {
 7715            completion
 7716                .with_animation(
 7717                    "loading-completion",
 7718                    Animation::new(Duration::from_secs(2))
 7719                        .repeat()
 7720                        .with_easing(pulsating_between(0.4, 0.8)),
 7721                    |label, delta| label.opacity(delta),
 7722                )
 7723                .into_any_element()
 7724        } else {
 7725            completion.into_any_element()
 7726        };
 7727
 7728        let has_completion = self.active_inline_completion.is_some();
 7729
 7730        let is_platform_style_mac = PlatformStyle::platform() == PlatformStyle::Mac;
 7731        Some(
 7732            h_flex()
 7733                .min_w(min_width)
 7734                .max_w(max_width)
 7735                .flex_1()
 7736                .elevation_2(cx)
 7737                .border_color(cx.theme().colors().border)
 7738                .child(
 7739                    div()
 7740                        .flex_1()
 7741                        .py_1()
 7742                        .px_2()
 7743                        .overflow_hidden()
 7744                        .child(completion),
 7745                )
 7746                .when_some(accept_keystroke, |el, accept_keystroke| {
 7747                    if !accept_keystroke.modifiers.modified() {
 7748                        return el;
 7749                    }
 7750
 7751                    el.child(
 7752                        h_flex()
 7753                            .h_full()
 7754                            .border_l_1()
 7755                            .rounded_r_lg()
 7756                            .border_color(cx.theme().colors().border)
 7757                            .bg(Self::edit_prediction_line_popover_bg_color(cx))
 7758                            .gap_1()
 7759                            .py_1()
 7760                            .px_2()
 7761                            .child(
 7762                                h_flex()
 7763                                    .font(theme::ThemeSettings::get_global(cx).buffer_font.clone())
 7764                                    .when(is_platform_style_mac, |parent| parent.gap_1())
 7765                                    .child(h_flex().children(ui::render_modifiers(
 7766                                        &accept_keystroke.modifiers,
 7767                                        PlatformStyle::platform(),
 7768                                        Some(if !has_completion {
 7769                                            Color::Muted
 7770                                        } else {
 7771                                            Color::Default
 7772                                        }),
 7773                                        None,
 7774                                        false,
 7775                                    ))),
 7776                            )
 7777                            .child(Label::new("Preview").into_any_element())
 7778                            .opacity(if has_completion { 1.0 } else { 0.4 }),
 7779                    )
 7780                })
 7781                .into_any(),
 7782        )
 7783    }
 7784
 7785    fn render_edit_prediction_cursor_popover_preview(
 7786        &self,
 7787        completion: &InlineCompletionState,
 7788        cursor_point: Point,
 7789        style: &EditorStyle,
 7790        cx: &mut Context<Editor>,
 7791    ) -> Option<Div> {
 7792        use text::ToPoint as _;
 7793
 7794        fn render_relative_row_jump(
 7795            prefix: impl Into<String>,
 7796            current_row: u32,
 7797            target_row: u32,
 7798        ) -> Div {
 7799            let (row_diff, arrow) = if target_row < current_row {
 7800                (current_row - target_row, IconName::ArrowUp)
 7801            } else {
 7802                (target_row - current_row, IconName::ArrowDown)
 7803            };
 7804
 7805            h_flex()
 7806                .child(
 7807                    Label::new(format!("{}{}", prefix.into(), row_diff))
 7808                        .color(Color::Muted)
 7809                        .size(LabelSize::Small),
 7810                )
 7811                .child(Icon::new(arrow).color(Color::Muted).size(IconSize::Small))
 7812        }
 7813
 7814        match &completion.completion {
 7815            InlineCompletion::Move {
 7816                target, snapshot, ..
 7817            } => Some(
 7818                h_flex()
 7819                    .px_2()
 7820                    .gap_2()
 7821                    .flex_1()
 7822                    .child(
 7823                        if target.text_anchor.to_point(&snapshot).row > cursor_point.row {
 7824                            Icon::new(IconName::ZedPredictDown)
 7825                        } else {
 7826                            Icon::new(IconName::ZedPredictUp)
 7827                        },
 7828                    )
 7829                    .child(Label::new("Jump to Edit")),
 7830            ),
 7831
 7832            InlineCompletion::Edit {
 7833                edits,
 7834                edit_preview,
 7835                snapshot,
 7836                display_mode: _,
 7837            } => {
 7838                let first_edit_row = edits.first()?.0.start.text_anchor.to_point(&snapshot).row;
 7839
 7840                let (highlighted_edits, has_more_lines) = crate::inline_completion_edit_text(
 7841                    &snapshot,
 7842                    &edits,
 7843                    edit_preview.as_ref()?,
 7844                    true,
 7845                    cx,
 7846                )
 7847                .first_line_preview();
 7848
 7849                let styled_text = gpui::StyledText::new(highlighted_edits.text)
 7850                    .with_default_highlights(&style.text, highlighted_edits.highlights);
 7851
 7852                let preview = h_flex()
 7853                    .gap_1()
 7854                    .min_w_16()
 7855                    .child(styled_text)
 7856                    .when(has_more_lines, |parent| parent.child(""));
 7857
 7858                let left = if first_edit_row != cursor_point.row {
 7859                    render_relative_row_jump("", cursor_point.row, first_edit_row)
 7860                        .into_any_element()
 7861                } else {
 7862                    Icon::new(IconName::ZedPredict).into_any_element()
 7863                };
 7864
 7865                Some(
 7866                    h_flex()
 7867                        .h_full()
 7868                        .flex_1()
 7869                        .gap_2()
 7870                        .pr_1()
 7871                        .overflow_x_hidden()
 7872                        .font(theme::ThemeSettings::get_global(cx).buffer_font.clone())
 7873                        .child(left)
 7874                        .child(preview),
 7875                )
 7876            }
 7877        }
 7878    }
 7879
 7880    fn render_context_menu(
 7881        &self,
 7882        style: &EditorStyle,
 7883        max_height_in_lines: u32,
 7884        window: &mut Window,
 7885        cx: &mut Context<Editor>,
 7886    ) -> Option<AnyElement> {
 7887        let menu = self.context_menu.borrow();
 7888        let menu = menu.as_ref()?;
 7889        if !menu.visible() {
 7890            return None;
 7891        };
 7892        Some(menu.render(style, max_height_in_lines, window, cx))
 7893    }
 7894
 7895    fn render_context_menu_aside(
 7896        &mut self,
 7897        max_size: Size<Pixels>,
 7898        window: &mut Window,
 7899        cx: &mut Context<Editor>,
 7900    ) -> Option<AnyElement> {
 7901        self.context_menu.borrow_mut().as_mut().and_then(|menu| {
 7902            if menu.visible() {
 7903                menu.render_aside(self, max_size, window, cx)
 7904            } else {
 7905                None
 7906            }
 7907        })
 7908    }
 7909
 7910    fn hide_context_menu(
 7911        &mut self,
 7912        window: &mut Window,
 7913        cx: &mut Context<Self>,
 7914    ) -> Option<CodeContextMenu> {
 7915        cx.notify();
 7916        self.completion_tasks.clear();
 7917        let context_menu = self.context_menu.borrow_mut().take();
 7918        self.stale_inline_completion_in_menu.take();
 7919        self.update_visible_inline_completion(window, cx);
 7920        context_menu
 7921    }
 7922
 7923    fn show_snippet_choices(
 7924        &mut self,
 7925        choices: &Vec<String>,
 7926        selection: Range<Anchor>,
 7927        cx: &mut Context<Self>,
 7928    ) {
 7929        if selection.start.buffer_id.is_none() {
 7930            return;
 7931        }
 7932        let buffer_id = selection.start.buffer_id.unwrap();
 7933        let buffer = self.buffer().read(cx).buffer(buffer_id);
 7934        let id = post_inc(&mut self.next_completion_id);
 7935
 7936        if let Some(buffer) = buffer {
 7937            *self.context_menu.borrow_mut() = Some(CodeContextMenu::Completions(
 7938                CompletionsMenu::new_snippet_choices(id, true, choices, selection, buffer),
 7939            ));
 7940        }
 7941    }
 7942
 7943    pub fn insert_snippet(
 7944        &mut self,
 7945        insertion_ranges: &[Range<usize>],
 7946        snippet: Snippet,
 7947        window: &mut Window,
 7948        cx: &mut Context<Self>,
 7949    ) -> Result<()> {
 7950        struct Tabstop<T> {
 7951            is_end_tabstop: bool,
 7952            ranges: Vec<Range<T>>,
 7953            choices: Option<Vec<String>>,
 7954        }
 7955
 7956        let tabstops = self.buffer.update(cx, |buffer, cx| {
 7957            let snippet_text: Arc<str> = snippet.text.clone().into();
 7958            let edits = insertion_ranges
 7959                .iter()
 7960                .cloned()
 7961                .map(|range| (range, snippet_text.clone()));
 7962            buffer.edit(edits, Some(AutoindentMode::EachLine), cx);
 7963
 7964            let snapshot = &*buffer.read(cx);
 7965            let snippet = &snippet;
 7966            snippet
 7967                .tabstops
 7968                .iter()
 7969                .map(|tabstop| {
 7970                    let is_end_tabstop = tabstop.ranges.first().map_or(false, |tabstop| {
 7971                        tabstop.is_empty() && tabstop.start == snippet.text.len() as isize
 7972                    });
 7973                    let mut tabstop_ranges = tabstop
 7974                        .ranges
 7975                        .iter()
 7976                        .flat_map(|tabstop_range| {
 7977                            let mut delta = 0_isize;
 7978                            insertion_ranges.iter().map(move |insertion_range| {
 7979                                let insertion_start = insertion_range.start as isize + delta;
 7980                                delta +=
 7981                                    snippet.text.len() as isize - insertion_range.len() as isize;
 7982
 7983                                let start = ((insertion_start + tabstop_range.start) as usize)
 7984                                    .min(snapshot.len());
 7985                                let end = ((insertion_start + tabstop_range.end) as usize)
 7986                                    .min(snapshot.len());
 7987                                snapshot.anchor_before(start)..snapshot.anchor_after(end)
 7988                            })
 7989                        })
 7990                        .collect::<Vec<_>>();
 7991                    tabstop_ranges.sort_unstable_by(|a, b| a.start.cmp(&b.start, snapshot));
 7992
 7993                    Tabstop {
 7994                        is_end_tabstop,
 7995                        ranges: tabstop_ranges,
 7996                        choices: tabstop.choices.clone(),
 7997                    }
 7998                })
 7999                .collect::<Vec<_>>()
 8000        });
 8001        if let Some(tabstop) = tabstops.first() {
 8002            self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8003                s.select_ranges(tabstop.ranges.iter().cloned());
 8004            });
 8005
 8006            if let Some(choices) = &tabstop.choices {
 8007                if let Some(selection) = tabstop.ranges.first() {
 8008                    self.show_snippet_choices(choices, selection.clone(), cx)
 8009                }
 8010            }
 8011
 8012            // If we're already at the last tabstop and it's at the end of the snippet,
 8013            // we're done, we don't need to keep the state around.
 8014            if !tabstop.is_end_tabstop {
 8015                let choices = tabstops
 8016                    .iter()
 8017                    .map(|tabstop| tabstop.choices.clone())
 8018                    .collect();
 8019
 8020                let ranges = tabstops
 8021                    .into_iter()
 8022                    .map(|tabstop| tabstop.ranges)
 8023                    .collect::<Vec<_>>();
 8024
 8025                self.snippet_stack.push(SnippetState {
 8026                    active_index: 0,
 8027                    ranges,
 8028                    choices,
 8029                });
 8030            }
 8031
 8032            // Check whether the just-entered snippet ends with an auto-closable bracket.
 8033            if self.autoclose_regions.is_empty() {
 8034                let snapshot = self.buffer.read(cx).snapshot(cx);
 8035                for selection in &mut self.selections.all::<Point>(cx) {
 8036                    let selection_head = selection.head();
 8037                    let Some(scope) = snapshot.language_scope_at(selection_head) else {
 8038                        continue;
 8039                    };
 8040
 8041                    let mut bracket_pair = None;
 8042                    let next_chars = snapshot.chars_at(selection_head).collect::<String>();
 8043                    let prev_chars = snapshot
 8044                        .reversed_chars_at(selection_head)
 8045                        .collect::<String>();
 8046                    for (pair, enabled) in scope.brackets() {
 8047                        if enabled
 8048                            && pair.close
 8049                            && prev_chars.starts_with(pair.start.as_str())
 8050                            && next_chars.starts_with(pair.end.as_str())
 8051                        {
 8052                            bracket_pair = Some(pair.clone());
 8053                            break;
 8054                        }
 8055                    }
 8056                    if let Some(pair) = bracket_pair {
 8057                        let snapshot_settings = snapshot.language_settings_at(selection_head, cx);
 8058                        let autoclose_enabled =
 8059                            self.use_autoclose && snapshot_settings.use_autoclose;
 8060                        if autoclose_enabled {
 8061                            let start = snapshot.anchor_after(selection_head);
 8062                            let end = snapshot.anchor_after(selection_head);
 8063                            self.autoclose_regions.push(AutocloseRegion {
 8064                                selection_id: selection.id,
 8065                                range: start..end,
 8066                                pair,
 8067                            });
 8068                        }
 8069                    }
 8070                }
 8071            }
 8072        }
 8073        Ok(())
 8074    }
 8075
 8076    pub fn move_to_next_snippet_tabstop(
 8077        &mut self,
 8078        window: &mut Window,
 8079        cx: &mut Context<Self>,
 8080    ) -> bool {
 8081        self.move_to_snippet_tabstop(Bias::Right, window, cx)
 8082    }
 8083
 8084    pub fn move_to_prev_snippet_tabstop(
 8085        &mut self,
 8086        window: &mut Window,
 8087        cx: &mut Context<Self>,
 8088    ) -> bool {
 8089        self.move_to_snippet_tabstop(Bias::Left, window, cx)
 8090    }
 8091
 8092    pub fn move_to_snippet_tabstop(
 8093        &mut self,
 8094        bias: Bias,
 8095        window: &mut Window,
 8096        cx: &mut Context<Self>,
 8097    ) -> bool {
 8098        if let Some(mut snippet) = self.snippet_stack.pop() {
 8099            match bias {
 8100                Bias::Left => {
 8101                    if snippet.active_index > 0 {
 8102                        snippet.active_index -= 1;
 8103                    } else {
 8104                        self.snippet_stack.push(snippet);
 8105                        return false;
 8106                    }
 8107                }
 8108                Bias::Right => {
 8109                    if snippet.active_index + 1 < snippet.ranges.len() {
 8110                        snippet.active_index += 1;
 8111                    } else {
 8112                        self.snippet_stack.push(snippet);
 8113                        return false;
 8114                    }
 8115                }
 8116            }
 8117            if let Some(current_ranges) = snippet.ranges.get(snippet.active_index) {
 8118                self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8119                    s.select_anchor_ranges(current_ranges.iter().cloned())
 8120                });
 8121
 8122                if let Some(choices) = &snippet.choices[snippet.active_index] {
 8123                    if let Some(selection) = current_ranges.first() {
 8124                        self.show_snippet_choices(&choices, selection.clone(), cx);
 8125                    }
 8126                }
 8127
 8128                // If snippet state is not at the last tabstop, push it back on the stack
 8129                if snippet.active_index + 1 < snippet.ranges.len() {
 8130                    self.snippet_stack.push(snippet);
 8131                }
 8132                return true;
 8133            }
 8134        }
 8135
 8136        false
 8137    }
 8138
 8139    pub fn clear(&mut self, window: &mut Window, cx: &mut Context<Self>) {
 8140        self.transact(window, cx, |this, window, cx| {
 8141            this.select_all(&SelectAll, window, cx);
 8142            this.insert("", window, cx);
 8143        });
 8144    }
 8145
 8146    pub fn backspace(&mut self, _: &Backspace, window: &mut Window, cx: &mut Context<Self>) {
 8147        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
 8148        self.transact(window, cx, |this, window, cx| {
 8149            this.select_autoclose_pair(window, cx);
 8150            let mut linked_ranges = HashMap::<_, Vec<_>>::default();
 8151            if !this.linked_edit_ranges.is_empty() {
 8152                let selections = this.selections.all::<MultiBufferPoint>(cx);
 8153                let snapshot = this.buffer.read(cx).snapshot(cx);
 8154
 8155                for selection in selections.iter() {
 8156                    let selection_start = snapshot.anchor_before(selection.start).text_anchor;
 8157                    let selection_end = snapshot.anchor_after(selection.end).text_anchor;
 8158                    if selection_start.buffer_id != selection_end.buffer_id {
 8159                        continue;
 8160                    }
 8161                    if let Some(ranges) =
 8162                        this.linked_editing_ranges_for(selection_start..selection_end, cx)
 8163                    {
 8164                        for (buffer, entries) in ranges {
 8165                            linked_ranges.entry(buffer).or_default().extend(entries);
 8166                        }
 8167                    }
 8168                }
 8169            }
 8170
 8171            let mut selections = this.selections.all::<MultiBufferPoint>(cx);
 8172            let display_map = this.display_map.update(cx, |map, cx| map.snapshot(cx));
 8173            for selection in &mut selections {
 8174                if selection.is_empty() {
 8175                    let old_head = selection.head();
 8176                    let mut new_head =
 8177                        movement::left(&display_map, old_head.to_display_point(&display_map))
 8178                            .to_point(&display_map);
 8179                    if let Some((buffer, line_buffer_range)) = display_map
 8180                        .buffer_snapshot
 8181                        .buffer_line_for_row(MultiBufferRow(old_head.row))
 8182                    {
 8183                        let indent_size = buffer.indent_size_for_line(line_buffer_range.start.row);
 8184                        let indent_len = match indent_size.kind {
 8185                            IndentKind::Space => {
 8186                                buffer.settings_at(line_buffer_range.start, cx).tab_size
 8187                            }
 8188                            IndentKind::Tab => NonZeroU32::new(1).unwrap(),
 8189                        };
 8190                        if old_head.column <= indent_size.len && old_head.column > 0 {
 8191                            let indent_len = indent_len.get();
 8192                            new_head = cmp::min(
 8193                                new_head,
 8194                                MultiBufferPoint::new(
 8195                                    old_head.row,
 8196                                    ((old_head.column - 1) / indent_len) * indent_len,
 8197                                ),
 8198                            );
 8199                        }
 8200                    }
 8201
 8202                    selection.set_head(new_head, SelectionGoal::None);
 8203                }
 8204            }
 8205
 8206            this.signature_help_state.set_backspace_pressed(true);
 8207            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8208                s.select(selections)
 8209            });
 8210            this.insert("", window, cx);
 8211            let empty_str: Arc<str> = Arc::from("");
 8212            for (buffer, edits) in linked_ranges {
 8213                let snapshot = buffer.read(cx).snapshot();
 8214                use text::ToPoint as TP;
 8215
 8216                let edits = edits
 8217                    .into_iter()
 8218                    .map(|range| {
 8219                        let end_point = TP::to_point(&range.end, &snapshot);
 8220                        let mut start_point = TP::to_point(&range.start, &snapshot);
 8221
 8222                        if end_point == start_point {
 8223                            let offset = text::ToOffset::to_offset(&range.start, &snapshot)
 8224                                .saturating_sub(1);
 8225                            start_point =
 8226                                snapshot.clip_point(TP::to_point(&offset, &snapshot), Bias::Left);
 8227                        };
 8228
 8229                        (start_point..end_point, empty_str.clone())
 8230                    })
 8231                    .sorted_by_key(|(range, _)| range.start)
 8232                    .collect::<Vec<_>>();
 8233                buffer.update(cx, |this, cx| {
 8234                    this.edit(edits, None, cx);
 8235                })
 8236            }
 8237            this.refresh_inline_completion(true, false, window, cx);
 8238            linked_editing_ranges::refresh_linked_ranges(this, window, cx);
 8239        });
 8240    }
 8241
 8242    pub fn delete(&mut self, _: &Delete, window: &mut Window, cx: &mut Context<Self>) {
 8243        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
 8244        self.transact(window, cx, |this, window, cx| {
 8245            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8246                s.move_with(|map, selection| {
 8247                    if selection.is_empty() {
 8248                        let cursor = movement::right(map, selection.head());
 8249                        selection.end = cursor;
 8250                        selection.reversed = true;
 8251                        selection.goal = SelectionGoal::None;
 8252                    }
 8253                })
 8254            });
 8255            this.insert("", window, cx);
 8256            this.refresh_inline_completion(true, false, window, cx);
 8257        });
 8258    }
 8259
 8260    pub fn backtab(&mut self, _: &Backtab, window: &mut Window, cx: &mut Context<Self>) {
 8261        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
 8262        if self.move_to_prev_snippet_tabstop(window, cx) {
 8263            return;
 8264        }
 8265        self.outdent(&Outdent, window, cx);
 8266    }
 8267
 8268    pub fn tab(&mut self, _: &Tab, window: &mut Window, cx: &mut Context<Self>) {
 8269        if self.move_to_next_snippet_tabstop(window, cx) {
 8270            self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
 8271            return;
 8272        }
 8273        if self.read_only(cx) {
 8274            return;
 8275        }
 8276        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
 8277        let mut selections = self.selections.all_adjusted(cx);
 8278        let buffer = self.buffer.read(cx);
 8279        let snapshot = buffer.snapshot(cx);
 8280        let rows_iter = selections.iter().map(|s| s.head().row);
 8281        let suggested_indents = snapshot.suggested_indents(rows_iter, cx);
 8282
 8283        let mut edits = Vec::new();
 8284        let mut prev_edited_row = 0;
 8285        let mut row_delta = 0;
 8286        for selection in &mut selections {
 8287            if selection.start.row != prev_edited_row {
 8288                row_delta = 0;
 8289            }
 8290            prev_edited_row = selection.end.row;
 8291
 8292            // If the selection is non-empty, then increase the indentation of the selected lines.
 8293            if !selection.is_empty() {
 8294                row_delta =
 8295                    Self::indent_selection(buffer, &snapshot, selection, &mut edits, row_delta, cx);
 8296                continue;
 8297            }
 8298
 8299            // If the selection is empty and the cursor is in the leading whitespace before the
 8300            // suggested indentation, then auto-indent the line.
 8301            let cursor = selection.head();
 8302            let current_indent = snapshot.indent_size_for_line(MultiBufferRow(cursor.row));
 8303            if let Some(suggested_indent) =
 8304                suggested_indents.get(&MultiBufferRow(cursor.row)).copied()
 8305            {
 8306                if cursor.column < suggested_indent.len
 8307                    && cursor.column <= current_indent.len
 8308                    && current_indent.len <= suggested_indent.len
 8309                {
 8310                    selection.start = Point::new(cursor.row, suggested_indent.len);
 8311                    selection.end = selection.start;
 8312                    if row_delta == 0 {
 8313                        edits.extend(Buffer::edit_for_indent_size_adjustment(
 8314                            cursor.row,
 8315                            current_indent,
 8316                            suggested_indent,
 8317                        ));
 8318                        row_delta = suggested_indent.len - current_indent.len;
 8319                    }
 8320                    continue;
 8321                }
 8322            }
 8323
 8324            // Otherwise, insert a hard or soft tab.
 8325            let settings = buffer.language_settings_at(cursor, cx);
 8326            let tab_size = if settings.hard_tabs {
 8327                IndentSize::tab()
 8328            } else {
 8329                let tab_size = settings.tab_size.get();
 8330                let indent_remainder = snapshot
 8331                    .text_for_range(Point::new(cursor.row, 0)..cursor)
 8332                    .flat_map(str::chars)
 8333                    .fold(row_delta % tab_size, |counter: u32, c| {
 8334                        if c == '\t' {
 8335                            0
 8336                        } else {
 8337                            (counter + 1) % tab_size
 8338                        }
 8339                    });
 8340
 8341                let chars_to_next_tab_stop = tab_size - indent_remainder;
 8342                IndentSize::spaces(chars_to_next_tab_stop)
 8343            };
 8344            selection.start = Point::new(cursor.row, cursor.column + row_delta + tab_size.len);
 8345            selection.end = selection.start;
 8346            edits.push((cursor..cursor, tab_size.chars().collect::<String>()));
 8347            row_delta += tab_size.len;
 8348        }
 8349
 8350        self.transact(window, cx, |this, window, cx| {
 8351            this.buffer.update(cx, |b, cx| b.edit(edits, None, cx));
 8352            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8353                s.select(selections)
 8354            });
 8355            this.refresh_inline_completion(true, false, window, cx);
 8356        });
 8357    }
 8358
 8359    pub fn indent(&mut self, _: &Indent, window: &mut Window, cx: &mut Context<Self>) {
 8360        if self.read_only(cx) {
 8361            return;
 8362        }
 8363        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
 8364        let mut selections = self.selections.all::<Point>(cx);
 8365        let mut prev_edited_row = 0;
 8366        let mut row_delta = 0;
 8367        let mut edits = Vec::new();
 8368        let buffer = self.buffer.read(cx);
 8369        let snapshot = buffer.snapshot(cx);
 8370        for selection in &mut selections {
 8371            if selection.start.row != prev_edited_row {
 8372                row_delta = 0;
 8373            }
 8374            prev_edited_row = selection.end.row;
 8375
 8376            row_delta =
 8377                Self::indent_selection(buffer, &snapshot, selection, &mut edits, row_delta, cx);
 8378        }
 8379
 8380        self.transact(window, cx, |this, window, cx| {
 8381            this.buffer.update(cx, |b, cx| b.edit(edits, None, cx));
 8382            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8383                s.select(selections)
 8384            });
 8385        });
 8386    }
 8387
 8388    fn indent_selection(
 8389        buffer: &MultiBuffer,
 8390        snapshot: &MultiBufferSnapshot,
 8391        selection: &mut Selection<Point>,
 8392        edits: &mut Vec<(Range<Point>, String)>,
 8393        delta_for_start_row: u32,
 8394        cx: &App,
 8395    ) -> u32 {
 8396        let settings = buffer.language_settings_at(selection.start, cx);
 8397        let tab_size = settings.tab_size.get();
 8398        let indent_kind = if settings.hard_tabs {
 8399            IndentKind::Tab
 8400        } else {
 8401            IndentKind::Space
 8402        };
 8403        let mut start_row = selection.start.row;
 8404        let mut end_row = selection.end.row + 1;
 8405
 8406        // If a selection ends at the beginning of a line, don't indent
 8407        // that last line.
 8408        if selection.end.column == 0 && selection.end.row > selection.start.row {
 8409            end_row -= 1;
 8410        }
 8411
 8412        // Avoid re-indenting a row that has already been indented by a
 8413        // previous selection, but still update this selection's column
 8414        // to reflect that indentation.
 8415        if delta_for_start_row > 0 {
 8416            start_row += 1;
 8417            selection.start.column += delta_for_start_row;
 8418            if selection.end.row == selection.start.row {
 8419                selection.end.column += delta_for_start_row;
 8420            }
 8421        }
 8422
 8423        let mut delta_for_end_row = 0;
 8424        let has_multiple_rows = start_row + 1 != end_row;
 8425        for row in start_row..end_row {
 8426            let current_indent = snapshot.indent_size_for_line(MultiBufferRow(row));
 8427            let indent_delta = match (current_indent.kind, indent_kind) {
 8428                (IndentKind::Space, IndentKind::Space) => {
 8429                    let columns_to_next_tab_stop = tab_size - (current_indent.len % tab_size);
 8430                    IndentSize::spaces(columns_to_next_tab_stop)
 8431                }
 8432                (IndentKind::Tab, IndentKind::Space) => IndentSize::spaces(tab_size),
 8433                (_, IndentKind::Tab) => IndentSize::tab(),
 8434            };
 8435
 8436            let start = if has_multiple_rows || current_indent.len < selection.start.column {
 8437                0
 8438            } else {
 8439                selection.start.column
 8440            };
 8441            let row_start = Point::new(row, start);
 8442            edits.push((
 8443                row_start..row_start,
 8444                indent_delta.chars().collect::<String>(),
 8445            ));
 8446
 8447            // Update this selection's endpoints to reflect the indentation.
 8448            if row == selection.start.row {
 8449                selection.start.column += indent_delta.len;
 8450            }
 8451            if row == selection.end.row {
 8452                selection.end.column += indent_delta.len;
 8453                delta_for_end_row = indent_delta.len;
 8454            }
 8455        }
 8456
 8457        if selection.start.row == selection.end.row {
 8458            delta_for_start_row + delta_for_end_row
 8459        } else {
 8460            delta_for_end_row
 8461        }
 8462    }
 8463
 8464    pub fn outdent(&mut self, _: &Outdent, window: &mut Window, cx: &mut Context<Self>) {
 8465        if self.read_only(cx) {
 8466            return;
 8467        }
 8468        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
 8469        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 8470        let selections = self.selections.all::<Point>(cx);
 8471        let mut deletion_ranges = Vec::new();
 8472        let mut last_outdent = None;
 8473        {
 8474            let buffer = self.buffer.read(cx);
 8475            let snapshot = buffer.snapshot(cx);
 8476            for selection in &selections {
 8477                let settings = buffer.language_settings_at(selection.start, cx);
 8478                let tab_size = settings.tab_size.get();
 8479                let mut rows = selection.spanned_rows(false, &display_map);
 8480
 8481                // Avoid re-outdenting a row that has already been outdented by a
 8482                // previous selection.
 8483                if let Some(last_row) = last_outdent {
 8484                    if last_row == rows.start {
 8485                        rows.start = rows.start.next_row();
 8486                    }
 8487                }
 8488                let has_multiple_rows = rows.len() > 1;
 8489                for row in rows.iter_rows() {
 8490                    let indent_size = snapshot.indent_size_for_line(row);
 8491                    if indent_size.len > 0 {
 8492                        let deletion_len = match indent_size.kind {
 8493                            IndentKind::Space => {
 8494                                let columns_to_prev_tab_stop = indent_size.len % tab_size;
 8495                                if columns_to_prev_tab_stop == 0 {
 8496                                    tab_size
 8497                                } else {
 8498                                    columns_to_prev_tab_stop
 8499                                }
 8500                            }
 8501                            IndentKind::Tab => 1,
 8502                        };
 8503                        let start = if has_multiple_rows
 8504                            || deletion_len > selection.start.column
 8505                            || indent_size.len < selection.start.column
 8506                        {
 8507                            0
 8508                        } else {
 8509                            selection.start.column - deletion_len
 8510                        };
 8511                        deletion_ranges.push(
 8512                            Point::new(row.0, start)..Point::new(row.0, start + deletion_len),
 8513                        );
 8514                        last_outdent = Some(row);
 8515                    }
 8516                }
 8517            }
 8518        }
 8519
 8520        self.transact(window, cx, |this, window, cx| {
 8521            this.buffer.update(cx, |buffer, cx| {
 8522                let empty_str: Arc<str> = Arc::default();
 8523                buffer.edit(
 8524                    deletion_ranges
 8525                        .into_iter()
 8526                        .map(|range| (range, empty_str.clone())),
 8527                    None,
 8528                    cx,
 8529                );
 8530            });
 8531            let selections = this.selections.all::<usize>(cx);
 8532            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8533                s.select(selections)
 8534            });
 8535        });
 8536    }
 8537
 8538    pub fn autoindent(&mut self, _: &AutoIndent, window: &mut Window, cx: &mut Context<Self>) {
 8539        if self.read_only(cx) {
 8540            return;
 8541        }
 8542        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
 8543        let selections = self
 8544            .selections
 8545            .all::<usize>(cx)
 8546            .into_iter()
 8547            .map(|s| s.range());
 8548
 8549        self.transact(window, cx, |this, window, cx| {
 8550            this.buffer.update(cx, |buffer, cx| {
 8551                buffer.autoindent_ranges(selections, cx);
 8552            });
 8553            let selections = this.selections.all::<usize>(cx);
 8554            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8555                s.select(selections)
 8556            });
 8557        });
 8558    }
 8559
 8560    pub fn delete_line(&mut self, _: &DeleteLine, window: &mut Window, cx: &mut Context<Self>) {
 8561        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
 8562        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 8563        let selections = self.selections.all::<Point>(cx);
 8564
 8565        let mut new_cursors = Vec::new();
 8566        let mut edit_ranges = Vec::new();
 8567        let mut selections = selections.iter().peekable();
 8568        while let Some(selection) = selections.next() {
 8569            let mut rows = selection.spanned_rows(false, &display_map);
 8570            let goal_display_column = selection.head().to_display_point(&display_map).column();
 8571
 8572            // Accumulate contiguous regions of rows that we want to delete.
 8573            while let Some(next_selection) = selections.peek() {
 8574                let next_rows = next_selection.spanned_rows(false, &display_map);
 8575                if next_rows.start <= rows.end {
 8576                    rows.end = next_rows.end;
 8577                    selections.next().unwrap();
 8578                } else {
 8579                    break;
 8580                }
 8581            }
 8582
 8583            let buffer = &display_map.buffer_snapshot;
 8584            let mut edit_start = Point::new(rows.start.0, 0).to_offset(buffer);
 8585            let edit_end;
 8586            let cursor_buffer_row;
 8587            if buffer.max_point().row >= rows.end.0 {
 8588                // If there's a line after the range, delete the \n from the end of the row range
 8589                // and position the cursor on the next line.
 8590                edit_end = Point::new(rows.end.0, 0).to_offset(buffer);
 8591                cursor_buffer_row = rows.end;
 8592            } else {
 8593                // If there isn't a line after the range, delete the \n from the line before the
 8594                // start of the row range and position the cursor there.
 8595                edit_start = edit_start.saturating_sub(1);
 8596                edit_end = buffer.len();
 8597                cursor_buffer_row = rows.start.previous_row();
 8598            }
 8599
 8600            let mut cursor = Point::new(cursor_buffer_row.0, 0).to_display_point(&display_map);
 8601            *cursor.column_mut() =
 8602                cmp::min(goal_display_column, display_map.line_len(cursor.row()));
 8603
 8604            new_cursors.push((
 8605                selection.id,
 8606                buffer.anchor_after(cursor.to_point(&display_map)),
 8607            ));
 8608            edit_ranges.push(edit_start..edit_end);
 8609        }
 8610
 8611        self.transact(window, cx, |this, window, cx| {
 8612            let buffer = this.buffer.update(cx, |buffer, cx| {
 8613                let empty_str: Arc<str> = Arc::default();
 8614                buffer.edit(
 8615                    edit_ranges
 8616                        .into_iter()
 8617                        .map(|range| (range, empty_str.clone())),
 8618                    None,
 8619                    cx,
 8620                );
 8621                buffer.snapshot(cx)
 8622            });
 8623            let new_selections = new_cursors
 8624                .into_iter()
 8625                .map(|(id, cursor)| {
 8626                    let cursor = cursor.to_point(&buffer);
 8627                    Selection {
 8628                        id,
 8629                        start: cursor,
 8630                        end: cursor,
 8631                        reversed: false,
 8632                        goal: SelectionGoal::None,
 8633                    }
 8634                })
 8635                .collect();
 8636
 8637            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8638                s.select(new_selections);
 8639            });
 8640        });
 8641    }
 8642
 8643    pub fn join_lines_impl(
 8644        &mut self,
 8645        insert_whitespace: bool,
 8646        window: &mut Window,
 8647        cx: &mut Context<Self>,
 8648    ) {
 8649        if self.read_only(cx) {
 8650            return;
 8651        }
 8652        let mut row_ranges = Vec::<Range<MultiBufferRow>>::new();
 8653        for selection in self.selections.all::<Point>(cx) {
 8654            let start = MultiBufferRow(selection.start.row);
 8655            // Treat single line selections as if they include the next line. Otherwise this action
 8656            // would do nothing for single line selections individual cursors.
 8657            let end = if selection.start.row == selection.end.row {
 8658                MultiBufferRow(selection.start.row + 1)
 8659            } else {
 8660                MultiBufferRow(selection.end.row)
 8661            };
 8662
 8663            if let Some(last_row_range) = row_ranges.last_mut() {
 8664                if start <= last_row_range.end {
 8665                    last_row_range.end = end;
 8666                    continue;
 8667                }
 8668            }
 8669            row_ranges.push(start..end);
 8670        }
 8671
 8672        let snapshot = self.buffer.read(cx).snapshot(cx);
 8673        let mut cursor_positions = Vec::new();
 8674        for row_range in &row_ranges {
 8675            let anchor = snapshot.anchor_before(Point::new(
 8676                row_range.end.previous_row().0,
 8677                snapshot.line_len(row_range.end.previous_row()),
 8678            ));
 8679            cursor_positions.push(anchor..anchor);
 8680        }
 8681
 8682        self.transact(window, cx, |this, window, cx| {
 8683            for row_range in row_ranges.into_iter().rev() {
 8684                for row in row_range.iter_rows().rev() {
 8685                    let end_of_line = Point::new(row.0, snapshot.line_len(row));
 8686                    let next_line_row = row.next_row();
 8687                    let indent = snapshot.indent_size_for_line(next_line_row);
 8688                    let start_of_next_line = Point::new(next_line_row.0, indent.len);
 8689
 8690                    let replace =
 8691                        if snapshot.line_len(next_line_row) > indent.len && insert_whitespace {
 8692                            " "
 8693                        } else {
 8694                            ""
 8695                        };
 8696
 8697                    this.buffer.update(cx, |buffer, cx| {
 8698                        buffer.edit([(end_of_line..start_of_next_line, replace)], None, cx)
 8699                    });
 8700                }
 8701            }
 8702
 8703            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8704                s.select_anchor_ranges(cursor_positions)
 8705            });
 8706        });
 8707    }
 8708
 8709    pub fn join_lines(&mut self, _: &JoinLines, window: &mut Window, cx: &mut Context<Self>) {
 8710        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
 8711        self.join_lines_impl(true, window, cx);
 8712    }
 8713
 8714    pub fn sort_lines_case_sensitive(
 8715        &mut self,
 8716        _: &SortLinesCaseSensitive,
 8717        window: &mut Window,
 8718        cx: &mut Context<Self>,
 8719    ) {
 8720        self.manipulate_lines(window, cx, |lines| lines.sort())
 8721    }
 8722
 8723    pub fn sort_lines_case_insensitive(
 8724        &mut self,
 8725        _: &SortLinesCaseInsensitive,
 8726        window: &mut Window,
 8727        cx: &mut Context<Self>,
 8728    ) {
 8729        self.manipulate_lines(window, cx, |lines| {
 8730            lines.sort_by_key(|line| line.to_lowercase())
 8731        })
 8732    }
 8733
 8734    pub fn unique_lines_case_insensitive(
 8735        &mut self,
 8736        _: &UniqueLinesCaseInsensitive,
 8737        window: &mut Window,
 8738        cx: &mut Context<Self>,
 8739    ) {
 8740        self.manipulate_lines(window, cx, |lines| {
 8741            let mut seen = HashSet::default();
 8742            lines.retain(|line| seen.insert(line.to_lowercase()));
 8743        })
 8744    }
 8745
 8746    pub fn unique_lines_case_sensitive(
 8747        &mut self,
 8748        _: &UniqueLinesCaseSensitive,
 8749        window: &mut Window,
 8750        cx: &mut Context<Self>,
 8751    ) {
 8752        self.manipulate_lines(window, cx, |lines| {
 8753            let mut seen = HashSet::default();
 8754            lines.retain(|line| seen.insert(*line));
 8755        })
 8756    }
 8757
 8758    pub fn reload_file(&mut self, _: &ReloadFile, window: &mut Window, cx: &mut Context<Self>) {
 8759        let Some(project) = self.project.clone() else {
 8760            return;
 8761        };
 8762        self.reload(project, window, cx)
 8763            .detach_and_notify_err(window, cx);
 8764    }
 8765
 8766    pub fn restore_file(
 8767        &mut self,
 8768        _: &::git::RestoreFile,
 8769        window: &mut Window,
 8770        cx: &mut Context<Self>,
 8771    ) {
 8772        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
 8773        let mut buffer_ids = HashSet::default();
 8774        let snapshot = self.buffer().read(cx).snapshot(cx);
 8775        for selection in self.selections.all::<usize>(cx) {
 8776            buffer_ids.extend(snapshot.buffer_ids_for_range(selection.range()))
 8777        }
 8778
 8779        let buffer = self.buffer().read(cx);
 8780        let ranges = buffer_ids
 8781            .into_iter()
 8782            .flat_map(|buffer_id| buffer.excerpt_ranges_for_buffer(buffer_id, cx))
 8783            .collect::<Vec<_>>();
 8784
 8785        self.restore_hunks_in_ranges(ranges, window, cx);
 8786    }
 8787
 8788    pub fn git_restore(&mut self, _: &Restore, window: &mut Window, cx: &mut Context<Self>) {
 8789        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
 8790        let selections = self
 8791            .selections
 8792            .all(cx)
 8793            .into_iter()
 8794            .map(|s| s.range())
 8795            .collect();
 8796        self.restore_hunks_in_ranges(selections, window, cx);
 8797    }
 8798
 8799    pub fn restore_hunks_in_ranges(
 8800        &mut self,
 8801        ranges: Vec<Range<Point>>,
 8802        window: &mut Window,
 8803        cx: &mut Context<Editor>,
 8804    ) {
 8805        let mut revert_changes = HashMap::default();
 8806        let chunk_by = self
 8807            .snapshot(window, cx)
 8808            .hunks_for_ranges(ranges)
 8809            .into_iter()
 8810            .chunk_by(|hunk| hunk.buffer_id);
 8811        for (buffer_id, hunks) in &chunk_by {
 8812            let hunks = hunks.collect::<Vec<_>>();
 8813            for hunk in &hunks {
 8814                self.prepare_restore_change(&mut revert_changes, hunk, cx);
 8815            }
 8816            self.do_stage_or_unstage(false, buffer_id, hunks.into_iter(), cx);
 8817        }
 8818        drop(chunk_by);
 8819        if !revert_changes.is_empty() {
 8820            self.transact(window, cx, |editor, window, cx| {
 8821                editor.restore(revert_changes, window, cx);
 8822            });
 8823        }
 8824    }
 8825
 8826    pub fn open_active_item_in_terminal(
 8827        &mut self,
 8828        _: &OpenInTerminal,
 8829        window: &mut Window,
 8830        cx: &mut Context<Self>,
 8831    ) {
 8832        if let Some(working_directory) = self.active_excerpt(cx).and_then(|(_, buffer, _)| {
 8833            let project_path = buffer.read(cx).project_path(cx)?;
 8834            let project = self.project.as_ref()?.read(cx);
 8835            let entry = project.entry_for_path(&project_path, cx)?;
 8836            let parent = match &entry.canonical_path {
 8837                Some(canonical_path) => canonical_path.to_path_buf(),
 8838                None => project.absolute_path(&project_path, cx)?,
 8839            }
 8840            .parent()?
 8841            .to_path_buf();
 8842            Some(parent)
 8843        }) {
 8844            window.dispatch_action(OpenTerminal { working_directory }.boxed_clone(), cx);
 8845        }
 8846    }
 8847
 8848    fn set_breakpoint_context_menu(
 8849        &mut self,
 8850        display_row: DisplayRow,
 8851        position: Option<Anchor>,
 8852        clicked_point: gpui::Point<Pixels>,
 8853        window: &mut Window,
 8854        cx: &mut Context<Self>,
 8855    ) {
 8856        if !cx.has_flag::<Debugger>() {
 8857            return;
 8858        }
 8859        let source = self
 8860            .buffer
 8861            .read(cx)
 8862            .snapshot(cx)
 8863            .anchor_before(Point::new(display_row.0, 0u32));
 8864
 8865        let context_menu = self.breakpoint_context_menu(position.unwrap_or(source), window, cx);
 8866
 8867        self.mouse_context_menu = MouseContextMenu::pinned_to_editor(
 8868            self,
 8869            source,
 8870            clicked_point,
 8871            None,
 8872            context_menu,
 8873            window,
 8874            cx,
 8875        );
 8876    }
 8877
 8878    fn add_edit_breakpoint_block(
 8879        &mut self,
 8880        anchor: Anchor,
 8881        breakpoint: &Breakpoint,
 8882        edit_action: BreakpointPromptEditAction,
 8883        window: &mut Window,
 8884        cx: &mut Context<Self>,
 8885    ) {
 8886        let weak_editor = cx.weak_entity();
 8887        let bp_prompt = cx.new(|cx| {
 8888            BreakpointPromptEditor::new(
 8889                weak_editor,
 8890                anchor,
 8891                breakpoint.clone(),
 8892                edit_action,
 8893                window,
 8894                cx,
 8895            )
 8896        });
 8897
 8898        let height = bp_prompt.update(cx, |this, cx| {
 8899            this.prompt
 8900                .update(cx, |prompt, cx| prompt.max_point(cx).row().0 + 1 + 2)
 8901        });
 8902        let cloned_prompt = bp_prompt.clone();
 8903        let blocks = vec![BlockProperties {
 8904            style: BlockStyle::Sticky,
 8905            placement: BlockPlacement::Above(anchor),
 8906            height: Some(height),
 8907            render: Arc::new(move |cx| {
 8908                *cloned_prompt.read(cx).gutter_dimensions.lock() = *cx.gutter_dimensions;
 8909                cloned_prompt.clone().into_any_element()
 8910            }),
 8911            priority: 0,
 8912        }];
 8913
 8914        let focus_handle = bp_prompt.focus_handle(cx);
 8915        window.focus(&focus_handle);
 8916
 8917        let block_ids = self.insert_blocks(blocks, None, cx);
 8918        bp_prompt.update(cx, |prompt, _| {
 8919            prompt.add_block_ids(block_ids);
 8920        });
 8921    }
 8922
 8923    pub(crate) fn breakpoint_at_row(
 8924        &self,
 8925        row: u32,
 8926        window: &mut Window,
 8927        cx: &mut Context<Self>,
 8928    ) -> Option<(Anchor, Breakpoint)> {
 8929        let snapshot = self.snapshot(window, cx);
 8930        let breakpoint_position = snapshot.buffer_snapshot.anchor_before(Point::new(row, 0));
 8931
 8932        self.breakpoint_at_anchor(breakpoint_position, &snapshot, cx)
 8933    }
 8934
 8935    pub(crate) fn breakpoint_at_anchor(
 8936        &self,
 8937        breakpoint_position: Anchor,
 8938        snapshot: &EditorSnapshot,
 8939        cx: &mut Context<Self>,
 8940    ) -> Option<(Anchor, Breakpoint)> {
 8941        let project = self.project.clone()?;
 8942
 8943        let buffer_id = breakpoint_position.buffer_id.or_else(|| {
 8944            snapshot
 8945                .buffer_snapshot
 8946                .buffer_id_for_excerpt(breakpoint_position.excerpt_id)
 8947        })?;
 8948
 8949        let enclosing_excerpt = breakpoint_position.excerpt_id;
 8950        let buffer = project.read_with(cx, |project, cx| project.buffer_for_id(buffer_id, cx))?;
 8951        let buffer_snapshot = buffer.read(cx).snapshot();
 8952
 8953        let row = buffer_snapshot
 8954            .summary_for_anchor::<text::PointUtf16>(&breakpoint_position.text_anchor)
 8955            .row;
 8956
 8957        let line_len = snapshot.buffer_snapshot.line_len(MultiBufferRow(row));
 8958        let anchor_end = snapshot
 8959            .buffer_snapshot
 8960            .anchor_after(Point::new(row, line_len));
 8961
 8962        let bp = self
 8963            .breakpoint_store
 8964            .as_ref()?
 8965            .read_with(cx, |breakpoint_store, cx| {
 8966                breakpoint_store
 8967                    .breakpoints(
 8968                        &buffer,
 8969                        Some(breakpoint_position.text_anchor..anchor_end.text_anchor),
 8970                        &buffer_snapshot,
 8971                        cx,
 8972                    )
 8973                    .next()
 8974                    .and_then(|(anchor, bp)| {
 8975                        let breakpoint_row = buffer_snapshot
 8976                            .summary_for_anchor::<text::PointUtf16>(anchor)
 8977                            .row;
 8978
 8979                        if breakpoint_row == row {
 8980                            snapshot
 8981                                .buffer_snapshot
 8982                                .anchor_in_excerpt(enclosing_excerpt, *anchor)
 8983                                .map(|anchor| (anchor, bp.clone()))
 8984                        } else {
 8985                            None
 8986                        }
 8987                    })
 8988            });
 8989        bp
 8990    }
 8991
 8992    pub fn edit_log_breakpoint(
 8993        &mut self,
 8994        _: &EditLogBreakpoint,
 8995        window: &mut Window,
 8996        cx: &mut Context<Self>,
 8997    ) {
 8998        for (anchor, breakpoint) in self.breakpoints_at_cursors(window, cx) {
 8999            let breakpoint = breakpoint.unwrap_or_else(|| Breakpoint {
 9000                message: None,
 9001                state: BreakpointState::Enabled,
 9002                condition: None,
 9003                hit_condition: None,
 9004            });
 9005
 9006            self.add_edit_breakpoint_block(
 9007                anchor,
 9008                &breakpoint,
 9009                BreakpointPromptEditAction::Log,
 9010                window,
 9011                cx,
 9012            );
 9013        }
 9014    }
 9015
 9016    fn breakpoints_at_cursors(
 9017        &self,
 9018        window: &mut Window,
 9019        cx: &mut Context<Self>,
 9020    ) -> Vec<(Anchor, Option<Breakpoint>)> {
 9021        let snapshot = self.snapshot(window, cx);
 9022        let cursors = self
 9023            .selections
 9024            .disjoint_anchors()
 9025            .into_iter()
 9026            .map(|selection| {
 9027                let cursor_position: Point = selection.head().to_point(&snapshot.buffer_snapshot);
 9028
 9029                let breakpoint_position = self
 9030                    .breakpoint_at_row(cursor_position.row, window, cx)
 9031                    .map(|bp| bp.0)
 9032                    .unwrap_or_else(|| {
 9033                        snapshot
 9034                            .display_snapshot
 9035                            .buffer_snapshot
 9036                            .anchor_after(Point::new(cursor_position.row, 0))
 9037                    });
 9038
 9039                let breakpoint = self
 9040                    .breakpoint_at_anchor(breakpoint_position, &snapshot, cx)
 9041                    .map(|(anchor, breakpoint)| (anchor, Some(breakpoint)));
 9042
 9043                breakpoint.unwrap_or_else(|| (breakpoint_position, None))
 9044            })
 9045            // 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.
 9046            .collect::<HashMap<Anchor, _>>();
 9047
 9048        cursors.into_iter().collect()
 9049    }
 9050
 9051    pub fn enable_breakpoint(
 9052        &mut self,
 9053        _: &crate::actions::EnableBreakpoint,
 9054        window: &mut Window,
 9055        cx: &mut Context<Self>,
 9056    ) {
 9057        for (anchor, breakpoint) in self.breakpoints_at_cursors(window, cx) {
 9058            let Some(breakpoint) = breakpoint.filter(|breakpoint| breakpoint.is_disabled()) else {
 9059                continue;
 9060            };
 9061            self.edit_breakpoint_at_anchor(
 9062                anchor,
 9063                breakpoint,
 9064                BreakpointEditAction::InvertState,
 9065                cx,
 9066            );
 9067        }
 9068    }
 9069
 9070    pub fn disable_breakpoint(
 9071        &mut self,
 9072        _: &crate::actions::DisableBreakpoint,
 9073        window: &mut Window,
 9074        cx: &mut Context<Self>,
 9075    ) {
 9076        for (anchor, breakpoint) in self.breakpoints_at_cursors(window, cx) {
 9077            let Some(breakpoint) = breakpoint.filter(|breakpoint| breakpoint.is_enabled()) else {
 9078                continue;
 9079            };
 9080            self.edit_breakpoint_at_anchor(
 9081                anchor,
 9082                breakpoint,
 9083                BreakpointEditAction::InvertState,
 9084                cx,
 9085            );
 9086        }
 9087    }
 9088
 9089    pub fn toggle_breakpoint(
 9090        &mut self,
 9091        _: &crate::actions::ToggleBreakpoint,
 9092        window: &mut Window,
 9093        cx: &mut Context<Self>,
 9094    ) {
 9095        for (anchor, breakpoint) in self.breakpoints_at_cursors(window, cx) {
 9096            if let Some(breakpoint) = breakpoint {
 9097                self.edit_breakpoint_at_anchor(
 9098                    anchor,
 9099                    breakpoint,
 9100                    BreakpointEditAction::Toggle,
 9101                    cx,
 9102                );
 9103            } else {
 9104                self.edit_breakpoint_at_anchor(
 9105                    anchor,
 9106                    Breakpoint::new_standard(),
 9107                    BreakpointEditAction::Toggle,
 9108                    cx,
 9109                );
 9110            }
 9111        }
 9112    }
 9113
 9114    pub fn edit_breakpoint_at_anchor(
 9115        &mut self,
 9116        breakpoint_position: Anchor,
 9117        breakpoint: Breakpoint,
 9118        edit_action: BreakpointEditAction,
 9119        cx: &mut Context<Self>,
 9120    ) {
 9121        let Some(breakpoint_store) = &self.breakpoint_store else {
 9122            return;
 9123        };
 9124
 9125        let Some(buffer_id) = breakpoint_position.buffer_id.or_else(|| {
 9126            if breakpoint_position == Anchor::min() {
 9127                self.buffer()
 9128                    .read(cx)
 9129                    .excerpt_buffer_ids()
 9130                    .into_iter()
 9131                    .next()
 9132            } else {
 9133                None
 9134            }
 9135        }) else {
 9136            return;
 9137        };
 9138
 9139        let Some(buffer) = self.buffer().read(cx).buffer(buffer_id) else {
 9140            return;
 9141        };
 9142
 9143        breakpoint_store.update(cx, |breakpoint_store, cx| {
 9144            breakpoint_store.toggle_breakpoint(
 9145                buffer,
 9146                (breakpoint_position.text_anchor, breakpoint),
 9147                edit_action,
 9148                cx,
 9149            );
 9150        });
 9151
 9152        cx.notify();
 9153    }
 9154
 9155    #[cfg(any(test, feature = "test-support"))]
 9156    pub fn breakpoint_store(&self) -> Option<Entity<BreakpointStore>> {
 9157        self.breakpoint_store.clone()
 9158    }
 9159
 9160    pub fn prepare_restore_change(
 9161        &self,
 9162        revert_changes: &mut HashMap<BufferId, Vec<(Range<text::Anchor>, Rope)>>,
 9163        hunk: &MultiBufferDiffHunk,
 9164        cx: &mut App,
 9165    ) -> Option<()> {
 9166        if hunk.is_created_file() {
 9167            return None;
 9168        }
 9169        let buffer = self.buffer.read(cx);
 9170        let diff = buffer.diff_for(hunk.buffer_id)?;
 9171        let buffer = buffer.buffer(hunk.buffer_id)?;
 9172        let buffer = buffer.read(cx);
 9173        let original_text = diff
 9174            .read(cx)
 9175            .base_text()
 9176            .as_rope()
 9177            .slice(hunk.diff_base_byte_range.clone());
 9178        let buffer_snapshot = buffer.snapshot();
 9179        let buffer_revert_changes = revert_changes.entry(buffer.remote_id()).or_default();
 9180        if let Err(i) = buffer_revert_changes.binary_search_by(|probe| {
 9181            probe
 9182                .0
 9183                .start
 9184                .cmp(&hunk.buffer_range.start, &buffer_snapshot)
 9185                .then(probe.0.end.cmp(&hunk.buffer_range.end, &buffer_snapshot))
 9186        }) {
 9187            buffer_revert_changes.insert(i, (hunk.buffer_range.clone(), original_text));
 9188            Some(())
 9189        } else {
 9190            None
 9191        }
 9192    }
 9193
 9194    pub fn reverse_lines(&mut self, _: &ReverseLines, window: &mut Window, cx: &mut Context<Self>) {
 9195        self.manipulate_lines(window, cx, |lines| lines.reverse())
 9196    }
 9197
 9198    pub fn shuffle_lines(&mut self, _: &ShuffleLines, window: &mut Window, cx: &mut Context<Self>) {
 9199        self.manipulate_lines(window, cx, |lines| lines.shuffle(&mut thread_rng()))
 9200    }
 9201
 9202    fn manipulate_lines<Fn>(
 9203        &mut self,
 9204        window: &mut Window,
 9205        cx: &mut Context<Self>,
 9206        mut callback: Fn,
 9207    ) where
 9208        Fn: FnMut(&mut Vec<&str>),
 9209    {
 9210        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
 9211
 9212        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 9213        let buffer = self.buffer.read(cx).snapshot(cx);
 9214
 9215        let mut edits = Vec::new();
 9216
 9217        let selections = self.selections.all::<Point>(cx);
 9218        let mut selections = selections.iter().peekable();
 9219        let mut contiguous_row_selections = Vec::new();
 9220        let mut new_selections = Vec::new();
 9221        let mut added_lines = 0;
 9222        let mut removed_lines = 0;
 9223
 9224        while let Some(selection) = selections.next() {
 9225            let (start_row, end_row) = consume_contiguous_rows(
 9226                &mut contiguous_row_selections,
 9227                selection,
 9228                &display_map,
 9229                &mut selections,
 9230            );
 9231
 9232            let start_point = Point::new(start_row.0, 0);
 9233            let end_point = Point::new(
 9234                end_row.previous_row().0,
 9235                buffer.line_len(end_row.previous_row()),
 9236            );
 9237            let text = buffer
 9238                .text_for_range(start_point..end_point)
 9239                .collect::<String>();
 9240
 9241            let mut lines = text.split('\n').collect_vec();
 9242
 9243            let lines_before = lines.len();
 9244            callback(&mut lines);
 9245            let lines_after = lines.len();
 9246
 9247            edits.push((start_point..end_point, lines.join("\n")));
 9248
 9249            // Selections must change based on added and removed line count
 9250            let start_row =
 9251                MultiBufferRow(start_point.row + added_lines as u32 - removed_lines as u32);
 9252            let end_row = MultiBufferRow(start_row.0 + lines_after.saturating_sub(1) as u32);
 9253            new_selections.push(Selection {
 9254                id: selection.id,
 9255                start: start_row,
 9256                end: end_row,
 9257                goal: SelectionGoal::None,
 9258                reversed: selection.reversed,
 9259            });
 9260
 9261            if lines_after > lines_before {
 9262                added_lines += lines_after - lines_before;
 9263            } else if lines_before > lines_after {
 9264                removed_lines += lines_before - lines_after;
 9265            }
 9266        }
 9267
 9268        self.transact(window, cx, |this, window, cx| {
 9269            let buffer = this.buffer.update(cx, |buffer, cx| {
 9270                buffer.edit(edits, None, cx);
 9271                buffer.snapshot(cx)
 9272            });
 9273
 9274            // Recalculate offsets on newly edited buffer
 9275            let new_selections = new_selections
 9276                .iter()
 9277                .map(|s| {
 9278                    let start_point = Point::new(s.start.0, 0);
 9279                    let end_point = Point::new(s.end.0, buffer.line_len(s.end));
 9280                    Selection {
 9281                        id: s.id,
 9282                        start: buffer.point_to_offset(start_point),
 9283                        end: buffer.point_to_offset(end_point),
 9284                        goal: s.goal,
 9285                        reversed: s.reversed,
 9286                    }
 9287                })
 9288                .collect();
 9289
 9290            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9291                s.select(new_selections);
 9292            });
 9293
 9294            this.request_autoscroll(Autoscroll::fit(), cx);
 9295        });
 9296    }
 9297
 9298    pub fn toggle_case(&mut self, _: &ToggleCase, window: &mut Window, cx: &mut Context<Self>) {
 9299        self.manipulate_text(window, cx, |text| {
 9300            let has_upper_case_characters = text.chars().any(|c| c.is_uppercase());
 9301            if has_upper_case_characters {
 9302                text.to_lowercase()
 9303            } else {
 9304                text.to_uppercase()
 9305            }
 9306        })
 9307    }
 9308
 9309    pub fn convert_to_upper_case(
 9310        &mut self,
 9311        _: &ConvertToUpperCase,
 9312        window: &mut Window,
 9313        cx: &mut Context<Self>,
 9314    ) {
 9315        self.manipulate_text(window, cx, |text| text.to_uppercase())
 9316    }
 9317
 9318    pub fn convert_to_lower_case(
 9319        &mut self,
 9320        _: &ConvertToLowerCase,
 9321        window: &mut Window,
 9322        cx: &mut Context<Self>,
 9323    ) {
 9324        self.manipulate_text(window, cx, |text| text.to_lowercase())
 9325    }
 9326
 9327    pub fn convert_to_title_case(
 9328        &mut self,
 9329        _: &ConvertToTitleCase,
 9330        window: &mut Window,
 9331        cx: &mut Context<Self>,
 9332    ) {
 9333        self.manipulate_text(window, cx, |text| {
 9334            text.split('\n')
 9335                .map(|line| line.to_case(Case::Title))
 9336                .join("\n")
 9337        })
 9338    }
 9339
 9340    pub fn convert_to_snake_case(
 9341        &mut self,
 9342        _: &ConvertToSnakeCase,
 9343        window: &mut Window,
 9344        cx: &mut Context<Self>,
 9345    ) {
 9346        self.manipulate_text(window, cx, |text| text.to_case(Case::Snake))
 9347    }
 9348
 9349    pub fn convert_to_kebab_case(
 9350        &mut self,
 9351        _: &ConvertToKebabCase,
 9352        window: &mut Window,
 9353        cx: &mut Context<Self>,
 9354    ) {
 9355        self.manipulate_text(window, cx, |text| text.to_case(Case::Kebab))
 9356    }
 9357
 9358    pub fn convert_to_upper_camel_case(
 9359        &mut self,
 9360        _: &ConvertToUpperCamelCase,
 9361        window: &mut Window,
 9362        cx: &mut Context<Self>,
 9363    ) {
 9364        self.manipulate_text(window, cx, |text| {
 9365            text.split('\n')
 9366                .map(|line| line.to_case(Case::UpperCamel))
 9367                .join("\n")
 9368        })
 9369    }
 9370
 9371    pub fn convert_to_lower_camel_case(
 9372        &mut self,
 9373        _: &ConvertToLowerCamelCase,
 9374        window: &mut Window,
 9375        cx: &mut Context<Self>,
 9376    ) {
 9377        self.manipulate_text(window, cx, |text| text.to_case(Case::Camel))
 9378    }
 9379
 9380    pub fn convert_to_opposite_case(
 9381        &mut self,
 9382        _: &ConvertToOppositeCase,
 9383        window: &mut Window,
 9384        cx: &mut Context<Self>,
 9385    ) {
 9386        self.manipulate_text(window, cx, |text| {
 9387            text.chars()
 9388                .fold(String::with_capacity(text.len()), |mut t, c| {
 9389                    if c.is_uppercase() {
 9390                        t.extend(c.to_lowercase());
 9391                    } else {
 9392                        t.extend(c.to_uppercase());
 9393                    }
 9394                    t
 9395                })
 9396        })
 9397    }
 9398
 9399    pub fn convert_to_rot13(
 9400        &mut self,
 9401        _: &ConvertToRot13,
 9402        window: &mut Window,
 9403        cx: &mut Context<Self>,
 9404    ) {
 9405        self.manipulate_text(window, cx, |text| {
 9406            text.chars()
 9407                .map(|c| match c {
 9408                    'A'..='M' | 'a'..='m' => ((c as u8) + 13) as char,
 9409                    'N'..='Z' | 'n'..='z' => ((c as u8) - 13) as char,
 9410                    _ => c,
 9411                })
 9412                .collect()
 9413        })
 9414    }
 9415
 9416    pub fn convert_to_rot47(
 9417        &mut self,
 9418        _: &ConvertToRot47,
 9419        window: &mut Window,
 9420        cx: &mut Context<Self>,
 9421    ) {
 9422        self.manipulate_text(window, cx, |text| {
 9423            text.chars()
 9424                .map(|c| {
 9425                    let code_point = c as u32;
 9426                    if code_point >= 33 && code_point <= 126 {
 9427                        return char::from_u32(33 + ((code_point + 14) % 94)).unwrap();
 9428                    }
 9429                    c
 9430                })
 9431                .collect()
 9432        })
 9433    }
 9434
 9435    fn manipulate_text<Fn>(&mut self, window: &mut Window, cx: &mut Context<Self>, mut callback: Fn)
 9436    where
 9437        Fn: FnMut(&str) -> String,
 9438    {
 9439        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 9440        let buffer = self.buffer.read(cx).snapshot(cx);
 9441
 9442        let mut new_selections = Vec::new();
 9443        let mut edits = Vec::new();
 9444        let mut selection_adjustment = 0i32;
 9445
 9446        for selection in self.selections.all::<usize>(cx) {
 9447            let selection_is_empty = selection.is_empty();
 9448
 9449            let (start, end) = if selection_is_empty {
 9450                let word_range = movement::surrounding_word(
 9451                    &display_map,
 9452                    selection.start.to_display_point(&display_map),
 9453                );
 9454                let start = word_range.start.to_offset(&display_map, Bias::Left);
 9455                let end = word_range.end.to_offset(&display_map, Bias::Left);
 9456                (start, end)
 9457            } else {
 9458                (selection.start, selection.end)
 9459            };
 9460
 9461            let text = buffer.text_for_range(start..end).collect::<String>();
 9462            let old_length = text.len() as i32;
 9463            let text = callback(&text);
 9464
 9465            new_selections.push(Selection {
 9466                start: (start as i32 - selection_adjustment) as usize,
 9467                end: ((start + text.len()) as i32 - selection_adjustment) as usize,
 9468                goal: SelectionGoal::None,
 9469                ..selection
 9470            });
 9471
 9472            selection_adjustment += old_length - text.len() as i32;
 9473
 9474            edits.push((start..end, text));
 9475        }
 9476
 9477        self.transact(window, cx, |this, window, cx| {
 9478            this.buffer.update(cx, |buffer, cx| {
 9479                buffer.edit(edits, None, cx);
 9480            });
 9481
 9482            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9483                s.select(new_selections);
 9484            });
 9485
 9486            this.request_autoscroll(Autoscroll::fit(), cx);
 9487        });
 9488    }
 9489
 9490    pub fn duplicate(
 9491        &mut self,
 9492        upwards: bool,
 9493        whole_lines: bool,
 9494        window: &mut Window,
 9495        cx: &mut Context<Self>,
 9496    ) {
 9497        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
 9498
 9499        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 9500        let buffer = &display_map.buffer_snapshot;
 9501        let selections = self.selections.all::<Point>(cx);
 9502
 9503        let mut edits = Vec::new();
 9504        let mut selections_iter = selections.iter().peekable();
 9505        while let Some(selection) = selections_iter.next() {
 9506            let mut rows = selection.spanned_rows(false, &display_map);
 9507            // duplicate line-wise
 9508            if whole_lines || selection.start == selection.end {
 9509                // Avoid duplicating the same lines twice.
 9510                while let Some(next_selection) = selections_iter.peek() {
 9511                    let next_rows = next_selection.spanned_rows(false, &display_map);
 9512                    if next_rows.start < rows.end {
 9513                        rows.end = next_rows.end;
 9514                        selections_iter.next().unwrap();
 9515                    } else {
 9516                        break;
 9517                    }
 9518                }
 9519
 9520                // Copy the text from the selected row region and splice it either at the start
 9521                // or end of the region.
 9522                let start = Point::new(rows.start.0, 0);
 9523                let end = Point::new(
 9524                    rows.end.previous_row().0,
 9525                    buffer.line_len(rows.end.previous_row()),
 9526                );
 9527                let text = buffer
 9528                    .text_for_range(start..end)
 9529                    .chain(Some("\n"))
 9530                    .collect::<String>();
 9531                let insert_location = if upwards {
 9532                    Point::new(rows.end.0, 0)
 9533                } else {
 9534                    start
 9535                };
 9536                edits.push((insert_location..insert_location, text));
 9537            } else {
 9538                // duplicate character-wise
 9539                let start = selection.start;
 9540                let end = selection.end;
 9541                let text = buffer.text_for_range(start..end).collect::<String>();
 9542                edits.push((selection.end..selection.end, text));
 9543            }
 9544        }
 9545
 9546        self.transact(window, cx, |this, _, cx| {
 9547            this.buffer.update(cx, |buffer, cx| {
 9548                buffer.edit(edits, None, cx);
 9549            });
 9550
 9551            this.request_autoscroll(Autoscroll::fit(), cx);
 9552        });
 9553    }
 9554
 9555    pub fn duplicate_line_up(
 9556        &mut self,
 9557        _: &DuplicateLineUp,
 9558        window: &mut Window,
 9559        cx: &mut Context<Self>,
 9560    ) {
 9561        self.duplicate(true, true, window, cx);
 9562    }
 9563
 9564    pub fn duplicate_line_down(
 9565        &mut self,
 9566        _: &DuplicateLineDown,
 9567        window: &mut Window,
 9568        cx: &mut Context<Self>,
 9569    ) {
 9570        self.duplicate(false, true, window, cx);
 9571    }
 9572
 9573    pub fn duplicate_selection(
 9574        &mut self,
 9575        _: &DuplicateSelection,
 9576        window: &mut Window,
 9577        cx: &mut Context<Self>,
 9578    ) {
 9579        self.duplicate(false, false, window, cx);
 9580    }
 9581
 9582    pub fn move_line_up(&mut self, _: &MoveLineUp, window: &mut Window, cx: &mut Context<Self>) {
 9583        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
 9584
 9585        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 9586        let buffer = self.buffer.read(cx).snapshot(cx);
 9587
 9588        let mut edits = Vec::new();
 9589        let mut unfold_ranges = Vec::new();
 9590        let mut refold_creases = Vec::new();
 9591
 9592        let selections = self.selections.all::<Point>(cx);
 9593        let mut selections = selections.iter().peekable();
 9594        let mut contiguous_row_selections = Vec::new();
 9595        let mut new_selections = Vec::new();
 9596
 9597        while let Some(selection) = selections.next() {
 9598            // Find all the selections that span a contiguous row range
 9599            let (start_row, end_row) = consume_contiguous_rows(
 9600                &mut contiguous_row_selections,
 9601                selection,
 9602                &display_map,
 9603                &mut selections,
 9604            );
 9605
 9606            // Move the text spanned by the row range to be before the line preceding the row range
 9607            if start_row.0 > 0 {
 9608                let range_to_move = Point::new(
 9609                    start_row.previous_row().0,
 9610                    buffer.line_len(start_row.previous_row()),
 9611                )
 9612                    ..Point::new(
 9613                        end_row.previous_row().0,
 9614                        buffer.line_len(end_row.previous_row()),
 9615                    );
 9616                let insertion_point = display_map
 9617                    .prev_line_boundary(Point::new(start_row.previous_row().0, 0))
 9618                    .0;
 9619
 9620                // Don't move lines across excerpts
 9621                if buffer
 9622                    .excerpt_containing(insertion_point..range_to_move.end)
 9623                    .is_some()
 9624                {
 9625                    let text = buffer
 9626                        .text_for_range(range_to_move.clone())
 9627                        .flat_map(|s| s.chars())
 9628                        .skip(1)
 9629                        .chain(['\n'])
 9630                        .collect::<String>();
 9631
 9632                    edits.push((
 9633                        buffer.anchor_after(range_to_move.start)
 9634                            ..buffer.anchor_before(range_to_move.end),
 9635                        String::new(),
 9636                    ));
 9637                    let insertion_anchor = buffer.anchor_after(insertion_point);
 9638                    edits.push((insertion_anchor..insertion_anchor, text));
 9639
 9640                    let row_delta = range_to_move.start.row - insertion_point.row + 1;
 9641
 9642                    // Move selections up
 9643                    new_selections.extend(contiguous_row_selections.drain(..).map(
 9644                        |mut selection| {
 9645                            selection.start.row -= row_delta;
 9646                            selection.end.row -= row_delta;
 9647                            selection
 9648                        },
 9649                    ));
 9650
 9651                    // Move folds up
 9652                    unfold_ranges.push(range_to_move.clone());
 9653                    for fold in display_map.folds_in_range(
 9654                        buffer.anchor_before(range_to_move.start)
 9655                            ..buffer.anchor_after(range_to_move.end),
 9656                    ) {
 9657                        let mut start = fold.range.start.to_point(&buffer);
 9658                        let mut end = fold.range.end.to_point(&buffer);
 9659                        start.row -= row_delta;
 9660                        end.row -= row_delta;
 9661                        refold_creases.push(Crease::simple(start..end, fold.placeholder.clone()));
 9662                    }
 9663                }
 9664            }
 9665
 9666            // If we didn't move line(s), preserve the existing selections
 9667            new_selections.append(&mut contiguous_row_selections);
 9668        }
 9669
 9670        self.transact(window, cx, |this, window, cx| {
 9671            this.unfold_ranges(&unfold_ranges, true, true, cx);
 9672            this.buffer.update(cx, |buffer, cx| {
 9673                for (range, text) in edits {
 9674                    buffer.edit([(range, text)], None, cx);
 9675                }
 9676            });
 9677            this.fold_creases(refold_creases, true, window, cx);
 9678            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9679                s.select(new_selections);
 9680            })
 9681        });
 9682    }
 9683
 9684    pub fn move_line_down(
 9685        &mut self,
 9686        _: &MoveLineDown,
 9687        window: &mut Window,
 9688        cx: &mut Context<Self>,
 9689    ) {
 9690        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
 9691
 9692        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 9693        let buffer = self.buffer.read(cx).snapshot(cx);
 9694
 9695        let mut edits = Vec::new();
 9696        let mut unfold_ranges = Vec::new();
 9697        let mut refold_creases = Vec::new();
 9698
 9699        let selections = self.selections.all::<Point>(cx);
 9700        let mut selections = selections.iter().peekable();
 9701        let mut contiguous_row_selections = Vec::new();
 9702        let mut new_selections = Vec::new();
 9703
 9704        while let Some(selection) = selections.next() {
 9705            // Find all the selections that span a contiguous row range
 9706            let (start_row, end_row) = consume_contiguous_rows(
 9707                &mut contiguous_row_selections,
 9708                selection,
 9709                &display_map,
 9710                &mut selections,
 9711            );
 9712
 9713            // Move the text spanned by the row range to be after the last line of the row range
 9714            if end_row.0 <= buffer.max_point().row {
 9715                let range_to_move =
 9716                    MultiBufferPoint::new(start_row.0, 0)..MultiBufferPoint::new(end_row.0, 0);
 9717                let insertion_point = display_map
 9718                    .next_line_boundary(MultiBufferPoint::new(end_row.0, 0))
 9719                    .0;
 9720
 9721                // Don't move lines across excerpt boundaries
 9722                if buffer
 9723                    .excerpt_containing(range_to_move.start..insertion_point)
 9724                    .is_some()
 9725                {
 9726                    let mut text = String::from("\n");
 9727                    text.extend(buffer.text_for_range(range_to_move.clone()));
 9728                    text.pop(); // Drop trailing newline
 9729                    edits.push((
 9730                        buffer.anchor_after(range_to_move.start)
 9731                            ..buffer.anchor_before(range_to_move.end),
 9732                        String::new(),
 9733                    ));
 9734                    let insertion_anchor = buffer.anchor_after(insertion_point);
 9735                    edits.push((insertion_anchor..insertion_anchor, text));
 9736
 9737                    let row_delta = insertion_point.row - range_to_move.end.row + 1;
 9738
 9739                    // Move selections down
 9740                    new_selections.extend(contiguous_row_selections.drain(..).map(
 9741                        |mut selection| {
 9742                            selection.start.row += row_delta;
 9743                            selection.end.row += row_delta;
 9744                            selection
 9745                        },
 9746                    ));
 9747
 9748                    // Move folds down
 9749                    unfold_ranges.push(range_to_move.clone());
 9750                    for fold in display_map.folds_in_range(
 9751                        buffer.anchor_before(range_to_move.start)
 9752                            ..buffer.anchor_after(range_to_move.end),
 9753                    ) {
 9754                        let mut start = fold.range.start.to_point(&buffer);
 9755                        let mut end = fold.range.end.to_point(&buffer);
 9756                        start.row += row_delta;
 9757                        end.row += row_delta;
 9758                        refold_creases.push(Crease::simple(start..end, fold.placeholder.clone()));
 9759                    }
 9760                }
 9761            }
 9762
 9763            // If we didn't move line(s), preserve the existing selections
 9764            new_selections.append(&mut contiguous_row_selections);
 9765        }
 9766
 9767        self.transact(window, cx, |this, window, cx| {
 9768            this.unfold_ranges(&unfold_ranges, true, true, cx);
 9769            this.buffer.update(cx, |buffer, cx| {
 9770                for (range, text) in edits {
 9771                    buffer.edit([(range, text)], None, cx);
 9772                }
 9773            });
 9774            this.fold_creases(refold_creases, true, window, cx);
 9775            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9776                s.select(new_selections)
 9777            });
 9778        });
 9779    }
 9780
 9781    pub fn transpose(&mut self, _: &Transpose, window: &mut Window, cx: &mut Context<Self>) {
 9782        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
 9783        let text_layout_details = &self.text_layout_details(window);
 9784        self.transact(window, cx, |this, window, cx| {
 9785            let edits = this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9786                let mut edits: Vec<(Range<usize>, String)> = Default::default();
 9787                s.move_with(|display_map, selection| {
 9788                    if !selection.is_empty() {
 9789                        return;
 9790                    }
 9791
 9792                    let mut head = selection.head();
 9793                    let mut transpose_offset = head.to_offset(display_map, Bias::Right);
 9794                    if head.column() == display_map.line_len(head.row()) {
 9795                        transpose_offset = display_map
 9796                            .buffer_snapshot
 9797                            .clip_offset(transpose_offset.saturating_sub(1), Bias::Left);
 9798                    }
 9799
 9800                    if transpose_offset == 0 {
 9801                        return;
 9802                    }
 9803
 9804                    *head.column_mut() += 1;
 9805                    head = display_map.clip_point(head, Bias::Right);
 9806                    let goal = SelectionGoal::HorizontalPosition(
 9807                        display_map
 9808                            .x_for_display_point(head, text_layout_details)
 9809                            .into(),
 9810                    );
 9811                    selection.collapse_to(head, goal);
 9812
 9813                    let transpose_start = display_map
 9814                        .buffer_snapshot
 9815                        .clip_offset(transpose_offset.saturating_sub(1), Bias::Left);
 9816                    if edits.last().map_or(true, |e| e.0.end <= transpose_start) {
 9817                        let transpose_end = display_map
 9818                            .buffer_snapshot
 9819                            .clip_offset(transpose_offset + 1, Bias::Right);
 9820                        if let Some(ch) =
 9821                            display_map.buffer_snapshot.chars_at(transpose_start).next()
 9822                        {
 9823                            edits.push((transpose_start..transpose_offset, String::new()));
 9824                            edits.push((transpose_end..transpose_end, ch.to_string()));
 9825                        }
 9826                    }
 9827                });
 9828                edits
 9829            });
 9830            this.buffer
 9831                .update(cx, |buffer, cx| buffer.edit(edits, None, cx));
 9832            let selections = this.selections.all::<usize>(cx);
 9833            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9834                s.select(selections);
 9835            });
 9836        });
 9837    }
 9838
 9839    pub fn rewrap(&mut self, _: &Rewrap, _: &mut Window, cx: &mut Context<Self>) {
 9840        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
 9841        self.rewrap_impl(RewrapOptions::default(), cx)
 9842    }
 9843
 9844    pub fn rewrap_impl(&mut self, options: RewrapOptions, cx: &mut Context<Self>) {
 9845        let buffer = self.buffer.read(cx).snapshot(cx);
 9846        let selections = self.selections.all::<Point>(cx);
 9847        let mut selections = selections.iter().peekable();
 9848
 9849        let mut edits = Vec::new();
 9850        let mut rewrapped_row_ranges = Vec::<RangeInclusive<u32>>::new();
 9851
 9852        while let Some(selection) = selections.next() {
 9853            let mut start_row = selection.start.row;
 9854            let mut end_row = selection.end.row;
 9855
 9856            // Skip selections that overlap with a range that has already been rewrapped.
 9857            let selection_range = start_row..end_row;
 9858            if rewrapped_row_ranges
 9859                .iter()
 9860                .any(|range| range.overlaps(&selection_range))
 9861            {
 9862                continue;
 9863            }
 9864
 9865            let tab_size = buffer.language_settings_at(selection.head(), cx).tab_size;
 9866
 9867            // Since not all lines in the selection may be at the same indent
 9868            // level, choose the indent size that is the most common between all
 9869            // of the lines.
 9870            //
 9871            // If there is a tie, we use the deepest indent.
 9872            let (indent_size, indent_end) = {
 9873                let mut indent_size_occurrences = HashMap::default();
 9874                let mut rows_by_indent_size = HashMap::<IndentSize, Vec<u32>>::default();
 9875
 9876                for row in start_row..=end_row {
 9877                    let indent = buffer.indent_size_for_line(MultiBufferRow(row));
 9878                    rows_by_indent_size.entry(indent).or_default().push(row);
 9879                    *indent_size_occurrences.entry(indent).or_insert(0) += 1;
 9880                }
 9881
 9882                let indent_size = indent_size_occurrences
 9883                    .into_iter()
 9884                    .max_by_key(|(indent, count)| (*count, indent.len_with_expanded_tabs(tab_size)))
 9885                    .map(|(indent, _)| indent)
 9886                    .unwrap_or_default();
 9887                let row = rows_by_indent_size[&indent_size][0];
 9888                let indent_end = Point::new(row, indent_size.len);
 9889
 9890                (indent_size, indent_end)
 9891            };
 9892
 9893            let mut line_prefix = indent_size.chars().collect::<String>();
 9894
 9895            let mut inside_comment = false;
 9896            if let Some(comment_prefix) =
 9897                buffer
 9898                    .language_scope_at(selection.head())
 9899                    .and_then(|language| {
 9900                        language
 9901                            .line_comment_prefixes()
 9902                            .iter()
 9903                            .find(|prefix| buffer.contains_str_at(indent_end, prefix))
 9904                            .cloned()
 9905                    })
 9906            {
 9907                line_prefix.push_str(&comment_prefix);
 9908                inside_comment = true;
 9909            }
 9910
 9911            let language_settings = buffer.language_settings_at(selection.head(), cx);
 9912            let allow_rewrap_based_on_language = match language_settings.allow_rewrap {
 9913                RewrapBehavior::InComments => inside_comment,
 9914                RewrapBehavior::InSelections => !selection.is_empty(),
 9915                RewrapBehavior::Anywhere => true,
 9916            };
 9917
 9918            let should_rewrap = options.override_language_settings
 9919                || allow_rewrap_based_on_language
 9920                || self.hard_wrap.is_some();
 9921            if !should_rewrap {
 9922                continue;
 9923            }
 9924
 9925            if selection.is_empty() {
 9926                'expand_upwards: while start_row > 0 {
 9927                    let prev_row = start_row - 1;
 9928                    if buffer.contains_str_at(Point::new(prev_row, 0), &line_prefix)
 9929                        && buffer.line_len(MultiBufferRow(prev_row)) as usize > line_prefix.len()
 9930                    {
 9931                        start_row = prev_row;
 9932                    } else {
 9933                        break 'expand_upwards;
 9934                    }
 9935                }
 9936
 9937                'expand_downwards: while end_row < buffer.max_point().row {
 9938                    let next_row = end_row + 1;
 9939                    if buffer.contains_str_at(Point::new(next_row, 0), &line_prefix)
 9940                        && buffer.line_len(MultiBufferRow(next_row)) as usize > line_prefix.len()
 9941                    {
 9942                        end_row = next_row;
 9943                    } else {
 9944                        break 'expand_downwards;
 9945                    }
 9946                }
 9947            }
 9948
 9949            let start = Point::new(start_row, 0);
 9950            let start_offset = start.to_offset(&buffer);
 9951            let end = Point::new(end_row, buffer.line_len(MultiBufferRow(end_row)));
 9952            let selection_text = buffer.text_for_range(start..end).collect::<String>();
 9953            let Some(lines_without_prefixes) = selection_text
 9954                .lines()
 9955                .map(|line| {
 9956                    line.strip_prefix(&line_prefix)
 9957                        .or_else(|| line.trim_start().strip_prefix(&line_prefix.trim_start()))
 9958                        .ok_or_else(|| {
 9959                            anyhow!("line did not start with prefix {line_prefix:?}: {line:?}")
 9960                        })
 9961                })
 9962                .collect::<Result<Vec<_>, _>>()
 9963                .log_err()
 9964            else {
 9965                continue;
 9966            };
 9967
 9968            let wrap_column = self.hard_wrap.unwrap_or_else(|| {
 9969                buffer
 9970                    .language_settings_at(Point::new(start_row, 0), cx)
 9971                    .preferred_line_length as usize
 9972            });
 9973            let wrapped_text = wrap_with_prefix(
 9974                line_prefix,
 9975                lines_without_prefixes.join("\n"),
 9976                wrap_column,
 9977                tab_size,
 9978                options.preserve_existing_whitespace,
 9979            );
 9980
 9981            // TODO: should always use char-based diff while still supporting cursor behavior that
 9982            // matches vim.
 9983            let mut diff_options = DiffOptions::default();
 9984            if options.override_language_settings {
 9985                diff_options.max_word_diff_len = 0;
 9986                diff_options.max_word_diff_line_count = 0;
 9987            } else {
 9988                diff_options.max_word_diff_len = usize::MAX;
 9989                diff_options.max_word_diff_line_count = usize::MAX;
 9990            }
 9991
 9992            for (old_range, new_text) in
 9993                text_diff_with_options(&selection_text, &wrapped_text, diff_options)
 9994            {
 9995                let edit_start = buffer.anchor_after(start_offset + old_range.start);
 9996                let edit_end = buffer.anchor_after(start_offset + old_range.end);
 9997                edits.push((edit_start..edit_end, new_text));
 9998            }
 9999
10000            rewrapped_row_ranges.push(start_row..=end_row);
10001        }
10002
10003        self.buffer
10004            .update(cx, |buffer, cx| buffer.edit(edits, None, cx));
10005    }
10006
10007    pub fn cut_common(&mut self, window: &mut Window, cx: &mut Context<Self>) -> ClipboardItem {
10008        let mut text = String::new();
10009        let buffer = self.buffer.read(cx).snapshot(cx);
10010        let mut selections = self.selections.all::<Point>(cx);
10011        let mut clipboard_selections = Vec::with_capacity(selections.len());
10012        {
10013            let max_point = buffer.max_point();
10014            let mut is_first = true;
10015            for selection in &mut selections {
10016                let is_entire_line = selection.is_empty() || self.selections.line_mode;
10017                if is_entire_line {
10018                    selection.start = Point::new(selection.start.row, 0);
10019                    if !selection.is_empty() && selection.end.column == 0 {
10020                        selection.end = cmp::min(max_point, selection.end);
10021                    } else {
10022                        selection.end = cmp::min(max_point, Point::new(selection.end.row + 1, 0));
10023                    }
10024                    selection.goal = SelectionGoal::None;
10025                }
10026                if is_first {
10027                    is_first = false;
10028                } else {
10029                    text += "\n";
10030                }
10031                let mut len = 0;
10032                for chunk in buffer.text_for_range(selection.start..selection.end) {
10033                    text.push_str(chunk);
10034                    len += chunk.len();
10035                }
10036                clipboard_selections.push(ClipboardSelection {
10037                    len,
10038                    is_entire_line,
10039                    first_line_indent: buffer
10040                        .indent_size_for_line(MultiBufferRow(selection.start.row))
10041                        .len,
10042                });
10043            }
10044        }
10045
10046        self.transact(window, cx, |this, window, cx| {
10047            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10048                s.select(selections);
10049            });
10050            this.insert("", window, cx);
10051        });
10052        ClipboardItem::new_string_with_json_metadata(text, clipboard_selections)
10053    }
10054
10055    pub fn cut(&mut self, _: &Cut, window: &mut Window, cx: &mut Context<Self>) {
10056        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
10057        let item = self.cut_common(window, cx);
10058        cx.write_to_clipboard(item);
10059    }
10060
10061    pub fn kill_ring_cut(&mut self, _: &KillRingCut, window: &mut Window, cx: &mut Context<Self>) {
10062        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
10063        self.change_selections(None, window, cx, |s| {
10064            s.move_with(|snapshot, sel| {
10065                if sel.is_empty() {
10066                    sel.end = DisplayPoint::new(sel.end.row(), snapshot.line_len(sel.end.row()))
10067                }
10068            });
10069        });
10070        let item = self.cut_common(window, cx);
10071        cx.set_global(KillRing(item))
10072    }
10073
10074    pub fn kill_ring_yank(
10075        &mut self,
10076        _: &KillRingYank,
10077        window: &mut Window,
10078        cx: &mut Context<Self>,
10079    ) {
10080        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
10081        let (text, metadata) = if let Some(KillRing(item)) = cx.try_global() {
10082            if let Some(ClipboardEntry::String(kill_ring)) = item.entries().first() {
10083                (kill_ring.text().to_string(), kill_ring.metadata_json())
10084            } else {
10085                return;
10086            }
10087        } else {
10088            return;
10089        };
10090        self.do_paste(&text, metadata, false, window, cx);
10091    }
10092
10093    pub fn copy_and_trim(&mut self, _: &CopyAndTrim, _: &mut Window, cx: &mut Context<Self>) {
10094        self.do_copy(true, cx);
10095    }
10096
10097    pub fn copy(&mut self, _: &Copy, _: &mut Window, cx: &mut Context<Self>) {
10098        self.do_copy(false, cx);
10099    }
10100
10101    fn do_copy(&self, strip_leading_indents: bool, cx: &mut Context<Self>) {
10102        let selections = self.selections.all::<Point>(cx);
10103        let buffer = self.buffer.read(cx).read(cx);
10104        let mut text = String::new();
10105
10106        let mut clipboard_selections = Vec::with_capacity(selections.len());
10107        {
10108            let max_point = buffer.max_point();
10109            let mut is_first = true;
10110            for selection in &selections {
10111                let mut start = selection.start;
10112                let mut end = selection.end;
10113                let is_entire_line = selection.is_empty() || self.selections.line_mode;
10114                if is_entire_line {
10115                    start = Point::new(start.row, 0);
10116                    end = cmp::min(max_point, Point::new(end.row + 1, 0));
10117                }
10118
10119                let mut trimmed_selections = Vec::new();
10120                if strip_leading_indents && end.row.saturating_sub(start.row) > 0 {
10121                    let row = MultiBufferRow(start.row);
10122                    let first_indent = buffer.indent_size_for_line(row);
10123                    if first_indent.len == 0 || start.column > first_indent.len {
10124                        trimmed_selections.push(start..end);
10125                    } else {
10126                        trimmed_selections.push(
10127                            Point::new(row.0, first_indent.len)
10128                                ..Point::new(row.0, buffer.line_len(row)),
10129                        );
10130                        for row in start.row + 1..=end.row {
10131                            let row_indent_size = buffer.indent_size_for_line(MultiBufferRow(row));
10132                            if row_indent_size.len >= first_indent.len {
10133                                trimmed_selections.push(
10134                                    Point::new(row, first_indent.len)
10135                                        ..Point::new(row, buffer.line_len(MultiBufferRow(row))),
10136                                );
10137                            } else {
10138                                trimmed_selections.clear();
10139                                trimmed_selections.push(start..end);
10140                                break;
10141                            }
10142                        }
10143                    }
10144                } else {
10145                    trimmed_selections.push(start..end);
10146                }
10147
10148                for trimmed_range in trimmed_selections {
10149                    if is_first {
10150                        is_first = false;
10151                    } else {
10152                        text += "\n";
10153                    }
10154                    let mut len = 0;
10155                    for chunk in buffer.text_for_range(trimmed_range.start..trimmed_range.end) {
10156                        text.push_str(chunk);
10157                        len += chunk.len();
10158                    }
10159                    clipboard_selections.push(ClipboardSelection {
10160                        len,
10161                        is_entire_line,
10162                        first_line_indent: buffer
10163                            .indent_size_for_line(MultiBufferRow(trimmed_range.start.row))
10164                            .len,
10165                    });
10166                }
10167            }
10168        }
10169
10170        cx.write_to_clipboard(ClipboardItem::new_string_with_json_metadata(
10171            text,
10172            clipboard_selections,
10173        ));
10174    }
10175
10176    pub fn do_paste(
10177        &mut self,
10178        text: &String,
10179        clipboard_selections: Option<Vec<ClipboardSelection>>,
10180        handle_entire_lines: bool,
10181        window: &mut Window,
10182        cx: &mut Context<Self>,
10183    ) {
10184        if self.read_only(cx) {
10185            return;
10186        }
10187
10188        let clipboard_text = Cow::Borrowed(text);
10189
10190        self.transact(window, cx, |this, window, cx| {
10191            if let Some(mut clipboard_selections) = clipboard_selections {
10192                let old_selections = this.selections.all::<usize>(cx);
10193                let all_selections_were_entire_line =
10194                    clipboard_selections.iter().all(|s| s.is_entire_line);
10195                let first_selection_indent_column =
10196                    clipboard_selections.first().map(|s| s.first_line_indent);
10197                if clipboard_selections.len() != old_selections.len() {
10198                    clipboard_selections.drain(..);
10199                }
10200                let cursor_offset = this.selections.last::<usize>(cx).head();
10201                let mut auto_indent_on_paste = true;
10202
10203                this.buffer.update(cx, |buffer, cx| {
10204                    let snapshot = buffer.read(cx);
10205                    auto_indent_on_paste = snapshot
10206                        .language_settings_at(cursor_offset, cx)
10207                        .auto_indent_on_paste;
10208
10209                    let mut start_offset = 0;
10210                    let mut edits = Vec::new();
10211                    let mut original_indent_columns = Vec::new();
10212                    for (ix, selection) in old_selections.iter().enumerate() {
10213                        let to_insert;
10214                        let entire_line;
10215                        let original_indent_column;
10216                        if let Some(clipboard_selection) = clipboard_selections.get(ix) {
10217                            let end_offset = start_offset + clipboard_selection.len;
10218                            to_insert = &clipboard_text[start_offset..end_offset];
10219                            entire_line = clipboard_selection.is_entire_line;
10220                            start_offset = end_offset + 1;
10221                            original_indent_column = Some(clipboard_selection.first_line_indent);
10222                        } else {
10223                            to_insert = clipboard_text.as_str();
10224                            entire_line = all_selections_were_entire_line;
10225                            original_indent_column = first_selection_indent_column
10226                        }
10227
10228                        // If the corresponding selection was empty when this slice of the
10229                        // clipboard text was written, then the entire line containing the
10230                        // selection was copied. If this selection is also currently empty,
10231                        // then paste the line before the current line of the buffer.
10232                        let range = if selection.is_empty() && handle_entire_lines && entire_line {
10233                            let column = selection.start.to_point(&snapshot).column as usize;
10234                            let line_start = selection.start - column;
10235                            line_start..line_start
10236                        } else {
10237                            selection.range()
10238                        };
10239
10240                        edits.push((range, to_insert));
10241                        original_indent_columns.push(original_indent_column);
10242                    }
10243                    drop(snapshot);
10244
10245                    buffer.edit(
10246                        edits,
10247                        if auto_indent_on_paste {
10248                            Some(AutoindentMode::Block {
10249                                original_indent_columns,
10250                            })
10251                        } else {
10252                            None
10253                        },
10254                        cx,
10255                    );
10256                });
10257
10258                let selections = this.selections.all::<usize>(cx);
10259                this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10260                    s.select(selections)
10261                });
10262            } else {
10263                this.insert(&clipboard_text, window, cx);
10264            }
10265        });
10266    }
10267
10268    pub fn paste(&mut self, _: &Paste, window: &mut Window, cx: &mut Context<Self>) {
10269        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
10270        if let Some(item) = cx.read_from_clipboard() {
10271            let entries = item.entries();
10272
10273            match entries.first() {
10274                // For now, we only support applying metadata if there's one string. In the future, we can incorporate all the selections
10275                // of all the pasted entries.
10276                Some(ClipboardEntry::String(clipboard_string)) if entries.len() == 1 => self
10277                    .do_paste(
10278                        clipboard_string.text(),
10279                        clipboard_string.metadata_json::<Vec<ClipboardSelection>>(),
10280                        true,
10281                        window,
10282                        cx,
10283                    ),
10284                _ => self.do_paste(&item.text().unwrap_or_default(), None, true, window, cx),
10285            }
10286        }
10287    }
10288
10289    pub fn undo(&mut self, _: &Undo, window: &mut Window, cx: &mut Context<Self>) {
10290        if self.read_only(cx) {
10291            return;
10292        }
10293
10294        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
10295
10296        if let Some(transaction_id) = self.buffer.update(cx, |buffer, cx| buffer.undo(cx)) {
10297            if let Some((selections, _)) =
10298                self.selection_history.transaction(transaction_id).cloned()
10299            {
10300                self.change_selections(None, window, cx, |s| {
10301                    s.select_anchors(selections.to_vec());
10302                });
10303            } else {
10304                log::error!(
10305                    "No entry in selection_history found for undo. \
10306                     This may correspond to a bug where undo does not update the selection. \
10307                     If this is occurring, please add details to \
10308                     https://github.com/zed-industries/zed/issues/22692"
10309                );
10310            }
10311            self.request_autoscroll(Autoscroll::fit(), cx);
10312            self.unmark_text(window, cx);
10313            self.refresh_inline_completion(true, false, window, cx);
10314            cx.emit(EditorEvent::Edited { transaction_id });
10315            cx.emit(EditorEvent::TransactionUndone { transaction_id });
10316        }
10317    }
10318
10319    pub fn redo(&mut self, _: &Redo, window: &mut Window, cx: &mut Context<Self>) {
10320        if self.read_only(cx) {
10321            return;
10322        }
10323
10324        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
10325
10326        if let Some(transaction_id) = self.buffer.update(cx, |buffer, cx| buffer.redo(cx)) {
10327            if let Some((_, Some(selections))) =
10328                self.selection_history.transaction(transaction_id).cloned()
10329            {
10330                self.change_selections(None, window, cx, |s| {
10331                    s.select_anchors(selections.to_vec());
10332                });
10333            } else {
10334                log::error!(
10335                    "No entry in selection_history found for redo. \
10336                     This may correspond to a bug where undo does not update the selection. \
10337                     If this is occurring, please add details to \
10338                     https://github.com/zed-industries/zed/issues/22692"
10339                );
10340            }
10341            self.request_autoscroll(Autoscroll::fit(), cx);
10342            self.unmark_text(window, cx);
10343            self.refresh_inline_completion(true, false, window, cx);
10344            cx.emit(EditorEvent::Edited { transaction_id });
10345        }
10346    }
10347
10348    pub fn finalize_last_transaction(&mut self, cx: &mut Context<Self>) {
10349        self.buffer
10350            .update(cx, |buffer, cx| buffer.finalize_last_transaction(cx));
10351    }
10352
10353    pub fn group_until_transaction(&mut self, tx_id: TransactionId, cx: &mut Context<Self>) {
10354        self.buffer
10355            .update(cx, |buffer, cx| buffer.group_until_transaction(tx_id, cx));
10356    }
10357
10358    pub fn move_left(&mut self, _: &MoveLeft, window: &mut Window, cx: &mut Context<Self>) {
10359        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
10360        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10361            s.move_with(|map, selection| {
10362                let cursor = if selection.is_empty() {
10363                    movement::left(map, selection.start)
10364                } else {
10365                    selection.start
10366                };
10367                selection.collapse_to(cursor, SelectionGoal::None);
10368            });
10369        })
10370    }
10371
10372    pub fn select_left(&mut self, _: &SelectLeft, window: &mut Window, cx: &mut Context<Self>) {
10373        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
10374        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10375            s.move_heads_with(|map, head, _| (movement::left(map, head), SelectionGoal::None));
10376        })
10377    }
10378
10379    pub fn move_right(&mut self, _: &MoveRight, window: &mut Window, cx: &mut Context<Self>) {
10380        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
10381        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10382            s.move_with(|map, selection| {
10383                let cursor = if selection.is_empty() {
10384                    movement::right(map, selection.end)
10385                } else {
10386                    selection.end
10387                };
10388                selection.collapse_to(cursor, SelectionGoal::None)
10389            });
10390        })
10391    }
10392
10393    pub fn select_right(&mut self, _: &SelectRight, window: &mut Window, cx: &mut Context<Self>) {
10394        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
10395        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10396            s.move_heads_with(|map, head, _| (movement::right(map, head), SelectionGoal::None));
10397        })
10398    }
10399
10400    pub fn move_up(&mut self, _: &MoveUp, window: &mut Window, cx: &mut Context<Self>) {
10401        if self.take_rename(true, window, cx).is_some() {
10402            return;
10403        }
10404
10405        if matches!(self.mode, EditorMode::SingleLine { .. }) {
10406            cx.propagate();
10407            return;
10408        }
10409
10410        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
10411
10412        let text_layout_details = &self.text_layout_details(window);
10413        let selection_count = self.selections.count();
10414        let first_selection = self.selections.first_anchor();
10415
10416        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10417            s.move_with(|map, selection| {
10418                if !selection.is_empty() {
10419                    selection.goal = SelectionGoal::None;
10420                }
10421                let (cursor, goal) = movement::up(
10422                    map,
10423                    selection.start,
10424                    selection.goal,
10425                    false,
10426                    text_layout_details,
10427                );
10428                selection.collapse_to(cursor, goal);
10429            });
10430        });
10431
10432        if selection_count == 1 && first_selection.range() == self.selections.first_anchor().range()
10433        {
10434            cx.propagate();
10435        }
10436    }
10437
10438    pub fn move_up_by_lines(
10439        &mut self,
10440        action: &MoveUpByLines,
10441        window: &mut Window,
10442        cx: &mut Context<Self>,
10443    ) {
10444        if self.take_rename(true, window, cx).is_some() {
10445            return;
10446        }
10447
10448        if matches!(self.mode, EditorMode::SingleLine { .. }) {
10449            cx.propagate();
10450            return;
10451        }
10452
10453        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
10454
10455        let text_layout_details = &self.text_layout_details(window);
10456
10457        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10458            s.move_with(|map, selection| {
10459                if !selection.is_empty() {
10460                    selection.goal = SelectionGoal::None;
10461                }
10462                let (cursor, goal) = movement::up_by_rows(
10463                    map,
10464                    selection.start,
10465                    action.lines,
10466                    selection.goal,
10467                    false,
10468                    text_layout_details,
10469                );
10470                selection.collapse_to(cursor, goal);
10471            });
10472        })
10473    }
10474
10475    pub fn move_down_by_lines(
10476        &mut self,
10477        action: &MoveDownByLines,
10478        window: &mut Window,
10479        cx: &mut Context<Self>,
10480    ) {
10481        if self.take_rename(true, window, cx).is_some() {
10482            return;
10483        }
10484
10485        if matches!(self.mode, EditorMode::SingleLine { .. }) {
10486            cx.propagate();
10487            return;
10488        }
10489
10490        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
10491
10492        let text_layout_details = &self.text_layout_details(window);
10493
10494        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10495            s.move_with(|map, selection| {
10496                if !selection.is_empty() {
10497                    selection.goal = SelectionGoal::None;
10498                }
10499                let (cursor, goal) = movement::down_by_rows(
10500                    map,
10501                    selection.start,
10502                    action.lines,
10503                    selection.goal,
10504                    false,
10505                    text_layout_details,
10506                );
10507                selection.collapse_to(cursor, goal);
10508            });
10509        })
10510    }
10511
10512    pub fn select_down_by_lines(
10513        &mut self,
10514        action: &SelectDownByLines,
10515        window: &mut Window,
10516        cx: &mut Context<Self>,
10517    ) {
10518        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
10519        let text_layout_details = &self.text_layout_details(window);
10520        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10521            s.move_heads_with(|map, head, goal| {
10522                movement::down_by_rows(map, head, action.lines, goal, false, text_layout_details)
10523            })
10524        })
10525    }
10526
10527    pub fn select_up_by_lines(
10528        &mut self,
10529        action: &SelectUpByLines,
10530        window: &mut Window,
10531        cx: &mut Context<Self>,
10532    ) {
10533        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
10534        let text_layout_details = &self.text_layout_details(window);
10535        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10536            s.move_heads_with(|map, head, goal| {
10537                movement::up_by_rows(map, head, action.lines, goal, false, text_layout_details)
10538            })
10539        })
10540    }
10541
10542    pub fn select_page_up(
10543        &mut self,
10544        _: &SelectPageUp,
10545        window: &mut Window,
10546        cx: &mut Context<Self>,
10547    ) {
10548        let Some(row_count) = self.visible_row_count() else {
10549            return;
10550        };
10551
10552        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
10553
10554        let text_layout_details = &self.text_layout_details(window);
10555
10556        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10557            s.move_heads_with(|map, head, goal| {
10558                movement::up_by_rows(map, head, row_count, goal, false, text_layout_details)
10559            })
10560        })
10561    }
10562
10563    pub fn move_page_up(
10564        &mut self,
10565        action: &MovePageUp,
10566        window: &mut Window,
10567        cx: &mut Context<Self>,
10568    ) {
10569        if self.take_rename(true, window, cx).is_some() {
10570            return;
10571        }
10572
10573        if self
10574            .context_menu
10575            .borrow_mut()
10576            .as_mut()
10577            .map(|menu| menu.select_first(self.completion_provider.as_deref(), cx))
10578            .unwrap_or(false)
10579        {
10580            return;
10581        }
10582
10583        if matches!(self.mode, EditorMode::SingleLine { .. }) {
10584            cx.propagate();
10585            return;
10586        }
10587
10588        let Some(row_count) = self.visible_row_count() else {
10589            return;
10590        };
10591
10592        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
10593
10594        let autoscroll = if action.center_cursor {
10595            Autoscroll::center()
10596        } else {
10597            Autoscroll::fit()
10598        };
10599
10600        let text_layout_details = &self.text_layout_details(window);
10601
10602        self.change_selections(Some(autoscroll), window, cx, |s| {
10603            s.move_with(|map, selection| {
10604                if !selection.is_empty() {
10605                    selection.goal = SelectionGoal::None;
10606                }
10607                let (cursor, goal) = movement::up_by_rows(
10608                    map,
10609                    selection.end,
10610                    row_count,
10611                    selection.goal,
10612                    false,
10613                    text_layout_details,
10614                );
10615                selection.collapse_to(cursor, goal);
10616            });
10617        });
10618    }
10619
10620    pub fn select_up(&mut self, _: &SelectUp, window: &mut Window, cx: &mut Context<Self>) {
10621        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
10622        let text_layout_details = &self.text_layout_details(window);
10623        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10624            s.move_heads_with(|map, head, goal| {
10625                movement::up(map, head, goal, false, text_layout_details)
10626            })
10627        })
10628    }
10629
10630    pub fn move_down(&mut self, _: &MoveDown, window: &mut Window, cx: &mut Context<Self>) {
10631        self.take_rename(true, window, cx);
10632
10633        if matches!(self.mode, EditorMode::SingleLine { .. }) {
10634            cx.propagate();
10635            return;
10636        }
10637
10638        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
10639
10640        let text_layout_details = &self.text_layout_details(window);
10641        let selection_count = self.selections.count();
10642        let first_selection = self.selections.first_anchor();
10643
10644        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10645            s.move_with(|map, selection| {
10646                if !selection.is_empty() {
10647                    selection.goal = SelectionGoal::None;
10648                }
10649                let (cursor, goal) = movement::down(
10650                    map,
10651                    selection.end,
10652                    selection.goal,
10653                    false,
10654                    text_layout_details,
10655                );
10656                selection.collapse_to(cursor, goal);
10657            });
10658        });
10659
10660        if selection_count == 1 && first_selection.range() == self.selections.first_anchor().range()
10661        {
10662            cx.propagate();
10663        }
10664    }
10665
10666    pub fn select_page_down(
10667        &mut self,
10668        _: &SelectPageDown,
10669        window: &mut Window,
10670        cx: &mut Context<Self>,
10671    ) {
10672        let Some(row_count) = self.visible_row_count() else {
10673            return;
10674        };
10675
10676        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
10677
10678        let text_layout_details = &self.text_layout_details(window);
10679
10680        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10681            s.move_heads_with(|map, head, goal| {
10682                movement::down_by_rows(map, head, row_count, goal, false, text_layout_details)
10683            })
10684        })
10685    }
10686
10687    pub fn move_page_down(
10688        &mut self,
10689        action: &MovePageDown,
10690        window: &mut Window,
10691        cx: &mut Context<Self>,
10692    ) {
10693        if self.take_rename(true, window, cx).is_some() {
10694            return;
10695        }
10696
10697        if self
10698            .context_menu
10699            .borrow_mut()
10700            .as_mut()
10701            .map(|menu| menu.select_last(self.completion_provider.as_deref(), cx))
10702            .unwrap_or(false)
10703        {
10704            return;
10705        }
10706
10707        if matches!(self.mode, EditorMode::SingleLine { .. }) {
10708            cx.propagate();
10709            return;
10710        }
10711
10712        let Some(row_count) = self.visible_row_count() else {
10713            return;
10714        };
10715
10716        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
10717
10718        let autoscroll = if action.center_cursor {
10719            Autoscroll::center()
10720        } else {
10721            Autoscroll::fit()
10722        };
10723
10724        let text_layout_details = &self.text_layout_details(window);
10725        self.change_selections(Some(autoscroll), window, cx, |s| {
10726            s.move_with(|map, selection| {
10727                if !selection.is_empty() {
10728                    selection.goal = SelectionGoal::None;
10729                }
10730                let (cursor, goal) = movement::down_by_rows(
10731                    map,
10732                    selection.end,
10733                    row_count,
10734                    selection.goal,
10735                    false,
10736                    text_layout_details,
10737                );
10738                selection.collapse_to(cursor, goal);
10739            });
10740        });
10741    }
10742
10743    pub fn select_down(&mut self, _: &SelectDown, window: &mut Window, cx: &mut Context<Self>) {
10744        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
10745        let text_layout_details = &self.text_layout_details(window);
10746        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10747            s.move_heads_with(|map, head, goal| {
10748                movement::down(map, head, goal, false, text_layout_details)
10749            })
10750        });
10751    }
10752
10753    pub fn context_menu_first(
10754        &mut self,
10755        _: &ContextMenuFirst,
10756        _window: &mut Window,
10757        cx: &mut Context<Self>,
10758    ) {
10759        if let Some(context_menu) = self.context_menu.borrow_mut().as_mut() {
10760            context_menu.select_first(self.completion_provider.as_deref(), cx);
10761        }
10762    }
10763
10764    pub fn context_menu_prev(
10765        &mut self,
10766        _: &ContextMenuPrevious,
10767        _window: &mut Window,
10768        cx: &mut Context<Self>,
10769    ) {
10770        if let Some(context_menu) = self.context_menu.borrow_mut().as_mut() {
10771            context_menu.select_prev(self.completion_provider.as_deref(), cx);
10772        }
10773    }
10774
10775    pub fn context_menu_next(
10776        &mut self,
10777        _: &ContextMenuNext,
10778        _window: &mut Window,
10779        cx: &mut Context<Self>,
10780    ) {
10781        if let Some(context_menu) = self.context_menu.borrow_mut().as_mut() {
10782            context_menu.select_next(self.completion_provider.as_deref(), cx);
10783        }
10784    }
10785
10786    pub fn context_menu_last(
10787        &mut self,
10788        _: &ContextMenuLast,
10789        _window: &mut Window,
10790        cx: &mut Context<Self>,
10791    ) {
10792        if let Some(context_menu) = self.context_menu.borrow_mut().as_mut() {
10793            context_menu.select_last(self.completion_provider.as_deref(), cx);
10794        }
10795    }
10796
10797    pub fn move_to_previous_word_start(
10798        &mut self,
10799        _: &MoveToPreviousWordStart,
10800        window: &mut Window,
10801        cx: &mut Context<Self>,
10802    ) {
10803        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
10804        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10805            s.move_cursors_with(|map, head, _| {
10806                (
10807                    movement::previous_word_start(map, head),
10808                    SelectionGoal::None,
10809                )
10810            });
10811        })
10812    }
10813
10814    pub fn move_to_previous_subword_start(
10815        &mut self,
10816        _: &MoveToPreviousSubwordStart,
10817        window: &mut Window,
10818        cx: &mut Context<Self>,
10819    ) {
10820        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
10821        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10822            s.move_cursors_with(|map, head, _| {
10823                (
10824                    movement::previous_subword_start(map, head),
10825                    SelectionGoal::None,
10826                )
10827            });
10828        })
10829    }
10830
10831    pub fn select_to_previous_word_start(
10832        &mut self,
10833        _: &SelectToPreviousWordStart,
10834        window: &mut Window,
10835        cx: &mut Context<Self>,
10836    ) {
10837        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
10838        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10839            s.move_heads_with(|map, head, _| {
10840                (
10841                    movement::previous_word_start(map, head),
10842                    SelectionGoal::None,
10843                )
10844            });
10845        })
10846    }
10847
10848    pub fn select_to_previous_subword_start(
10849        &mut self,
10850        _: &SelectToPreviousSubwordStart,
10851        window: &mut Window,
10852        cx: &mut Context<Self>,
10853    ) {
10854        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
10855        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10856            s.move_heads_with(|map, head, _| {
10857                (
10858                    movement::previous_subword_start(map, head),
10859                    SelectionGoal::None,
10860                )
10861            });
10862        })
10863    }
10864
10865    pub fn delete_to_previous_word_start(
10866        &mut self,
10867        action: &DeleteToPreviousWordStart,
10868        window: &mut Window,
10869        cx: &mut Context<Self>,
10870    ) {
10871        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
10872        self.transact(window, cx, |this, window, cx| {
10873            this.select_autoclose_pair(window, cx);
10874            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10875                s.move_with(|map, selection| {
10876                    if selection.is_empty() {
10877                        let cursor = if action.ignore_newlines {
10878                            movement::previous_word_start(map, selection.head())
10879                        } else {
10880                            movement::previous_word_start_or_newline(map, selection.head())
10881                        };
10882                        selection.set_head(cursor, SelectionGoal::None);
10883                    }
10884                });
10885            });
10886            this.insert("", window, cx);
10887        });
10888    }
10889
10890    pub fn delete_to_previous_subword_start(
10891        &mut self,
10892        _: &DeleteToPreviousSubwordStart,
10893        window: &mut Window,
10894        cx: &mut Context<Self>,
10895    ) {
10896        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
10897        self.transact(window, cx, |this, window, cx| {
10898            this.select_autoclose_pair(window, cx);
10899            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10900                s.move_with(|map, selection| {
10901                    if selection.is_empty() {
10902                        let cursor = movement::previous_subword_start(map, selection.head());
10903                        selection.set_head(cursor, SelectionGoal::None);
10904                    }
10905                });
10906            });
10907            this.insert("", window, cx);
10908        });
10909    }
10910
10911    pub fn move_to_next_word_end(
10912        &mut self,
10913        _: &MoveToNextWordEnd,
10914        window: &mut Window,
10915        cx: &mut Context<Self>,
10916    ) {
10917        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
10918        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10919            s.move_cursors_with(|map, head, _| {
10920                (movement::next_word_end(map, head), SelectionGoal::None)
10921            });
10922        })
10923    }
10924
10925    pub fn move_to_next_subword_end(
10926        &mut self,
10927        _: &MoveToNextSubwordEnd,
10928        window: &mut Window,
10929        cx: &mut Context<Self>,
10930    ) {
10931        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
10932        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10933            s.move_cursors_with(|map, head, _| {
10934                (movement::next_subword_end(map, head), SelectionGoal::None)
10935            });
10936        })
10937    }
10938
10939    pub fn select_to_next_word_end(
10940        &mut self,
10941        _: &SelectToNextWordEnd,
10942        window: &mut Window,
10943        cx: &mut Context<Self>,
10944    ) {
10945        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
10946        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10947            s.move_heads_with(|map, head, _| {
10948                (movement::next_word_end(map, head), SelectionGoal::None)
10949            });
10950        })
10951    }
10952
10953    pub fn select_to_next_subword_end(
10954        &mut self,
10955        _: &SelectToNextSubwordEnd,
10956        window: &mut Window,
10957        cx: &mut Context<Self>,
10958    ) {
10959        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
10960        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10961            s.move_heads_with(|map, head, _| {
10962                (movement::next_subword_end(map, head), SelectionGoal::None)
10963            });
10964        })
10965    }
10966
10967    pub fn delete_to_next_word_end(
10968        &mut self,
10969        action: &DeleteToNextWordEnd,
10970        window: &mut Window,
10971        cx: &mut Context<Self>,
10972    ) {
10973        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
10974        self.transact(window, cx, |this, window, cx| {
10975            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10976                s.move_with(|map, selection| {
10977                    if selection.is_empty() {
10978                        let cursor = if action.ignore_newlines {
10979                            movement::next_word_end(map, selection.head())
10980                        } else {
10981                            movement::next_word_end_or_newline(map, selection.head())
10982                        };
10983                        selection.set_head(cursor, SelectionGoal::None);
10984                    }
10985                });
10986            });
10987            this.insert("", window, cx);
10988        });
10989    }
10990
10991    pub fn delete_to_next_subword_end(
10992        &mut self,
10993        _: &DeleteToNextSubwordEnd,
10994        window: &mut Window,
10995        cx: &mut Context<Self>,
10996    ) {
10997        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
10998        self.transact(window, cx, |this, window, cx| {
10999            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11000                s.move_with(|map, selection| {
11001                    if selection.is_empty() {
11002                        let cursor = movement::next_subword_end(map, selection.head());
11003                        selection.set_head(cursor, SelectionGoal::None);
11004                    }
11005                });
11006            });
11007            this.insert("", window, cx);
11008        });
11009    }
11010
11011    pub fn move_to_beginning_of_line(
11012        &mut self,
11013        action: &MoveToBeginningOfLine,
11014        window: &mut Window,
11015        cx: &mut Context<Self>,
11016    ) {
11017        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11018        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11019            s.move_cursors_with(|map, head, _| {
11020                (
11021                    movement::indented_line_beginning(
11022                        map,
11023                        head,
11024                        action.stop_at_soft_wraps,
11025                        action.stop_at_indent,
11026                    ),
11027                    SelectionGoal::None,
11028                )
11029            });
11030        })
11031    }
11032
11033    pub fn select_to_beginning_of_line(
11034        &mut self,
11035        action: &SelectToBeginningOfLine,
11036        window: &mut Window,
11037        cx: &mut Context<Self>,
11038    ) {
11039        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11040        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11041            s.move_heads_with(|map, head, _| {
11042                (
11043                    movement::indented_line_beginning(
11044                        map,
11045                        head,
11046                        action.stop_at_soft_wraps,
11047                        action.stop_at_indent,
11048                    ),
11049                    SelectionGoal::None,
11050                )
11051            });
11052        });
11053    }
11054
11055    pub fn delete_to_beginning_of_line(
11056        &mut self,
11057        action: &DeleteToBeginningOfLine,
11058        window: &mut Window,
11059        cx: &mut Context<Self>,
11060    ) {
11061        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
11062        self.transact(window, cx, |this, window, cx| {
11063            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11064                s.move_with(|_, selection| {
11065                    selection.reversed = true;
11066                });
11067            });
11068
11069            this.select_to_beginning_of_line(
11070                &SelectToBeginningOfLine {
11071                    stop_at_soft_wraps: false,
11072                    stop_at_indent: action.stop_at_indent,
11073                },
11074                window,
11075                cx,
11076            );
11077            this.backspace(&Backspace, window, cx);
11078        });
11079    }
11080
11081    pub fn move_to_end_of_line(
11082        &mut self,
11083        action: &MoveToEndOfLine,
11084        window: &mut Window,
11085        cx: &mut Context<Self>,
11086    ) {
11087        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11088        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11089            s.move_cursors_with(|map, head, _| {
11090                (
11091                    movement::line_end(map, head, action.stop_at_soft_wraps),
11092                    SelectionGoal::None,
11093                )
11094            });
11095        })
11096    }
11097
11098    pub fn select_to_end_of_line(
11099        &mut self,
11100        action: &SelectToEndOfLine,
11101        window: &mut Window,
11102        cx: &mut Context<Self>,
11103    ) {
11104        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11105        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11106            s.move_heads_with(|map, head, _| {
11107                (
11108                    movement::line_end(map, head, action.stop_at_soft_wraps),
11109                    SelectionGoal::None,
11110                )
11111            });
11112        })
11113    }
11114
11115    pub fn delete_to_end_of_line(
11116        &mut self,
11117        _: &DeleteToEndOfLine,
11118        window: &mut Window,
11119        cx: &mut Context<Self>,
11120    ) {
11121        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
11122        self.transact(window, cx, |this, window, cx| {
11123            this.select_to_end_of_line(
11124                &SelectToEndOfLine {
11125                    stop_at_soft_wraps: false,
11126                },
11127                window,
11128                cx,
11129            );
11130            this.delete(&Delete, window, cx);
11131        });
11132    }
11133
11134    pub fn cut_to_end_of_line(
11135        &mut self,
11136        _: &CutToEndOfLine,
11137        window: &mut Window,
11138        cx: &mut Context<Self>,
11139    ) {
11140        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
11141        self.transact(window, cx, |this, window, cx| {
11142            this.select_to_end_of_line(
11143                &SelectToEndOfLine {
11144                    stop_at_soft_wraps: false,
11145                },
11146                window,
11147                cx,
11148            );
11149            this.cut(&Cut, window, cx);
11150        });
11151    }
11152
11153    pub fn move_to_start_of_paragraph(
11154        &mut self,
11155        _: &MoveToStartOfParagraph,
11156        window: &mut Window,
11157        cx: &mut Context<Self>,
11158    ) {
11159        if matches!(self.mode, EditorMode::SingleLine { .. }) {
11160            cx.propagate();
11161            return;
11162        }
11163        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11164        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11165            s.move_with(|map, selection| {
11166                selection.collapse_to(
11167                    movement::start_of_paragraph(map, selection.head(), 1),
11168                    SelectionGoal::None,
11169                )
11170            });
11171        })
11172    }
11173
11174    pub fn move_to_end_of_paragraph(
11175        &mut self,
11176        _: &MoveToEndOfParagraph,
11177        window: &mut Window,
11178        cx: &mut Context<Self>,
11179    ) {
11180        if matches!(self.mode, EditorMode::SingleLine { .. }) {
11181            cx.propagate();
11182            return;
11183        }
11184        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11185        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11186            s.move_with(|map, selection| {
11187                selection.collapse_to(
11188                    movement::end_of_paragraph(map, selection.head(), 1),
11189                    SelectionGoal::None,
11190                )
11191            });
11192        })
11193    }
11194
11195    pub fn select_to_start_of_paragraph(
11196        &mut self,
11197        _: &SelectToStartOfParagraph,
11198        window: &mut Window,
11199        cx: &mut Context<Self>,
11200    ) {
11201        if matches!(self.mode, EditorMode::SingleLine { .. }) {
11202            cx.propagate();
11203            return;
11204        }
11205        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11206        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11207            s.move_heads_with(|map, head, _| {
11208                (
11209                    movement::start_of_paragraph(map, head, 1),
11210                    SelectionGoal::None,
11211                )
11212            });
11213        })
11214    }
11215
11216    pub fn select_to_end_of_paragraph(
11217        &mut self,
11218        _: &SelectToEndOfParagraph,
11219        window: &mut Window,
11220        cx: &mut Context<Self>,
11221    ) {
11222        if matches!(self.mode, EditorMode::SingleLine { .. }) {
11223            cx.propagate();
11224            return;
11225        }
11226        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11227        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11228            s.move_heads_with(|map, head, _| {
11229                (
11230                    movement::end_of_paragraph(map, head, 1),
11231                    SelectionGoal::None,
11232                )
11233            });
11234        })
11235    }
11236
11237    pub fn move_to_start_of_excerpt(
11238        &mut self,
11239        _: &MoveToStartOfExcerpt,
11240        window: &mut Window,
11241        cx: &mut Context<Self>,
11242    ) {
11243        if matches!(self.mode, EditorMode::SingleLine { .. }) {
11244            cx.propagate();
11245            return;
11246        }
11247        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11248        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11249            s.move_with(|map, selection| {
11250                selection.collapse_to(
11251                    movement::start_of_excerpt(
11252                        map,
11253                        selection.head(),
11254                        workspace::searchable::Direction::Prev,
11255                    ),
11256                    SelectionGoal::None,
11257                )
11258            });
11259        })
11260    }
11261
11262    pub fn move_to_start_of_next_excerpt(
11263        &mut self,
11264        _: &MoveToStartOfNextExcerpt,
11265        window: &mut Window,
11266        cx: &mut Context<Self>,
11267    ) {
11268        if matches!(self.mode, EditorMode::SingleLine { .. }) {
11269            cx.propagate();
11270            return;
11271        }
11272
11273        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11274            s.move_with(|map, selection| {
11275                selection.collapse_to(
11276                    movement::start_of_excerpt(
11277                        map,
11278                        selection.head(),
11279                        workspace::searchable::Direction::Next,
11280                    ),
11281                    SelectionGoal::None,
11282                )
11283            });
11284        })
11285    }
11286
11287    pub fn move_to_end_of_excerpt(
11288        &mut self,
11289        _: &MoveToEndOfExcerpt,
11290        window: &mut Window,
11291        cx: &mut Context<Self>,
11292    ) {
11293        if matches!(self.mode, EditorMode::SingleLine { .. }) {
11294            cx.propagate();
11295            return;
11296        }
11297        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11298        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11299            s.move_with(|map, selection| {
11300                selection.collapse_to(
11301                    movement::end_of_excerpt(
11302                        map,
11303                        selection.head(),
11304                        workspace::searchable::Direction::Next,
11305                    ),
11306                    SelectionGoal::None,
11307                )
11308            });
11309        })
11310    }
11311
11312    pub fn move_to_end_of_previous_excerpt(
11313        &mut self,
11314        _: &MoveToEndOfPreviousExcerpt,
11315        window: &mut Window,
11316        cx: &mut Context<Self>,
11317    ) {
11318        if matches!(self.mode, EditorMode::SingleLine { .. }) {
11319            cx.propagate();
11320            return;
11321        }
11322        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11323        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11324            s.move_with(|map, selection| {
11325                selection.collapse_to(
11326                    movement::end_of_excerpt(
11327                        map,
11328                        selection.head(),
11329                        workspace::searchable::Direction::Prev,
11330                    ),
11331                    SelectionGoal::None,
11332                )
11333            });
11334        })
11335    }
11336
11337    pub fn select_to_start_of_excerpt(
11338        &mut self,
11339        _: &SelectToStartOfExcerpt,
11340        window: &mut Window,
11341        cx: &mut Context<Self>,
11342    ) {
11343        if matches!(self.mode, EditorMode::SingleLine { .. }) {
11344            cx.propagate();
11345            return;
11346        }
11347        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11348        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11349            s.move_heads_with(|map, head, _| {
11350                (
11351                    movement::start_of_excerpt(map, head, workspace::searchable::Direction::Prev),
11352                    SelectionGoal::None,
11353                )
11354            });
11355        })
11356    }
11357
11358    pub fn select_to_start_of_next_excerpt(
11359        &mut self,
11360        _: &SelectToStartOfNextExcerpt,
11361        window: &mut Window,
11362        cx: &mut Context<Self>,
11363    ) {
11364        if matches!(self.mode, EditorMode::SingleLine { .. }) {
11365            cx.propagate();
11366            return;
11367        }
11368        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11369        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11370            s.move_heads_with(|map, head, _| {
11371                (
11372                    movement::start_of_excerpt(map, head, workspace::searchable::Direction::Next),
11373                    SelectionGoal::None,
11374                )
11375            });
11376        })
11377    }
11378
11379    pub fn select_to_end_of_excerpt(
11380        &mut self,
11381        _: &SelectToEndOfExcerpt,
11382        window: &mut Window,
11383        cx: &mut Context<Self>,
11384    ) {
11385        if matches!(self.mode, EditorMode::SingleLine { .. }) {
11386            cx.propagate();
11387            return;
11388        }
11389        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11390        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11391            s.move_heads_with(|map, head, _| {
11392                (
11393                    movement::end_of_excerpt(map, head, workspace::searchable::Direction::Next),
11394                    SelectionGoal::None,
11395                )
11396            });
11397        })
11398    }
11399
11400    pub fn select_to_end_of_previous_excerpt(
11401        &mut self,
11402        _: &SelectToEndOfPreviousExcerpt,
11403        window: &mut Window,
11404        cx: &mut Context<Self>,
11405    ) {
11406        if matches!(self.mode, EditorMode::SingleLine { .. }) {
11407            cx.propagate();
11408            return;
11409        }
11410        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11411        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11412            s.move_heads_with(|map, head, _| {
11413                (
11414                    movement::end_of_excerpt(map, head, workspace::searchable::Direction::Prev),
11415                    SelectionGoal::None,
11416                )
11417            });
11418        })
11419    }
11420
11421    pub fn move_to_beginning(
11422        &mut self,
11423        _: &MoveToBeginning,
11424        window: &mut Window,
11425        cx: &mut Context<Self>,
11426    ) {
11427        if matches!(self.mode, EditorMode::SingleLine { .. }) {
11428            cx.propagate();
11429            return;
11430        }
11431        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11432        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11433            s.select_ranges(vec![0..0]);
11434        });
11435    }
11436
11437    pub fn select_to_beginning(
11438        &mut self,
11439        _: &SelectToBeginning,
11440        window: &mut Window,
11441        cx: &mut Context<Self>,
11442    ) {
11443        let mut selection = self.selections.last::<Point>(cx);
11444        selection.set_head(Point::zero(), SelectionGoal::None);
11445        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11446        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11447            s.select(vec![selection]);
11448        });
11449    }
11450
11451    pub fn move_to_end(&mut self, _: &MoveToEnd, window: &mut Window, cx: &mut Context<Self>) {
11452        if matches!(self.mode, EditorMode::SingleLine { .. }) {
11453            cx.propagate();
11454            return;
11455        }
11456        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11457        let cursor = self.buffer.read(cx).read(cx).len();
11458        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11459            s.select_ranges(vec![cursor..cursor])
11460        });
11461    }
11462
11463    pub fn set_nav_history(&mut self, nav_history: Option<ItemNavHistory>) {
11464        self.nav_history = nav_history;
11465    }
11466
11467    pub fn nav_history(&self) -> Option<&ItemNavHistory> {
11468        self.nav_history.as_ref()
11469    }
11470
11471    pub fn create_nav_history_entry(&mut self, cx: &mut Context<Self>) {
11472        self.push_to_nav_history(self.selections.newest_anchor().head(), None, false, cx);
11473    }
11474
11475    fn push_to_nav_history(
11476        &mut self,
11477        cursor_anchor: Anchor,
11478        new_position: Option<Point>,
11479        is_deactivate: bool,
11480        cx: &mut Context<Self>,
11481    ) {
11482        if let Some(nav_history) = self.nav_history.as_mut() {
11483            let buffer = self.buffer.read(cx).read(cx);
11484            let cursor_position = cursor_anchor.to_point(&buffer);
11485            let scroll_state = self.scroll_manager.anchor();
11486            let scroll_top_row = scroll_state.top_row(&buffer);
11487            drop(buffer);
11488
11489            if let Some(new_position) = new_position {
11490                let row_delta = (new_position.row as i64 - cursor_position.row as i64).abs();
11491                if row_delta < MIN_NAVIGATION_HISTORY_ROW_DELTA {
11492                    return;
11493                }
11494            }
11495
11496            nav_history.push(
11497                Some(NavigationData {
11498                    cursor_anchor,
11499                    cursor_position,
11500                    scroll_anchor: scroll_state,
11501                    scroll_top_row,
11502                }),
11503                cx,
11504            );
11505            cx.emit(EditorEvent::PushedToNavHistory {
11506                anchor: cursor_anchor,
11507                is_deactivate,
11508            })
11509        }
11510    }
11511
11512    pub fn select_to_end(&mut self, _: &SelectToEnd, window: &mut Window, cx: &mut Context<Self>) {
11513        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11514        let buffer = self.buffer.read(cx).snapshot(cx);
11515        let mut selection = self.selections.first::<usize>(cx);
11516        selection.set_head(buffer.len(), SelectionGoal::None);
11517        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11518            s.select(vec![selection]);
11519        });
11520    }
11521
11522    pub fn select_all(&mut self, _: &SelectAll, window: &mut Window, cx: &mut Context<Self>) {
11523        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11524        let end = self.buffer.read(cx).read(cx).len();
11525        self.change_selections(None, window, cx, |s| {
11526            s.select_ranges(vec![0..end]);
11527        });
11528    }
11529
11530    pub fn select_line(&mut self, _: &SelectLine, window: &mut Window, cx: &mut Context<Self>) {
11531        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11532        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
11533        let mut selections = self.selections.all::<Point>(cx);
11534        let max_point = display_map.buffer_snapshot.max_point();
11535        for selection in &mut selections {
11536            let rows = selection.spanned_rows(true, &display_map);
11537            selection.start = Point::new(rows.start.0, 0);
11538            selection.end = cmp::min(max_point, Point::new(rows.end.0, 0));
11539            selection.reversed = false;
11540        }
11541        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11542            s.select(selections);
11543        });
11544    }
11545
11546    pub fn split_selection_into_lines(
11547        &mut self,
11548        _: &SplitSelectionIntoLines,
11549        window: &mut Window,
11550        cx: &mut Context<Self>,
11551    ) {
11552        let selections = self
11553            .selections
11554            .all::<Point>(cx)
11555            .into_iter()
11556            .map(|selection| selection.start..selection.end)
11557            .collect::<Vec<_>>();
11558        self.unfold_ranges(&selections, true, true, cx);
11559
11560        let mut new_selection_ranges = Vec::new();
11561        {
11562            let buffer = self.buffer.read(cx).read(cx);
11563            for selection in selections {
11564                for row in selection.start.row..selection.end.row {
11565                    let cursor = Point::new(row, buffer.line_len(MultiBufferRow(row)));
11566                    new_selection_ranges.push(cursor..cursor);
11567                }
11568
11569                let is_multiline_selection = selection.start.row != selection.end.row;
11570                // Don't insert last one if it's a multi-line selection ending at the start of a line,
11571                // so this action feels more ergonomic when paired with other selection operations
11572                let should_skip_last = is_multiline_selection && selection.end.column == 0;
11573                if !should_skip_last {
11574                    new_selection_ranges.push(selection.end..selection.end);
11575                }
11576            }
11577        }
11578        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11579            s.select_ranges(new_selection_ranges);
11580        });
11581    }
11582
11583    pub fn add_selection_above(
11584        &mut self,
11585        _: &AddSelectionAbove,
11586        window: &mut Window,
11587        cx: &mut Context<Self>,
11588    ) {
11589        self.add_selection(true, window, cx);
11590    }
11591
11592    pub fn add_selection_below(
11593        &mut self,
11594        _: &AddSelectionBelow,
11595        window: &mut Window,
11596        cx: &mut Context<Self>,
11597    ) {
11598        self.add_selection(false, window, cx);
11599    }
11600
11601    fn add_selection(&mut self, above: bool, window: &mut Window, cx: &mut Context<Self>) {
11602        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11603
11604        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
11605        let mut selections = self.selections.all::<Point>(cx);
11606        let text_layout_details = self.text_layout_details(window);
11607        let mut state = self.add_selections_state.take().unwrap_or_else(|| {
11608            let oldest_selection = selections.iter().min_by_key(|s| s.id).unwrap().clone();
11609            let range = oldest_selection.display_range(&display_map).sorted();
11610
11611            let start_x = display_map.x_for_display_point(range.start, &text_layout_details);
11612            let end_x = display_map.x_for_display_point(range.end, &text_layout_details);
11613            let positions = start_x.min(end_x)..start_x.max(end_x);
11614
11615            selections.clear();
11616            let mut stack = Vec::new();
11617            for row in range.start.row().0..=range.end.row().0 {
11618                if let Some(selection) = self.selections.build_columnar_selection(
11619                    &display_map,
11620                    DisplayRow(row),
11621                    &positions,
11622                    oldest_selection.reversed,
11623                    &text_layout_details,
11624                ) {
11625                    stack.push(selection.id);
11626                    selections.push(selection);
11627                }
11628            }
11629
11630            if above {
11631                stack.reverse();
11632            }
11633
11634            AddSelectionsState { above, stack }
11635        });
11636
11637        let last_added_selection = *state.stack.last().unwrap();
11638        let mut new_selections = Vec::new();
11639        if above == state.above {
11640            let end_row = if above {
11641                DisplayRow(0)
11642            } else {
11643                display_map.max_point().row()
11644            };
11645
11646            'outer: for selection in selections {
11647                if selection.id == last_added_selection {
11648                    let range = selection.display_range(&display_map).sorted();
11649                    debug_assert_eq!(range.start.row(), range.end.row());
11650                    let mut row = range.start.row();
11651                    let positions =
11652                        if let SelectionGoal::HorizontalRange { start, end } = selection.goal {
11653                            px(start)..px(end)
11654                        } else {
11655                            let start_x =
11656                                display_map.x_for_display_point(range.start, &text_layout_details);
11657                            let end_x =
11658                                display_map.x_for_display_point(range.end, &text_layout_details);
11659                            start_x.min(end_x)..start_x.max(end_x)
11660                        };
11661
11662                    while row != end_row {
11663                        if above {
11664                            row.0 -= 1;
11665                        } else {
11666                            row.0 += 1;
11667                        }
11668
11669                        if let Some(new_selection) = self.selections.build_columnar_selection(
11670                            &display_map,
11671                            row,
11672                            &positions,
11673                            selection.reversed,
11674                            &text_layout_details,
11675                        ) {
11676                            state.stack.push(new_selection.id);
11677                            if above {
11678                                new_selections.push(new_selection);
11679                                new_selections.push(selection);
11680                            } else {
11681                                new_selections.push(selection);
11682                                new_selections.push(new_selection);
11683                            }
11684
11685                            continue 'outer;
11686                        }
11687                    }
11688                }
11689
11690                new_selections.push(selection);
11691            }
11692        } else {
11693            new_selections = selections;
11694            new_selections.retain(|s| s.id != last_added_selection);
11695            state.stack.pop();
11696        }
11697
11698        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11699            s.select(new_selections);
11700        });
11701        if state.stack.len() > 1 {
11702            self.add_selections_state = Some(state);
11703        }
11704    }
11705
11706    pub fn select_next_match_internal(
11707        &mut self,
11708        display_map: &DisplaySnapshot,
11709        replace_newest: bool,
11710        autoscroll: Option<Autoscroll>,
11711        window: &mut Window,
11712        cx: &mut Context<Self>,
11713    ) -> Result<()> {
11714        fn select_next_match_ranges(
11715            this: &mut Editor,
11716            range: Range<usize>,
11717            replace_newest: bool,
11718            auto_scroll: Option<Autoscroll>,
11719            window: &mut Window,
11720            cx: &mut Context<Editor>,
11721        ) {
11722            this.unfold_ranges(&[range.clone()], false, auto_scroll.is_some(), cx);
11723            this.change_selections(auto_scroll, window, cx, |s| {
11724                if replace_newest {
11725                    s.delete(s.newest_anchor().id);
11726                }
11727                s.insert_range(range.clone());
11728            });
11729        }
11730
11731        let buffer = &display_map.buffer_snapshot;
11732        let mut selections = self.selections.all::<usize>(cx);
11733        if let Some(mut select_next_state) = self.select_next_state.take() {
11734            let query = &select_next_state.query;
11735            if !select_next_state.done {
11736                let first_selection = selections.iter().min_by_key(|s| s.id).unwrap();
11737                let last_selection = selections.iter().max_by_key(|s| s.id).unwrap();
11738                let mut next_selected_range = None;
11739
11740                let bytes_after_last_selection =
11741                    buffer.bytes_in_range(last_selection.end..buffer.len());
11742                let bytes_before_first_selection = buffer.bytes_in_range(0..first_selection.start);
11743                let query_matches = query
11744                    .stream_find_iter(bytes_after_last_selection)
11745                    .map(|result| (last_selection.end, result))
11746                    .chain(
11747                        query
11748                            .stream_find_iter(bytes_before_first_selection)
11749                            .map(|result| (0, result)),
11750                    );
11751
11752                for (start_offset, query_match) in query_matches {
11753                    let query_match = query_match.unwrap(); // can only fail due to I/O
11754                    let offset_range =
11755                        start_offset + query_match.start()..start_offset + query_match.end();
11756                    let display_range = offset_range.start.to_display_point(display_map)
11757                        ..offset_range.end.to_display_point(display_map);
11758
11759                    if !select_next_state.wordwise
11760                        || (!movement::is_inside_word(display_map, display_range.start)
11761                            && !movement::is_inside_word(display_map, display_range.end))
11762                    {
11763                        // TODO: This is n^2, because we might check all the selections
11764                        if !selections
11765                            .iter()
11766                            .any(|selection| selection.range().overlaps(&offset_range))
11767                        {
11768                            next_selected_range = Some(offset_range);
11769                            break;
11770                        }
11771                    }
11772                }
11773
11774                if let Some(next_selected_range) = next_selected_range {
11775                    select_next_match_ranges(
11776                        self,
11777                        next_selected_range,
11778                        replace_newest,
11779                        autoscroll,
11780                        window,
11781                        cx,
11782                    );
11783                } else {
11784                    select_next_state.done = true;
11785                }
11786            }
11787
11788            self.select_next_state = Some(select_next_state);
11789        } else {
11790            let mut only_carets = true;
11791            let mut same_text_selected = true;
11792            let mut selected_text = None;
11793
11794            let mut selections_iter = selections.iter().peekable();
11795            while let Some(selection) = selections_iter.next() {
11796                if selection.start != selection.end {
11797                    only_carets = false;
11798                }
11799
11800                if same_text_selected {
11801                    if selected_text.is_none() {
11802                        selected_text =
11803                            Some(buffer.text_for_range(selection.range()).collect::<String>());
11804                    }
11805
11806                    if let Some(next_selection) = selections_iter.peek() {
11807                        if next_selection.range().len() == selection.range().len() {
11808                            let next_selected_text = buffer
11809                                .text_for_range(next_selection.range())
11810                                .collect::<String>();
11811                            if Some(next_selected_text) != selected_text {
11812                                same_text_selected = false;
11813                                selected_text = None;
11814                            }
11815                        } else {
11816                            same_text_selected = false;
11817                            selected_text = None;
11818                        }
11819                    }
11820                }
11821            }
11822
11823            if only_carets {
11824                for selection in &mut selections {
11825                    let word_range = movement::surrounding_word(
11826                        display_map,
11827                        selection.start.to_display_point(display_map),
11828                    );
11829                    selection.start = word_range.start.to_offset(display_map, Bias::Left);
11830                    selection.end = word_range.end.to_offset(display_map, Bias::Left);
11831                    selection.goal = SelectionGoal::None;
11832                    selection.reversed = false;
11833                    select_next_match_ranges(
11834                        self,
11835                        selection.start..selection.end,
11836                        replace_newest,
11837                        autoscroll,
11838                        window,
11839                        cx,
11840                    );
11841                }
11842
11843                if selections.len() == 1 {
11844                    let selection = selections
11845                        .last()
11846                        .expect("ensured that there's only one selection");
11847                    let query = buffer
11848                        .text_for_range(selection.start..selection.end)
11849                        .collect::<String>();
11850                    let is_empty = query.is_empty();
11851                    let select_state = SelectNextState {
11852                        query: AhoCorasick::new(&[query])?,
11853                        wordwise: true,
11854                        done: is_empty,
11855                    };
11856                    self.select_next_state = Some(select_state);
11857                } else {
11858                    self.select_next_state = None;
11859                }
11860            } else if let Some(selected_text) = selected_text {
11861                self.select_next_state = Some(SelectNextState {
11862                    query: AhoCorasick::new(&[selected_text])?,
11863                    wordwise: false,
11864                    done: false,
11865                });
11866                self.select_next_match_internal(
11867                    display_map,
11868                    replace_newest,
11869                    autoscroll,
11870                    window,
11871                    cx,
11872                )?;
11873            }
11874        }
11875        Ok(())
11876    }
11877
11878    pub fn select_all_matches(
11879        &mut self,
11880        _action: &SelectAllMatches,
11881        window: &mut Window,
11882        cx: &mut Context<Self>,
11883    ) -> Result<()> {
11884        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11885
11886        self.push_to_selection_history();
11887        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
11888
11889        self.select_next_match_internal(&display_map, false, None, window, cx)?;
11890        let Some(select_next_state) = self.select_next_state.as_mut() else {
11891            return Ok(());
11892        };
11893        if select_next_state.done {
11894            return Ok(());
11895        }
11896
11897        let mut new_selections = Vec::new();
11898
11899        let reversed = self.selections.oldest::<usize>(cx).reversed;
11900        let buffer = &display_map.buffer_snapshot;
11901        let query_matches = select_next_state
11902            .query
11903            .stream_find_iter(buffer.bytes_in_range(0..buffer.len()));
11904
11905        for query_match in query_matches.into_iter() {
11906            let query_match = query_match.context("query match for select all action")?; // can only fail due to I/O
11907            let offset_range = if reversed {
11908                query_match.end()..query_match.start()
11909            } else {
11910                query_match.start()..query_match.end()
11911            };
11912            let display_range = offset_range.start.to_display_point(&display_map)
11913                ..offset_range.end.to_display_point(&display_map);
11914
11915            if !select_next_state.wordwise
11916                || (!movement::is_inside_word(&display_map, display_range.start)
11917                    && !movement::is_inside_word(&display_map, display_range.end))
11918            {
11919                new_selections.push(offset_range.start..offset_range.end);
11920            }
11921        }
11922
11923        select_next_state.done = true;
11924        self.unfold_ranges(&new_selections.clone(), false, false, cx);
11925        self.change_selections(None, window, cx, |selections| {
11926            selections.select_ranges(new_selections)
11927        });
11928
11929        Ok(())
11930    }
11931
11932    pub fn select_next(
11933        &mut self,
11934        action: &SelectNext,
11935        window: &mut Window,
11936        cx: &mut Context<Self>,
11937    ) -> Result<()> {
11938        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11939        self.push_to_selection_history();
11940        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
11941        self.select_next_match_internal(
11942            &display_map,
11943            action.replace_newest,
11944            Some(Autoscroll::newest()),
11945            window,
11946            cx,
11947        )?;
11948        Ok(())
11949    }
11950
11951    pub fn select_previous(
11952        &mut self,
11953        action: &SelectPrevious,
11954        window: &mut Window,
11955        cx: &mut Context<Self>,
11956    ) -> Result<()> {
11957        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11958        self.push_to_selection_history();
11959        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
11960        let buffer = &display_map.buffer_snapshot;
11961        let mut selections = self.selections.all::<usize>(cx);
11962        if let Some(mut select_prev_state) = self.select_prev_state.take() {
11963            let query = &select_prev_state.query;
11964            if !select_prev_state.done {
11965                let first_selection = selections.iter().min_by_key(|s| s.id).unwrap();
11966                let last_selection = selections.iter().max_by_key(|s| s.id).unwrap();
11967                let mut next_selected_range = None;
11968                // When we're iterating matches backwards, the oldest match will actually be the furthest one in the buffer.
11969                let bytes_before_last_selection =
11970                    buffer.reversed_bytes_in_range(0..last_selection.start);
11971                let bytes_after_first_selection =
11972                    buffer.reversed_bytes_in_range(first_selection.end..buffer.len());
11973                let query_matches = query
11974                    .stream_find_iter(bytes_before_last_selection)
11975                    .map(|result| (last_selection.start, result))
11976                    .chain(
11977                        query
11978                            .stream_find_iter(bytes_after_first_selection)
11979                            .map(|result| (buffer.len(), result)),
11980                    );
11981                for (end_offset, query_match) in query_matches {
11982                    let query_match = query_match.unwrap(); // can only fail due to I/O
11983                    let offset_range =
11984                        end_offset - query_match.end()..end_offset - query_match.start();
11985                    let display_range = offset_range.start.to_display_point(&display_map)
11986                        ..offset_range.end.to_display_point(&display_map);
11987
11988                    if !select_prev_state.wordwise
11989                        || (!movement::is_inside_word(&display_map, display_range.start)
11990                            && !movement::is_inside_word(&display_map, display_range.end))
11991                    {
11992                        next_selected_range = Some(offset_range);
11993                        break;
11994                    }
11995                }
11996
11997                if let Some(next_selected_range) = next_selected_range {
11998                    self.unfold_ranges(&[next_selected_range.clone()], false, true, cx);
11999                    self.change_selections(Some(Autoscroll::newest()), window, cx, |s| {
12000                        if action.replace_newest {
12001                            s.delete(s.newest_anchor().id);
12002                        }
12003                        s.insert_range(next_selected_range);
12004                    });
12005                } else {
12006                    select_prev_state.done = true;
12007                }
12008            }
12009
12010            self.select_prev_state = Some(select_prev_state);
12011        } else {
12012            let mut only_carets = true;
12013            let mut same_text_selected = true;
12014            let mut selected_text = None;
12015
12016            let mut selections_iter = selections.iter().peekable();
12017            while let Some(selection) = selections_iter.next() {
12018                if selection.start != selection.end {
12019                    only_carets = false;
12020                }
12021
12022                if same_text_selected {
12023                    if selected_text.is_none() {
12024                        selected_text =
12025                            Some(buffer.text_for_range(selection.range()).collect::<String>());
12026                    }
12027
12028                    if let Some(next_selection) = selections_iter.peek() {
12029                        if next_selection.range().len() == selection.range().len() {
12030                            let next_selected_text = buffer
12031                                .text_for_range(next_selection.range())
12032                                .collect::<String>();
12033                            if Some(next_selected_text) != selected_text {
12034                                same_text_selected = false;
12035                                selected_text = None;
12036                            }
12037                        } else {
12038                            same_text_selected = false;
12039                            selected_text = None;
12040                        }
12041                    }
12042                }
12043            }
12044
12045            if only_carets {
12046                for selection in &mut selections {
12047                    let word_range = movement::surrounding_word(
12048                        &display_map,
12049                        selection.start.to_display_point(&display_map),
12050                    );
12051                    selection.start = word_range.start.to_offset(&display_map, Bias::Left);
12052                    selection.end = word_range.end.to_offset(&display_map, Bias::Left);
12053                    selection.goal = SelectionGoal::None;
12054                    selection.reversed = false;
12055                }
12056                if selections.len() == 1 {
12057                    let selection = selections
12058                        .last()
12059                        .expect("ensured that there's only one selection");
12060                    let query = buffer
12061                        .text_for_range(selection.start..selection.end)
12062                        .collect::<String>();
12063                    let is_empty = query.is_empty();
12064                    let select_state = SelectNextState {
12065                        query: AhoCorasick::new(&[query.chars().rev().collect::<String>()])?,
12066                        wordwise: true,
12067                        done: is_empty,
12068                    };
12069                    self.select_prev_state = Some(select_state);
12070                } else {
12071                    self.select_prev_state = None;
12072                }
12073
12074                self.unfold_ranges(
12075                    &selections.iter().map(|s| s.range()).collect::<Vec<_>>(),
12076                    false,
12077                    true,
12078                    cx,
12079                );
12080                self.change_selections(Some(Autoscroll::newest()), window, cx, |s| {
12081                    s.select(selections);
12082                });
12083            } else if let Some(selected_text) = selected_text {
12084                self.select_prev_state = Some(SelectNextState {
12085                    query: AhoCorasick::new(&[selected_text.chars().rev().collect::<String>()])?,
12086                    wordwise: false,
12087                    done: false,
12088                });
12089                self.select_previous(action, window, cx)?;
12090            }
12091        }
12092        Ok(())
12093    }
12094
12095    pub fn find_next_match(
12096        &mut self,
12097        _: &FindNextMatch,
12098        window: &mut Window,
12099        cx: &mut Context<Self>,
12100    ) -> Result<()> {
12101        let selections = self.selections.disjoint_anchors();
12102        match selections.first() {
12103            Some(first) if selections.len() >= 2 => {
12104                self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
12105                    s.select_ranges([first.range()]);
12106                });
12107            }
12108            _ => self.select_next(
12109                &SelectNext {
12110                    replace_newest: true,
12111                },
12112                window,
12113                cx,
12114            )?,
12115        }
12116        Ok(())
12117    }
12118
12119    pub fn find_previous_match(
12120        &mut self,
12121        _: &FindPreviousMatch,
12122        window: &mut Window,
12123        cx: &mut Context<Self>,
12124    ) -> Result<()> {
12125        let selections = self.selections.disjoint_anchors();
12126        match selections.last() {
12127            Some(last) if selections.len() >= 2 => {
12128                self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
12129                    s.select_ranges([last.range()]);
12130                });
12131            }
12132            _ => self.select_previous(
12133                &SelectPrevious {
12134                    replace_newest: true,
12135                },
12136                window,
12137                cx,
12138            )?,
12139        }
12140        Ok(())
12141    }
12142
12143    pub fn toggle_comments(
12144        &mut self,
12145        action: &ToggleComments,
12146        window: &mut Window,
12147        cx: &mut Context<Self>,
12148    ) {
12149        if self.read_only(cx) {
12150            return;
12151        }
12152        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
12153        let text_layout_details = &self.text_layout_details(window);
12154        self.transact(window, cx, |this, window, cx| {
12155            let mut selections = this.selections.all::<MultiBufferPoint>(cx);
12156            let mut edits = Vec::new();
12157            let mut selection_edit_ranges = Vec::new();
12158            let mut last_toggled_row = None;
12159            let snapshot = this.buffer.read(cx).read(cx);
12160            let empty_str: Arc<str> = Arc::default();
12161            let mut suffixes_inserted = Vec::new();
12162            let ignore_indent = action.ignore_indent;
12163
12164            fn comment_prefix_range(
12165                snapshot: &MultiBufferSnapshot,
12166                row: MultiBufferRow,
12167                comment_prefix: &str,
12168                comment_prefix_whitespace: &str,
12169                ignore_indent: bool,
12170            ) -> Range<Point> {
12171                let indent_size = if ignore_indent {
12172                    0
12173                } else {
12174                    snapshot.indent_size_for_line(row).len
12175                };
12176
12177                let start = Point::new(row.0, indent_size);
12178
12179                let mut line_bytes = snapshot
12180                    .bytes_in_range(start..snapshot.max_point())
12181                    .flatten()
12182                    .copied();
12183
12184                // If this line currently begins with the line comment prefix, then record
12185                // the range containing the prefix.
12186                if line_bytes
12187                    .by_ref()
12188                    .take(comment_prefix.len())
12189                    .eq(comment_prefix.bytes())
12190                {
12191                    // Include any whitespace that matches the comment prefix.
12192                    let matching_whitespace_len = line_bytes
12193                        .zip(comment_prefix_whitespace.bytes())
12194                        .take_while(|(a, b)| a == b)
12195                        .count() as u32;
12196                    let end = Point::new(
12197                        start.row,
12198                        start.column + comment_prefix.len() as u32 + matching_whitespace_len,
12199                    );
12200                    start..end
12201                } else {
12202                    start..start
12203                }
12204            }
12205
12206            fn comment_suffix_range(
12207                snapshot: &MultiBufferSnapshot,
12208                row: MultiBufferRow,
12209                comment_suffix: &str,
12210                comment_suffix_has_leading_space: bool,
12211            ) -> Range<Point> {
12212                let end = Point::new(row.0, snapshot.line_len(row));
12213                let suffix_start_column = end.column.saturating_sub(comment_suffix.len() as u32);
12214
12215                let mut line_end_bytes = snapshot
12216                    .bytes_in_range(Point::new(end.row, suffix_start_column.saturating_sub(1))..end)
12217                    .flatten()
12218                    .copied();
12219
12220                let leading_space_len = if suffix_start_column > 0
12221                    && line_end_bytes.next() == Some(b' ')
12222                    && comment_suffix_has_leading_space
12223                {
12224                    1
12225                } else {
12226                    0
12227                };
12228
12229                // If this line currently begins with the line comment prefix, then record
12230                // the range containing the prefix.
12231                if line_end_bytes.by_ref().eq(comment_suffix.bytes()) {
12232                    let start = Point::new(end.row, suffix_start_column - leading_space_len);
12233                    start..end
12234                } else {
12235                    end..end
12236                }
12237            }
12238
12239            // TODO: Handle selections that cross excerpts
12240            for selection in &mut selections {
12241                let start_column = snapshot
12242                    .indent_size_for_line(MultiBufferRow(selection.start.row))
12243                    .len;
12244                let language = if let Some(language) =
12245                    snapshot.language_scope_at(Point::new(selection.start.row, start_column))
12246                {
12247                    language
12248                } else {
12249                    continue;
12250                };
12251
12252                selection_edit_ranges.clear();
12253
12254                // If multiple selections contain a given row, avoid processing that
12255                // row more than once.
12256                let mut start_row = MultiBufferRow(selection.start.row);
12257                if last_toggled_row == Some(start_row) {
12258                    start_row = start_row.next_row();
12259                }
12260                let end_row =
12261                    if selection.end.row > selection.start.row && selection.end.column == 0 {
12262                        MultiBufferRow(selection.end.row - 1)
12263                    } else {
12264                        MultiBufferRow(selection.end.row)
12265                    };
12266                last_toggled_row = Some(end_row);
12267
12268                if start_row > end_row {
12269                    continue;
12270                }
12271
12272                // If the language has line comments, toggle those.
12273                let mut full_comment_prefixes = language.line_comment_prefixes().to_vec();
12274
12275                // If ignore_indent is set, trim spaces from the right side of all full_comment_prefixes
12276                if ignore_indent {
12277                    full_comment_prefixes = full_comment_prefixes
12278                        .into_iter()
12279                        .map(|s| Arc::from(s.trim_end()))
12280                        .collect();
12281                }
12282
12283                if !full_comment_prefixes.is_empty() {
12284                    let first_prefix = full_comment_prefixes
12285                        .first()
12286                        .expect("prefixes is non-empty");
12287                    let prefix_trimmed_lengths = full_comment_prefixes
12288                        .iter()
12289                        .map(|p| p.trim_end_matches(' ').len())
12290                        .collect::<SmallVec<[usize; 4]>>();
12291
12292                    let mut all_selection_lines_are_comments = true;
12293
12294                    for row in start_row.0..=end_row.0 {
12295                        let row = MultiBufferRow(row);
12296                        if start_row < end_row && snapshot.is_line_blank(row) {
12297                            continue;
12298                        }
12299
12300                        let prefix_range = full_comment_prefixes
12301                            .iter()
12302                            .zip(prefix_trimmed_lengths.iter().copied())
12303                            .map(|(prefix, trimmed_prefix_len)| {
12304                                comment_prefix_range(
12305                                    snapshot.deref(),
12306                                    row,
12307                                    &prefix[..trimmed_prefix_len],
12308                                    &prefix[trimmed_prefix_len..],
12309                                    ignore_indent,
12310                                )
12311                            })
12312                            .max_by_key(|range| range.end.column - range.start.column)
12313                            .expect("prefixes is non-empty");
12314
12315                        if prefix_range.is_empty() {
12316                            all_selection_lines_are_comments = false;
12317                        }
12318
12319                        selection_edit_ranges.push(prefix_range);
12320                    }
12321
12322                    if all_selection_lines_are_comments {
12323                        edits.extend(
12324                            selection_edit_ranges
12325                                .iter()
12326                                .cloned()
12327                                .map(|range| (range, empty_str.clone())),
12328                        );
12329                    } else {
12330                        let min_column = selection_edit_ranges
12331                            .iter()
12332                            .map(|range| range.start.column)
12333                            .min()
12334                            .unwrap_or(0);
12335                        edits.extend(selection_edit_ranges.iter().map(|range| {
12336                            let position = Point::new(range.start.row, min_column);
12337                            (position..position, first_prefix.clone())
12338                        }));
12339                    }
12340                } else if let Some((full_comment_prefix, comment_suffix)) =
12341                    language.block_comment_delimiters()
12342                {
12343                    let comment_prefix = full_comment_prefix.trim_end_matches(' ');
12344                    let comment_prefix_whitespace = &full_comment_prefix[comment_prefix.len()..];
12345                    let prefix_range = comment_prefix_range(
12346                        snapshot.deref(),
12347                        start_row,
12348                        comment_prefix,
12349                        comment_prefix_whitespace,
12350                        ignore_indent,
12351                    );
12352                    let suffix_range = comment_suffix_range(
12353                        snapshot.deref(),
12354                        end_row,
12355                        comment_suffix.trim_start_matches(' '),
12356                        comment_suffix.starts_with(' '),
12357                    );
12358
12359                    if prefix_range.is_empty() || suffix_range.is_empty() {
12360                        edits.push((
12361                            prefix_range.start..prefix_range.start,
12362                            full_comment_prefix.clone(),
12363                        ));
12364                        edits.push((suffix_range.end..suffix_range.end, comment_suffix.clone()));
12365                        suffixes_inserted.push((end_row, comment_suffix.len()));
12366                    } else {
12367                        edits.push((prefix_range, empty_str.clone()));
12368                        edits.push((suffix_range, empty_str.clone()));
12369                    }
12370                } else {
12371                    continue;
12372                }
12373            }
12374
12375            drop(snapshot);
12376            this.buffer.update(cx, |buffer, cx| {
12377                buffer.edit(edits, None, cx);
12378            });
12379
12380            // Adjust selections so that they end before any comment suffixes that
12381            // were inserted.
12382            let mut suffixes_inserted = suffixes_inserted.into_iter().peekable();
12383            let mut selections = this.selections.all::<Point>(cx);
12384            let snapshot = this.buffer.read(cx).read(cx);
12385            for selection in &mut selections {
12386                while let Some((row, suffix_len)) = suffixes_inserted.peek().copied() {
12387                    match row.cmp(&MultiBufferRow(selection.end.row)) {
12388                        Ordering::Less => {
12389                            suffixes_inserted.next();
12390                            continue;
12391                        }
12392                        Ordering::Greater => break,
12393                        Ordering::Equal => {
12394                            if selection.end.column == snapshot.line_len(row) {
12395                                if selection.is_empty() {
12396                                    selection.start.column -= suffix_len as u32;
12397                                }
12398                                selection.end.column -= suffix_len as u32;
12399                            }
12400                            break;
12401                        }
12402                    }
12403                }
12404            }
12405
12406            drop(snapshot);
12407            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
12408                s.select(selections)
12409            });
12410
12411            let selections = this.selections.all::<Point>(cx);
12412            let selections_on_single_row = selections.windows(2).all(|selections| {
12413                selections[0].start.row == selections[1].start.row
12414                    && selections[0].end.row == selections[1].end.row
12415                    && selections[0].start.row == selections[0].end.row
12416            });
12417            let selections_selecting = selections
12418                .iter()
12419                .any(|selection| selection.start != selection.end);
12420            let advance_downwards = action.advance_downwards
12421                && selections_on_single_row
12422                && !selections_selecting
12423                && !matches!(this.mode, EditorMode::SingleLine { .. });
12424
12425            if advance_downwards {
12426                let snapshot = this.buffer.read(cx).snapshot(cx);
12427
12428                this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
12429                    s.move_cursors_with(|display_snapshot, display_point, _| {
12430                        let mut point = display_point.to_point(display_snapshot);
12431                        point.row += 1;
12432                        point = snapshot.clip_point(point, Bias::Left);
12433                        let display_point = point.to_display_point(display_snapshot);
12434                        let goal = SelectionGoal::HorizontalPosition(
12435                            display_snapshot
12436                                .x_for_display_point(display_point, text_layout_details)
12437                                .into(),
12438                        );
12439                        (display_point, goal)
12440                    })
12441                });
12442            }
12443        });
12444    }
12445
12446    pub fn select_enclosing_symbol(
12447        &mut self,
12448        _: &SelectEnclosingSymbol,
12449        window: &mut Window,
12450        cx: &mut Context<Self>,
12451    ) {
12452        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
12453
12454        let buffer = self.buffer.read(cx).snapshot(cx);
12455        let old_selections = self.selections.all::<usize>(cx).into_boxed_slice();
12456
12457        fn update_selection(
12458            selection: &Selection<usize>,
12459            buffer_snap: &MultiBufferSnapshot,
12460        ) -> Option<Selection<usize>> {
12461            let cursor = selection.head();
12462            let (_buffer_id, symbols) = buffer_snap.symbols_containing(cursor, None)?;
12463            for symbol in symbols.iter().rev() {
12464                let start = symbol.range.start.to_offset(buffer_snap);
12465                let end = symbol.range.end.to_offset(buffer_snap);
12466                let new_range = start..end;
12467                if start < selection.start || end > selection.end {
12468                    return Some(Selection {
12469                        id: selection.id,
12470                        start: new_range.start,
12471                        end: new_range.end,
12472                        goal: SelectionGoal::None,
12473                        reversed: selection.reversed,
12474                    });
12475                }
12476            }
12477            None
12478        }
12479
12480        let mut selected_larger_symbol = false;
12481        let new_selections = old_selections
12482            .iter()
12483            .map(|selection| match update_selection(selection, &buffer) {
12484                Some(new_selection) => {
12485                    if new_selection.range() != selection.range() {
12486                        selected_larger_symbol = true;
12487                    }
12488                    new_selection
12489                }
12490                None => selection.clone(),
12491            })
12492            .collect::<Vec<_>>();
12493
12494        if selected_larger_symbol {
12495            self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
12496                s.select(new_selections);
12497            });
12498        }
12499    }
12500
12501    pub fn select_larger_syntax_node(
12502        &mut self,
12503        _: &SelectLargerSyntaxNode,
12504        window: &mut Window,
12505        cx: &mut Context<Self>,
12506    ) {
12507        let Some(visible_row_count) = self.visible_row_count() else {
12508            return;
12509        };
12510        let old_selections: Box<[_]> = self.selections.all::<usize>(cx).into();
12511        if old_selections.is_empty() {
12512            return;
12513        }
12514
12515        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
12516
12517        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
12518        let buffer = self.buffer.read(cx).snapshot(cx);
12519
12520        let mut selected_larger_node = false;
12521        let mut new_selections = old_selections
12522            .iter()
12523            .map(|selection| {
12524                let old_range = selection.start..selection.end;
12525                let mut new_range = old_range.clone();
12526                let mut new_node = None;
12527                while let Some((node, containing_range)) = buffer.syntax_ancestor(new_range.clone())
12528                {
12529                    new_node = Some(node);
12530                    new_range = match containing_range {
12531                        MultiOrSingleBufferOffsetRange::Single(_) => break,
12532                        MultiOrSingleBufferOffsetRange::Multi(range) => range,
12533                    };
12534                    if !display_map.intersects_fold(new_range.start)
12535                        && !display_map.intersects_fold(new_range.end)
12536                    {
12537                        break;
12538                    }
12539                }
12540
12541                if let Some(node) = new_node {
12542                    // Log the ancestor, to support using this action as a way to explore TreeSitter
12543                    // nodes. Parent and grandparent are also logged because this operation will not
12544                    // visit nodes that have the same range as their parent.
12545                    log::info!("Node: {node:?}");
12546                    let parent = node.parent();
12547                    log::info!("Parent: {parent:?}");
12548                    let grandparent = parent.and_then(|x| x.parent());
12549                    log::info!("Grandparent: {grandparent:?}");
12550                }
12551
12552                selected_larger_node |= new_range != old_range;
12553                Selection {
12554                    id: selection.id,
12555                    start: new_range.start,
12556                    end: new_range.end,
12557                    goal: SelectionGoal::None,
12558                    reversed: selection.reversed,
12559                }
12560            })
12561            .collect::<Vec<_>>();
12562
12563        if !selected_larger_node {
12564            return; // don't put this call in the history
12565        }
12566
12567        // scroll based on transformation done to the last selection created by the user
12568        let (last_old, last_new) = old_selections
12569            .last()
12570            .zip(new_selections.last().cloned())
12571            .expect("old_selections isn't empty");
12572
12573        // revert selection
12574        let is_selection_reversed = {
12575            let should_newest_selection_be_reversed = last_old.start != last_new.start;
12576            new_selections.last_mut().expect("checked above").reversed =
12577                should_newest_selection_be_reversed;
12578            should_newest_selection_be_reversed
12579        };
12580
12581        if selected_larger_node {
12582            self.select_syntax_node_history.disable_clearing = true;
12583            self.change_selections(None, window, cx, |s| {
12584                s.select(new_selections.clone());
12585            });
12586            self.select_syntax_node_history.disable_clearing = false;
12587        }
12588
12589        let start_row = last_new.start.to_display_point(&display_map).row().0;
12590        let end_row = last_new.end.to_display_point(&display_map).row().0;
12591        let selection_height = end_row - start_row + 1;
12592        let scroll_margin_rows = self.vertical_scroll_margin() as u32;
12593
12594        let fits_on_the_screen = visible_row_count >= selection_height + scroll_margin_rows * 2;
12595        let scroll_behavior = if fits_on_the_screen {
12596            self.request_autoscroll(Autoscroll::fit(), cx);
12597            SelectSyntaxNodeScrollBehavior::FitSelection
12598        } else if is_selection_reversed {
12599            self.scroll_cursor_top(&ScrollCursorTop, window, cx);
12600            SelectSyntaxNodeScrollBehavior::CursorTop
12601        } else {
12602            self.scroll_cursor_bottom(&ScrollCursorBottom, window, cx);
12603            SelectSyntaxNodeScrollBehavior::CursorBottom
12604        };
12605
12606        self.select_syntax_node_history.push((
12607            old_selections,
12608            scroll_behavior,
12609            is_selection_reversed,
12610        ));
12611    }
12612
12613    pub fn select_smaller_syntax_node(
12614        &mut self,
12615        _: &SelectSmallerSyntaxNode,
12616        window: &mut Window,
12617        cx: &mut Context<Self>,
12618    ) {
12619        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
12620
12621        if let Some((mut selections, scroll_behavior, is_selection_reversed)) =
12622            self.select_syntax_node_history.pop()
12623        {
12624            if let Some(selection) = selections.last_mut() {
12625                selection.reversed = is_selection_reversed;
12626            }
12627
12628            self.select_syntax_node_history.disable_clearing = true;
12629            self.change_selections(None, window, cx, |s| {
12630                s.select(selections.to_vec());
12631            });
12632            self.select_syntax_node_history.disable_clearing = false;
12633
12634            match scroll_behavior {
12635                SelectSyntaxNodeScrollBehavior::CursorTop => {
12636                    self.scroll_cursor_top(&ScrollCursorTop, window, cx);
12637                }
12638                SelectSyntaxNodeScrollBehavior::FitSelection => {
12639                    self.request_autoscroll(Autoscroll::fit(), cx);
12640                }
12641                SelectSyntaxNodeScrollBehavior::CursorBottom => {
12642                    self.scroll_cursor_bottom(&ScrollCursorBottom, window, cx);
12643                }
12644            }
12645        }
12646    }
12647
12648    fn refresh_runnables(&mut self, window: &mut Window, cx: &mut Context<Self>) -> Task<()> {
12649        if !EditorSettings::get_global(cx).gutter.runnables {
12650            self.clear_tasks();
12651            return Task::ready(());
12652        }
12653        let project = self.project.as_ref().map(Entity::downgrade);
12654        let task_sources = self.lsp_task_sources(cx);
12655        cx.spawn_in(window, async move |editor, cx| {
12656            cx.background_executor().timer(UPDATE_DEBOUNCE).await;
12657            let Some(project) = project.and_then(|p| p.upgrade()) else {
12658                return;
12659            };
12660            let Ok(display_snapshot) = editor.update(cx, |this, cx| {
12661                this.display_map.update(cx, |map, cx| map.snapshot(cx))
12662            }) else {
12663                return;
12664            };
12665
12666            let hide_runnables = project
12667                .update(cx, |project, cx| {
12668                    // Do not display any test indicators in non-dev server remote projects.
12669                    project.is_via_collab() && project.ssh_connection_string(cx).is_none()
12670                })
12671                .unwrap_or(true);
12672            if hide_runnables {
12673                return;
12674            }
12675            let new_rows =
12676                cx.background_spawn({
12677                    let snapshot = display_snapshot.clone();
12678                    async move {
12679                        Self::fetch_runnable_ranges(&snapshot, Anchor::min()..Anchor::max())
12680                    }
12681                })
12682                    .await;
12683            let Ok(lsp_tasks) =
12684                cx.update(|_, cx| crate::lsp_tasks(project.clone(), &task_sources, None, cx))
12685            else {
12686                return;
12687            };
12688            let lsp_tasks = lsp_tasks.await;
12689
12690            let Ok(mut lsp_tasks_by_rows) = cx.update(|_, cx| {
12691                lsp_tasks
12692                    .into_iter()
12693                    .flat_map(|(kind, tasks)| {
12694                        tasks.into_iter().filter_map(move |(location, task)| {
12695                            Some((kind.clone(), location?, task))
12696                        })
12697                    })
12698                    .fold(HashMap::default(), |mut acc, (kind, location, task)| {
12699                        let buffer = location.target.buffer;
12700                        let buffer_snapshot = buffer.read(cx).snapshot();
12701                        let offset = display_snapshot.buffer_snapshot.excerpts().find_map(
12702                            |(excerpt_id, snapshot, _)| {
12703                                if snapshot.remote_id() == buffer_snapshot.remote_id() {
12704                                    display_snapshot
12705                                        .buffer_snapshot
12706                                        .anchor_in_excerpt(excerpt_id, location.target.range.start)
12707                                } else {
12708                                    None
12709                                }
12710                            },
12711                        );
12712                        if let Some(offset) = offset {
12713                            let task_buffer_range =
12714                                location.target.range.to_point(&buffer_snapshot);
12715                            let context_buffer_range =
12716                                task_buffer_range.to_offset(&buffer_snapshot);
12717                            let context_range = BufferOffset(context_buffer_range.start)
12718                                ..BufferOffset(context_buffer_range.end);
12719
12720                            acc.entry((buffer_snapshot.remote_id(), task_buffer_range.start.row))
12721                                .or_insert_with(|| RunnableTasks {
12722                                    templates: Vec::new(),
12723                                    offset,
12724                                    column: task_buffer_range.start.column,
12725                                    extra_variables: HashMap::default(),
12726                                    context_range,
12727                                })
12728                                .templates
12729                                .push((kind, task.original_task().clone()));
12730                        }
12731
12732                        acc
12733                    })
12734            }) else {
12735                return;
12736            };
12737
12738            let rows = Self::runnable_rows(project, display_snapshot, new_rows, cx.clone());
12739            editor
12740                .update(cx, |editor, _| {
12741                    editor.clear_tasks();
12742                    for (key, mut value) in rows {
12743                        if let Some(lsp_tasks) = lsp_tasks_by_rows.remove(&key) {
12744                            value.templates.extend(lsp_tasks.templates);
12745                        }
12746
12747                        editor.insert_tasks(key, value);
12748                    }
12749                    for (key, value) in lsp_tasks_by_rows {
12750                        editor.insert_tasks(key, value);
12751                    }
12752                })
12753                .ok();
12754        })
12755    }
12756    fn fetch_runnable_ranges(
12757        snapshot: &DisplaySnapshot,
12758        range: Range<Anchor>,
12759    ) -> Vec<language::RunnableRange> {
12760        snapshot.buffer_snapshot.runnable_ranges(range).collect()
12761    }
12762
12763    fn runnable_rows(
12764        project: Entity<Project>,
12765        snapshot: DisplaySnapshot,
12766        runnable_ranges: Vec<RunnableRange>,
12767        mut cx: AsyncWindowContext,
12768    ) -> Vec<((BufferId, BufferRow), RunnableTasks)> {
12769        runnable_ranges
12770            .into_iter()
12771            .filter_map(|mut runnable| {
12772                let tasks = cx
12773                    .update(|_, cx| Self::templates_with_tags(&project, &mut runnable.runnable, cx))
12774                    .ok()?;
12775                if tasks.is_empty() {
12776                    return None;
12777                }
12778
12779                let point = runnable.run_range.start.to_point(&snapshot.buffer_snapshot);
12780
12781                let row = snapshot
12782                    .buffer_snapshot
12783                    .buffer_line_for_row(MultiBufferRow(point.row))?
12784                    .1
12785                    .start
12786                    .row;
12787
12788                let context_range =
12789                    BufferOffset(runnable.full_range.start)..BufferOffset(runnable.full_range.end);
12790                Some((
12791                    (runnable.buffer_id, row),
12792                    RunnableTasks {
12793                        templates: tasks,
12794                        offset: snapshot
12795                            .buffer_snapshot
12796                            .anchor_before(runnable.run_range.start),
12797                        context_range,
12798                        column: point.column,
12799                        extra_variables: runnable.extra_captures,
12800                    },
12801                ))
12802            })
12803            .collect()
12804    }
12805
12806    fn templates_with_tags(
12807        project: &Entity<Project>,
12808        runnable: &mut Runnable,
12809        cx: &mut App,
12810    ) -> Vec<(TaskSourceKind, TaskTemplate)> {
12811        let (inventory, worktree_id, file) = project.read_with(cx, |project, cx| {
12812            let (worktree_id, file) = project
12813                .buffer_for_id(runnable.buffer, cx)
12814                .and_then(|buffer| buffer.read(cx).file())
12815                .map(|file| (file.worktree_id(cx), file.clone()))
12816                .unzip();
12817
12818            (
12819                project.task_store().read(cx).task_inventory().cloned(),
12820                worktree_id,
12821                file,
12822            )
12823        });
12824
12825        let mut templates_with_tags = mem::take(&mut runnable.tags)
12826            .into_iter()
12827            .flat_map(|RunnableTag(tag)| {
12828                inventory
12829                    .as_ref()
12830                    .into_iter()
12831                    .flat_map(|inventory| {
12832                        inventory.read(cx).list_tasks(
12833                            file.clone(),
12834                            Some(runnable.language.clone()),
12835                            worktree_id,
12836                            cx,
12837                        )
12838                    })
12839                    .filter(move |(_, template)| {
12840                        template.tags.iter().any(|source_tag| source_tag == &tag)
12841                    })
12842            })
12843            .sorted_by_key(|(kind, _)| kind.to_owned())
12844            .collect::<Vec<_>>();
12845        if let Some((leading_tag_source, _)) = templates_with_tags.first() {
12846            // Strongest source wins; if we have worktree tag binding, prefer that to
12847            // global and language bindings;
12848            // if we have a global binding, prefer that to language binding.
12849            let first_mismatch = templates_with_tags
12850                .iter()
12851                .position(|(tag_source, _)| tag_source != leading_tag_source);
12852            if let Some(index) = first_mismatch {
12853                templates_with_tags.truncate(index);
12854            }
12855        }
12856
12857        templates_with_tags
12858    }
12859
12860    pub fn move_to_enclosing_bracket(
12861        &mut self,
12862        _: &MoveToEnclosingBracket,
12863        window: &mut Window,
12864        cx: &mut Context<Self>,
12865    ) {
12866        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
12867        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
12868            s.move_offsets_with(|snapshot, selection| {
12869                let Some(enclosing_bracket_ranges) =
12870                    snapshot.enclosing_bracket_ranges(selection.start..selection.end)
12871                else {
12872                    return;
12873                };
12874
12875                let mut best_length = usize::MAX;
12876                let mut best_inside = false;
12877                let mut best_in_bracket_range = false;
12878                let mut best_destination = None;
12879                for (open, close) in enclosing_bracket_ranges {
12880                    let close = close.to_inclusive();
12881                    let length = close.end() - open.start;
12882                    let inside = selection.start >= open.end && selection.end <= *close.start();
12883                    let in_bracket_range = open.to_inclusive().contains(&selection.head())
12884                        || close.contains(&selection.head());
12885
12886                    // If best is next to a bracket and current isn't, skip
12887                    if !in_bracket_range && best_in_bracket_range {
12888                        continue;
12889                    }
12890
12891                    // Prefer smaller lengths unless best is inside and current isn't
12892                    if length > best_length && (best_inside || !inside) {
12893                        continue;
12894                    }
12895
12896                    best_length = length;
12897                    best_inside = inside;
12898                    best_in_bracket_range = in_bracket_range;
12899                    best_destination = Some(
12900                        if close.contains(&selection.start) && close.contains(&selection.end) {
12901                            if inside { open.end } else { open.start }
12902                        } else if inside {
12903                            *close.start()
12904                        } else {
12905                            *close.end()
12906                        },
12907                    );
12908                }
12909
12910                if let Some(destination) = best_destination {
12911                    selection.collapse_to(destination, SelectionGoal::None);
12912                }
12913            })
12914        });
12915    }
12916
12917    pub fn undo_selection(
12918        &mut self,
12919        _: &UndoSelection,
12920        window: &mut Window,
12921        cx: &mut Context<Self>,
12922    ) {
12923        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
12924        self.end_selection(window, cx);
12925        self.selection_history.mode = SelectionHistoryMode::Undoing;
12926        if let Some(entry) = self.selection_history.undo_stack.pop_back() {
12927            self.change_selections(None, window, cx, |s| {
12928                s.select_anchors(entry.selections.to_vec())
12929            });
12930            self.select_next_state = entry.select_next_state;
12931            self.select_prev_state = entry.select_prev_state;
12932            self.add_selections_state = entry.add_selections_state;
12933            self.request_autoscroll(Autoscroll::newest(), cx);
12934        }
12935        self.selection_history.mode = SelectionHistoryMode::Normal;
12936    }
12937
12938    pub fn redo_selection(
12939        &mut self,
12940        _: &RedoSelection,
12941        window: &mut Window,
12942        cx: &mut Context<Self>,
12943    ) {
12944        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
12945        self.end_selection(window, cx);
12946        self.selection_history.mode = SelectionHistoryMode::Redoing;
12947        if let Some(entry) = self.selection_history.redo_stack.pop_back() {
12948            self.change_selections(None, window, cx, |s| {
12949                s.select_anchors(entry.selections.to_vec())
12950            });
12951            self.select_next_state = entry.select_next_state;
12952            self.select_prev_state = entry.select_prev_state;
12953            self.add_selections_state = entry.add_selections_state;
12954            self.request_autoscroll(Autoscroll::newest(), cx);
12955        }
12956        self.selection_history.mode = SelectionHistoryMode::Normal;
12957    }
12958
12959    pub fn expand_excerpts(
12960        &mut self,
12961        action: &ExpandExcerpts,
12962        _: &mut Window,
12963        cx: &mut Context<Self>,
12964    ) {
12965        self.expand_excerpts_for_direction(action.lines, ExpandExcerptDirection::UpAndDown, cx)
12966    }
12967
12968    pub fn expand_excerpts_down(
12969        &mut self,
12970        action: &ExpandExcerptsDown,
12971        _: &mut Window,
12972        cx: &mut Context<Self>,
12973    ) {
12974        self.expand_excerpts_for_direction(action.lines, ExpandExcerptDirection::Down, cx)
12975    }
12976
12977    pub fn expand_excerpts_up(
12978        &mut self,
12979        action: &ExpandExcerptsUp,
12980        _: &mut Window,
12981        cx: &mut Context<Self>,
12982    ) {
12983        self.expand_excerpts_for_direction(action.lines, ExpandExcerptDirection::Up, cx)
12984    }
12985
12986    pub fn expand_excerpts_for_direction(
12987        &mut self,
12988        lines: u32,
12989        direction: ExpandExcerptDirection,
12990
12991        cx: &mut Context<Self>,
12992    ) {
12993        let selections = self.selections.disjoint_anchors();
12994
12995        let lines = if lines == 0 {
12996            EditorSettings::get_global(cx).expand_excerpt_lines
12997        } else {
12998            lines
12999        };
13000
13001        self.buffer.update(cx, |buffer, cx| {
13002            let snapshot = buffer.snapshot(cx);
13003            let mut excerpt_ids = selections
13004                .iter()
13005                .flat_map(|selection| snapshot.excerpt_ids_for_range(selection.range()))
13006                .collect::<Vec<_>>();
13007            excerpt_ids.sort();
13008            excerpt_ids.dedup();
13009            buffer.expand_excerpts(excerpt_ids, lines, direction, cx)
13010        })
13011    }
13012
13013    pub fn expand_excerpt(
13014        &mut self,
13015        excerpt: ExcerptId,
13016        direction: ExpandExcerptDirection,
13017        window: &mut Window,
13018        cx: &mut Context<Self>,
13019    ) {
13020        let current_scroll_position = self.scroll_position(cx);
13021        let lines_to_expand = EditorSettings::get_global(cx).expand_excerpt_lines;
13022        let mut should_scroll_up = false;
13023
13024        if direction == ExpandExcerptDirection::Down {
13025            let multi_buffer = self.buffer.read(cx);
13026            let snapshot = multi_buffer.snapshot(cx);
13027            if let Some(buffer_id) = snapshot.buffer_id_for_excerpt(excerpt) {
13028                if let Some(buffer) = multi_buffer.buffer(buffer_id) {
13029                    if let Some(excerpt_range) = snapshot.buffer_range_for_excerpt(excerpt) {
13030                        let buffer_snapshot = buffer.read(cx).snapshot();
13031                        let excerpt_end_row =
13032                            Point::from_anchor(&excerpt_range.end, &buffer_snapshot).row;
13033                        let last_row = buffer_snapshot.max_point().row;
13034                        let lines_below = last_row.saturating_sub(excerpt_end_row);
13035                        should_scroll_up = lines_below >= lines_to_expand;
13036                    }
13037                }
13038            }
13039        }
13040
13041        self.buffer.update(cx, |buffer, cx| {
13042            buffer.expand_excerpts([excerpt], lines_to_expand, direction, cx)
13043        });
13044
13045        if should_scroll_up {
13046            let new_scroll_position =
13047                current_scroll_position + gpui::Point::new(0.0, lines_to_expand as f32);
13048            self.set_scroll_position(new_scroll_position, window, cx);
13049        }
13050    }
13051
13052    pub fn go_to_singleton_buffer_point(
13053        &mut self,
13054        point: Point,
13055        window: &mut Window,
13056        cx: &mut Context<Self>,
13057    ) {
13058        self.go_to_singleton_buffer_range(point..point, window, cx);
13059    }
13060
13061    pub fn go_to_singleton_buffer_range(
13062        &mut self,
13063        range: Range<Point>,
13064        window: &mut Window,
13065        cx: &mut Context<Self>,
13066    ) {
13067        let multibuffer = self.buffer().read(cx);
13068        let Some(buffer) = multibuffer.as_singleton() else {
13069            return;
13070        };
13071        let Some(start) = multibuffer.buffer_point_to_anchor(&buffer, range.start, cx) else {
13072            return;
13073        };
13074        let Some(end) = multibuffer.buffer_point_to_anchor(&buffer, range.end, cx) else {
13075            return;
13076        };
13077        self.change_selections(Some(Autoscroll::center()), window, cx, |s| {
13078            s.select_anchor_ranges([start..end])
13079        });
13080    }
13081
13082    pub fn go_to_diagnostic(
13083        &mut self,
13084        _: &GoToDiagnostic,
13085        window: &mut Window,
13086        cx: &mut Context<Self>,
13087    ) {
13088        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
13089        self.go_to_diagnostic_impl(Direction::Next, window, cx)
13090    }
13091
13092    pub fn go_to_prev_diagnostic(
13093        &mut self,
13094        _: &GoToPreviousDiagnostic,
13095        window: &mut Window,
13096        cx: &mut Context<Self>,
13097    ) {
13098        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
13099        self.go_to_diagnostic_impl(Direction::Prev, window, cx)
13100    }
13101
13102    pub fn go_to_diagnostic_impl(
13103        &mut self,
13104        direction: Direction,
13105        window: &mut Window,
13106        cx: &mut Context<Self>,
13107    ) {
13108        let buffer = self.buffer.read(cx).snapshot(cx);
13109        let selection = self.selections.newest::<usize>(cx);
13110
13111        let mut active_group_id = None;
13112        if let ActiveDiagnostic::Group(active_group) = &self.active_diagnostics {
13113            if active_group.active_range.start.to_offset(&buffer) == selection.start {
13114                active_group_id = Some(active_group.group_id);
13115            }
13116        }
13117
13118        fn filtered(
13119            snapshot: EditorSnapshot,
13120            diagnostics: impl Iterator<Item = DiagnosticEntry<usize>>,
13121        ) -> impl Iterator<Item = DiagnosticEntry<usize>> {
13122            diagnostics
13123                .filter(|entry| entry.range.start != entry.range.end)
13124                .filter(|entry| !entry.diagnostic.is_unnecessary)
13125                .filter(move |entry| !snapshot.intersects_fold(entry.range.start))
13126        }
13127
13128        let snapshot = self.snapshot(window, cx);
13129        let before = filtered(
13130            snapshot.clone(),
13131            buffer
13132                .diagnostics_in_range(0..selection.start)
13133                .filter(|entry| entry.range.start <= selection.start),
13134        );
13135        let after = filtered(
13136            snapshot,
13137            buffer
13138                .diagnostics_in_range(selection.start..buffer.len())
13139                .filter(|entry| entry.range.start >= selection.start),
13140        );
13141
13142        let mut found: Option<DiagnosticEntry<usize>> = None;
13143        if direction == Direction::Prev {
13144            'outer: for prev_diagnostics in [before.collect::<Vec<_>>(), after.collect::<Vec<_>>()]
13145            {
13146                for diagnostic in prev_diagnostics.into_iter().rev() {
13147                    if diagnostic.range.start != selection.start
13148                        || active_group_id
13149                            .is_some_and(|active| diagnostic.diagnostic.group_id < active)
13150                    {
13151                        found = Some(diagnostic);
13152                        break 'outer;
13153                    }
13154                }
13155            }
13156        } else {
13157            for diagnostic in after.chain(before) {
13158                if diagnostic.range.start != selection.start
13159                    || active_group_id.is_some_and(|active| diagnostic.diagnostic.group_id > active)
13160                {
13161                    found = Some(diagnostic);
13162                    break;
13163                }
13164            }
13165        }
13166        let Some(next_diagnostic) = found else {
13167            return;
13168        };
13169
13170        let Some(buffer_id) = buffer.anchor_after(next_diagnostic.range.start).buffer_id else {
13171            return;
13172        };
13173        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
13174            s.select_ranges(vec![
13175                next_diagnostic.range.start..next_diagnostic.range.start,
13176            ])
13177        });
13178        self.activate_diagnostics(buffer_id, next_diagnostic, window, cx);
13179        self.refresh_inline_completion(false, true, window, cx);
13180    }
13181
13182    fn go_to_next_hunk(&mut self, _: &GoToHunk, window: &mut Window, cx: &mut Context<Self>) {
13183        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
13184        let snapshot = self.snapshot(window, cx);
13185        let selection = self.selections.newest::<Point>(cx);
13186        self.go_to_hunk_before_or_after_position(
13187            &snapshot,
13188            selection.head(),
13189            Direction::Next,
13190            window,
13191            cx,
13192        );
13193    }
13194
13195    pub fn go_to_hunk_before_or_after_position(
13196        &mut self,
13197        snapshot: &EditorSnapshot,
13198        position: Point,
13199        direction: Direction,
13200        window: &mut Window,
13201        cx: &mut Context<Editor>,
13202    ) {
13203        let row = if direction == Direction::Next {
13204            self.hunk_after_position(snapshot, position)
13205                .map(|hunk| hunk.row_range.start)
13206        } else {
13207            self.hunk_before_position(snapshot, position)
13208        };
13209
13210        if let Some(row) = row {
13211            let destination = Point::new(row.0, 0);
13212            let autoscroll = Autoscroll::center();
13213
13214            self.unfold_ranges(&[destination..destination], false, false, cx);
13215            self.change_selections(Some(autoscroll), window, cx, |s| {
13216                s.select_ranges([destination..destination]);
13217            });
13218        }
13219    }
13220
13221    fn hunk_after_position(
13222        &mut self,
13223        snapshot: &EditorSnapshot,
13224        position: Point,
13225    ) -> Option<MultiBufferDiffHunk> {
13226        snapshot
13227            .buffer_snapshot
13228            .diff_hunks_in_range(position..snapshot.buffer_snapshot.max_point())
13229            .find(|hunk| hunk.row_range.start.0 > position.row)
13230            .or_else(|| {
13231                snapshot
13232                    .buffer_snapshot
13233                    .diff_hunks_in_range(Point::zero()..position)
13234                    .find(|hunk| hunk.row_range.end.0 < position.row)
13235            })
13236    }
13237
13238    fn go_to_prev_hunk(
13239        &mut self,
13240        _: &GoToPreviousHunk,
13241        window: &mut Window,
13242        cx: &mut Context<Self>,
13243    ) {
13244        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
13245        let snapshot = self.snapshot(window, cx);
13246        let selection = self.selections.newest::<Point>(cx);
13247        self.go_to_hunk_before_or_after_position(
13248            &snapshot,
13249            selection.head(),
13250            Direction::Prev,
13251            window,
13252            cx,
13253        );
13254    }
13255
13256    fn hunk_before_position(
13257        &mut self,
13258        snapshot: &EditorSnapshot,
13259        position: Point,
13260    ) -> Option<MultiBufferRow> {
13261        snapshot
13262            .buffer_snapshot
13263            .diff_hunk_before(position)
13264            .or_else(|| snapshot.buffer_snapshot.diff_hunk_before(Point::MAX))
13265    }
13266
13267    fn go_to_line<T: 'static>(
13268        &mut self,
13269        position: Anchor,
13270        highlight_color: Option<Hsla>,
13271        window: &mut Window,
13272        cx: &mut Context<Self>,
13273    ) {
13274        let snapshot = self.snapshot(window, cx).display_snapshot;
13275        let position = position.to_point(&snapshot.buffer_snapshot);
13276        let start = snapshot
13277            .buffer_snapshot
13278            .clip_point(Point::new(position.row, 0), Bias::Left);
13279        let end = start + Point::new(1, 0);
13280        let start = snapshot.buffer_snapshot.anchor_before(start);
13281        let end = snapshot.buffer_snapshot.anchor_before(end);
13282
13283        self.highlight_rows::<T>(
13284            start..end,
13285            highlight_color
13286                .unwrap_or_else(|| cx.theme().colors().editor_highlighted_line_background),
13287            false,
13288            cx,
13289        );
13290        self.request_autoscroll(Autoscroll::center().for_anchor(start), cx);
13291    }
13292
13293    pub fn go_to_definition(
13294        &mut self,
13295        _: &GoToDefinition,
13296        window: &mut Window,
13297        cx: &mut Context<Self>,
13298    ) -> Task<Result<Navigated>> {
13299        let definition =
13300            self.go_to_definition_of_kind(GotoDefinitionKind::Symbol, false, window, cx);
13301        let fallback_strategy = EditorSettings::get_global(cx).go_to_definition_fallback;
13302        cx.spawn_in(window, async move |editor, cx| {
13303            if definition.await? == Navigated::Yes {
13304                return Ok(Navigated::Yes);
13305            }
13306            match fallback_strategy {
13307                GoToDefinitionFallback::None => Ok(Navigated::No),
13308                GoToDefinitionFallback::FindAllReferences => {
13309                    match editor.update_in(cx, |editor, window, cx| {
13310                        editor.find_all_references(&FindAllReferences, window, cx)
13311                    })? {
13312                        Some(references) => references.await,
13313                        None => Ok(Navigated::No),
13314                    }
13315                }
13316            }
13317        })
13318    }
13319
13320    pub fn go_to_declaration(
13321        &mut self,
13322        _: &GoToDeclaration,
13323        window: &mut Window,
13324        cx: &mut Context<Self>,
13325    ) -> Task<Result<Navigated>> {
13326        self.go_to_definition_of_kind(GotoDefinitionKind::Declaration, false, window, cx)
13327    }
13328
13329    pub fn go_to_declaration_split(
13330        &mut self,
13331        _: &GoToDeclaration,
13332        window: &mut Window,
13333        cx: &mut Context<Self>,
13334    ) -> Task<Result<Navigated>> {
13335        self.go_to_definition_of_kind(GotoDefinitionKind::Declaration, true, window, cx)
13336    }
13337
13338    pub fn go_to_implementation(
13339        &mut self,
13340        _: &GoToImplementation,
13341        window: &mut Window,
13342        cx: &mut Context<Self>,
13343    ) -> Task<Result<Navigated>> {
13344        self.go_to_definition_of_kind(GotoDefinitionKind::Implementation, false, window, cx)
13345    }
13346
13347    pub fn go_to_implementation_split(
13348        &mut self,
13349        _: &GoToImplementationSplit,
13350        window: &mut Window,
13351        cx: &mut Context<Self>,
13352    ) -> Task<Result<Navigated>> {
13353        self.go_to_definition_of_kind(GotoDefinitionKind::Implementation, true, window, cx)
13354    }
13355
13356    pub fn go_to_type_definition(
13357        &mut self,
13358        _: &GoToTypeDefinition,
13359        window: &mut Window,
13360        cx: &mut Context<Self>,
13361    ) -> Task<Result<Navigated>> {
13362        self.go_to_definition_of_kind(GotoDefinitionKind::Type, false, window, cx)
13363    }
13364
13365    pub fn go_to_definition_split(
13366        &mut self,
13367        _: &GoToDefinitionSplit,
13368        window: &mut Window,
13369        cx: &mut Context<Self>,
13370    ) -> Task<Result<Navigated>> {
13371        self.go_to_definition_of_kind(GotoDefinitionKind::Symbol, true, window, cx)
13372    }
13373
13374    pub fn go_to_type_definition_split(
13375        &mut self,
13376        _: &GoToTypeDefinitionSplit,
13377        window: &mut Window,
13378        cx: &mut Context<Self>,
13379    ) -> Task<Result<Navigated>> {
13380        self.go_to_definition_of_kind(GotoDefinitionKind::Type, true, window, cx)
13381    }
13382
13383    fn go_to_definition_of_kind(
13384        &mut self,
13385        kind: GotoDefinitionKind,
13386        split: bool,
13387        window: &mut Window,
13388        cx: &mut Context<Self>,
13389    ) -> Task<Result<Navigated>> {
13390        let Some(provider) = self.semantics_provider.clone() else {
13391            return Task::ready(Ok(Navigated::No));
13392        };
13393        let head = self.selections.newest::<usize>(cx).head();
13394        let buffer = self.buffer.read(cx);
13395        let (buffer, head) = if let Some(text_anchor) = buffer.text_anchor_for_position(head, cx) {
13396            text_anchor
13397        } else {
13398            return Task::ready(Ok(Navigated::No));
13399        };
13400
13401        let Some(definitions) = provider.definitions(&buffer, head, kind, cx) else {
13402            return Task::ready(Ok(Navigated::No));
13403        };
13404
13405        cx.spawn_in(window, async move |editor, cx| {
13406            let definitions = definitions.await?;
13407            let navigated = editor
13408                .update_in(cx, |editor, window, cx| {
13409                    editor.navigate_to_hover_links(
13410                        Some(kind),
13411                        definitions
13412                            .into_iter()
13413                            .filter(|location| {
13414                                hover_links::exclude_link_to_position(&buffer, &head, location, cx)
13415                            })
13416                            .map(HoverLink::Text)
13417                            .collect::<Vec<_>>(),
13418                        split,
13419                        window,
13420                        cx,
13421                    )
13422                })?
13423                .await?;
13424            anyhow::Ok(navigated)
13425        })
13426    }
13427
13428    pub fn open_url(&mut self, _: &OpenUrl, window: &mut Window, cx: &mut Context<Self>) {
13429        let selection = self.selections.newest_anchor();
13430        let head = selection.head();
13431        let tail = selection.tail();
13432
13433        let Some((buffer, start_position)) =
13434            self.buffer.read(cx).text_anchor_for_position(head, cx)
13435        else {
13436            return;
13437        };
13438
13439        let end_position = if head != tail {
13440            let Some((_, pos)) = self.buffer.read(cx).text_anchor_for_position(tail, cx) else {
13441                return;
13442            };
13443            Some(pos)
13444        } else {
13445            None
13446        };
13447
13448        let url_finder = cx.spawn_in(window, async move |editor, cx| {
13449            let url = if let Some(end_pos) = end_position {
13450                find_url_from_range(&buffer, start_position..end_pos, cx.clone())
13451            } else {
13452                find_url(&buffer, start_position, cx.clone()).map(|(_, url)| url)
13453            };
13454
13455            if let Some(url) = url {
13456                editor.update(cx, |_, cx| {
13457                    cx.open_url(&url);
13458                })
13459            } else {
13460                Ok(())
13461            }
13462        });
13463
13464        url_finder.detach();
13465    }
13466
13467    pub fn open_selected_filename(
13468        &mut self,
13469        _: &OpenSelectedFilename,
13470        window: &mut Window,
13471        cx: &mut Context<Self>,
13472    ) {
13473        let Some(workspace) = self.workspace() else {
13474            return;
13475        };
13476
13477        let position = self.selections.newest_anchor().head();
13478
13479        let Some((buffer, buffer_position)) =
13480            self.buffer.read(cx).text_anchor_for_position(position, cx)
13481        else {
13482            return;
13483        };
13484
13485        let project = self.project.clone();
13486
13487        cx.spawn_in(window, async move |_, cx| {
13488            let result = find_file(&buffer, project, buffer_position, cx).await;
13489
13490            if let Some((_, path)) = result {
13491                workspace
13492                    .update_in(cx, |workspace, window, cx| {
13493                        workspace.open_resolved_path(path, window, cx)
13494                    })?
13495                    .await?;
13496            }
13497            anyhow::Ok(())
13498        })
13499        .detach();
13500    }
13501
13502    pub(crate) fn navigate_to_hover_links(
13503        &mut self,
13504        kind: Option<GotoDefinitionKind>,
13505        mut definitions: Vec<HoverLink>,
13506        split: bool,
13507        window: &mut Window,
13508        cx: &mut Context<Editor>,
13509    ) -> Task<Result<Navigated>> {
13510        // If there is one definition, just open it directly
13511        if definitions.len() == 1 {
13512            let definition = definitions.pop().unwrap();
13513
13514            enum TargetTaskResult {
13515                Location(Option<Location>),
13516                AlreadyNavigated,
13517            }
13518
13519            let target_task = match definition {
13520                HoverLink::Text(link) => {
13521                    Task::ready(anyhow::Ok(TargetTaskResult::Location(Some(link.target))))
13522                }
13523                HoverLink::InlayHint(lsp_location, server_id) => {
13524                    let computation =
13525                        self.compute_target_location(lsp_location, server_id, window, cx);
13526                    cx.background_spawn(async move {
13527                        let location = computation.await?;
13528                        Ok(TargetTaskResult::Location(location))
13529                    })
13530                }
13531                HoverLink::Url(url) => {
13532                    cx.open_url(&url);
13533                    Task::ready(Ok(TargetTaskResult::AlreadyNavigated))
13534                }
13535                HoverLink::File(path) => {
13536                    if let Some(workspace) = self.workspace() {
13537                        cx.spawn_in(window, async move |_, cx| {
13538                            workspace
13539                                .update_in(cx, |workspace, window, cx| {
13540                                    workspace.open_resolved_path(path, window, cx)
13541                                })?
13542                                .await
13543                                .map(|_| TargetTaskResult::AlreadyNavigated)
13544                        })
13545                    } else {
13546                        Task::ready(Ok(TargetTaskResult::Location(None)))
13547                    }
13548                }
13549            };
13550            cx.spawn_in(window, async move |editor, cx| {
13551                let target = match target_task.await.context("target resolution task")? {
13552                    TargetTaskResult::AlreadyNavigated => return Ok(Navigated::Yes),
13553                    TargetTaskResult::Location(None) => return Ok(Navigated::No),
13554                    TargetTaskResult::Location(Some(target)) => target,
13555                };
13556
13557                editor.update_in(cx, |editor, window, cx| {
13558                    let Some(workspace) = editor.workspace() else {
13559                        return Navigated::No;
13560                    };
13561                    let pane = workspace.read(cx).active_pane().clone();
13562
13563                    let range = target.range.to_point(target.buffer.read(cx));
13564                    let range = editor.range_for_match(&range);
13565                    let range = collapse_multiline_range(range);
13566
13567                    if !split
13568                        && Some(&target.buffer) == editor.buffer.read(cx).as_singleton().as_ref()
13569                    {
13570                        editor.go_to_singleton_buffer_range(range.clone(), window, cx);
13571                    } else {
13572                        window.defer(cx, move |window, cx| {
13573                            let target_editor: Entity<Self> =
13574                                workspace.update(cx, |workspace, cx| {
13575                                    let pane = if split {
13576                                        workspace.adjacent_pane(window, cx)
13577                                    } else {
13578                                        workspace.active_pane().clone()
13579                                    };
13580
13581                                    workspace.open_project_item(
13582                                        pane,
13583                                        target.buffer.clone(),
13584                                        true,
13585                                        true,
13586                                        window,
13587                                        cx,
13588                                    )
13589                                });
13590                            target_editor.update(cx, |target_editor, cx| {
13591                                // When selecting a definition in a different buffer, disable the nav history
13592                                // to avoid creating a history entry at the previous cursor location.
13593                                pane.update(cx, |pane, _| pane.disable_history());
13594                                target_editor.go_to_singleton_buffer_range(range, window, cx);
13595                                pane.update(cx, |pane, _| pane.enable_history());
13596                            });
13597                        });
13598                    }
13599                    Navigated::Yes
13600                })
13601            })
13602        } else if !definitions.is_empty() {
13603            cx.spawn_in(window, async move |editor, cx| {
13604                let (title, location_tasks, workspace) = editor
13605                    .update_in(cx, |editor, window, cx| {
13606                        let tab_kind = match kind {
13607                            Some(GotoDefinitionKind::Implementation) => "Implementations",
13608                            _ => "Definitions",
13609                        };
13610                        let title = definitions
13611                            .iter()
13612                            .find_map(|definition| match definition {
13613                                HoverLink::Text(link) => link.origin.as_ref().map(|origin| {
13614                                    let buffer = origin.buffer.read(cx);
13615                                    format!(
13616                                        "{} for {}",
13617                                        tab_kind,
13618                                        buffer
13619                                            .text_for_range(origin.range.clone())
13620                                            .collect::<String>()
13621                                    )
13622                                }),
13623                                HoverLink::InlayHint(_, _) => None,
13624                                HoverLink::Url(_) => None,
13625                                HoverLink::File(_) => None,
13626                            })
13627                            .unwrap_or(tab_kind.to_string());
13628                        let location_tasks = definitions
13629                            .into_iter()
13630                            .map(|definition| match definition {
13631                                HoverLink::Text(link) => Task::ready(Ok(Some(link.target))),
13632                                HoverLink::InlayHint(lsp_location, server_id) => editor
13633                                    .compute_target_location(lsp_location, server_id, window, cx),
13634                                HoverLink::Url(_) => Task::ready(Ok(None)),
13635                                HoverLink::File(_) => Task::ready(Ok(None)),
13636                            })
13637                            .collect::<Vec<_>>();
13638                        (title, location_tasks, editor.workspace().clone())
13639                    })
13640                    .context("location tasks preparation")?;
13641
13642                let locations = future::join_all(location_tasks)
13643                    .await
13644                    .into_iter()
13645                    .filter_map(|location| location.transpose())
13646                    .collect::<Result<_>>()
13647                    .context("location tasks")?;
13648
13649                let Some(workspace) = workspace else {
13650                    return Ok(Navigated::No);
13651                };
13652                let opened = workspace
13653                    .update_in(cx, |workspace, window, cx| {
13654                        Self::open_locations_in_multibuffer(
13655                            workspace,
13656                            locations,
13657                            title,
13658                            split,
13659                            MultibufferSelectionMode::First,
13660                            window,
13661                            cx,
13662                        )
13663                    })
13664                    .ok();
13665
13666                anyhow::Ok(Navigated::from_bool(opened.is_some()))
13667            })
13668        } else {
13669            Task::ready(Ok(Navigated::No))
13670        }
13671    }
13672
13673    fn compute_target_location(
13674        &self,
13675        lsp_location: lsp::Location,
13676        server_id: LanguageServerId,
13677        window: &mut Window,
13678        cx: &mut Context<Self>,
13679    ) -> Task<anyhow::Result<Option<Location>>> {
13680        let Some(project) = self.project.clone() else {
13681            return Task::ready(Ok(None));
13682        };
13683
13684        cx.spawn_in(window, async move |editor, cx| {
13685            let location_task = editor.update(cx, |_, cx| {
13686                project.update(cx, |project, cx| {
13687                    let language_server_name = project
13688                        .language_server_statuses(cx)
13689                        .find(|(id, _)| server_id == *id)
13690                        .map(|(_, status)| LanguageServerName::from(status.name.as_str()));
13691                    language_server_name.map(|language_server_name| {
13692                        project.open_local_buffer_via_lsp(
13693                            lsp_location.uri.clone(),
13694                            server_id,
13695                            language_server_name,
13696                            cx,
13697                        )
13698                    })
13699                })
13700            })?;
13701            let location = match location_task {
13702                Some(task) => Some({
13703                    let target_buffer_handle = task.await.context("open local buffer")?;
13704                    let range = target_buffer_handle.update(cx, |target_buffer, _| {
13705                        let target_start = target_buffer
13706                            .clip_point_utf16(point_from_lsp(lsp_location.range.start), Bias::Left);
13707                        let target_end = target_buffer
13708                            .clip_point_utf16(point_from_lsp(lsp_location.range.end), Bias::Left);
13709                        target_buffer.anchor_after(target_start)
13710                            ..target_buffer.anchor_before(target_end)
13711                    })?;
13712                    Location {
13713                        buffer: target_buffer_handle,
13714                        range,
13715                    }
13716                }),
13717                None => None,
13718            };
13719            Ok(location)
13720        })
13721    }
13722
13723    pub fn find_all_references(
13724        &mut self,
13725        _: &FindAllReferences,
13726        window: &mut Window,
13727        cx: &mut Context<Self>,
13728    ) -> Option<Task<Result<Navigated>>> {
13729        let selection = self.selections.newest::<usize>(cx);
13730        let multi_buffer = self.buffer.read(cx);
13731        let head = selection.head();
13732
13733        let multi_buffer_snapshot = multi_buffer.snapshot(cx);
13734        let head_anchor = multi_buffer_snapshot.anchor_at(
13735            head,
13736            if head < selection.tail() {
13737                Bias::Right
13738            } else {
13739                Bias::Left
13740            },
13741        );
13742
13743        match self
13744            .find_all_references_task_sources
13745            .binary_search_by(|anchor| anchor.cmp(&head_anchor, &multi_buffer_snapshot))
13746        {
13747            Ok(_) => {
13748                log::info!(
13749                    "Ignoring repeated FindAllReferences invocation with the position of already running task"
13750                );
13751                return None;
13752            }
13753            Err(i) => {
13754                self.find_all_references_task_sources.insert(i, head_anchor);
13755            }
13756        }
13757
13758        let (buffer, head) = multi_buffer.text_anchor_for_position(head, cx)?;
13759        let workspace = self.workspace()?;
13760        let project = workspace.read(cx).project().clone();
13761        let references = project.update(cx, |project, cx| project.references(&buffer, head, cx));
13762        Some(cx.spawn_in(window, async move |editor, cx| {
13763            let _cleanup = cx.on_drop(&editor, move |editor, _| {
13764                if let Ok(i) = editor
13765                    .find_all_references_task_sources
13766                    .binary_search_by(|anchor| anchor.cmp(&head_anchor, &multi_buffer_snapshot))
13767                {
13768                    editor.find_all_references_task_sources.remove(i);
13769                }
13770            });
13771
13772            let locations = references.await?;
13773            if locations.is_empty() {
13774                return anyhow::Ok(Navigated::No);
13775            }
13776
13777            workspace.update_in(cx, |workspace, window, cx| {
13778                let title = locations
13779                    .first()
13780                    .as_ref()
13781                    .map(|location| {
13782                        let buffer = location.buffer.read(cx);
13783                        format!(
13784                            "References to `{}`",
13785                            buffer
13786                                .text_for_range(location.range.clone())
13787                                .collect::<String>()
13788                        )
13789                    })
13790                    .unwrap();
13791                Self::open_locations_in_multibuffer(
13792                    workspace,
13793                    locations,
13794                    title,
13795                    false,
13796                    MultibufferSelectionMode::First,
13797                    window,
13798                    cx,
13799                );
13800                Navigated::Yes
13801            })
13802        }))
13803    }
13804
13805    /// Opens a multibuffer with the given project locations in it
13806    pub fn open_locations_in_multibuffer(
13807        workspace: &mut Workspace,
13808        mut locations: Vec<Location>,
13809        title: String,
13810        split: bool,
13811        multibuffer_selection_mode: MultibufferSelectionMode,
13812        window: &mut Window,
13813        cx: &mut Context<Workspace>,
13814    ) {
13815        // If there are multiple definitions, open them in a multibuffer
13816        locations.sort_by_key(|location| location.buffer.read(cx).remote_id());
13817        let mut locations = locations.into_iter().peekable();
13818        let mut ranges: Vec<Range<Anchor>> = Vec::new();
13819        let capability = workspace.project().read(cx).capability();
13820
13821        let excerpt_buffer = cx.new(|cx| {
13822            let mut multibuffer = MultiBuffer::new(capability);
13823            while let Some(location) = locations.next() {
13824                let buffer = location.buffer.read(cx);
13825                let mut ranges_for_buffer = Vec::new();
13826                let range = location.range.to_point(buffer);
13827                ranges_for_buffer.push(range.clone());
13828
13829                while let Some(next_location) = locations.peek() {
13830                    if next_location.buffer == location.buffer {
13831                        ranges_for_buffer.push(next_location.range.to_point(buffer));
13832                        locations.next();
13833                    } else {
13834                        break;
13835                    }
13836                }
13837
13838                ranges_for_buffer.sort_by_key(|range| (range.start, Reverse(range.end)));
13839                let (new_ranges, _) = multibuffer.set_excerpts_for_path(
13840                    PathKey::for_buffer(&location.buffer, cx),
13841                    location.buffer.clone(),
13842                    ranges_for_buffer,
13843                    DEFAULT_MULTIBUFFER_CONTEXT,
13844                    cx,
13845                );
13846                ranges.extend(new_ranges)
13847            }
13848
13849            multibuffer.with_title(title)
13850        });
13851
13852        let editor = cx.new(|cx| {
13853            Editor::for_multibuffer(
13854                excerpt_buffer,
13855                Some(workspace.project().clone()),
13856                window,
13857                cx,
13858            )
13859        });
13860        editor.update(cx, |editor, cx| {
13861            match multibuffer_selection_mode {
13862                MultibufferSelectionMode::First => {
13863                    if let Some(first_range) = ranges.first() {
13864                        editor.change_selections(None, window, cx, |selections| {
13865                            selections.clear_disjoint();
13866                            selections.select_anchor_ranges(std::iter::once(first_range.clone()));
13867                        });
13868                    }
13869                    editor.highlight_background::<Self>(
13870                        &ranges,
13871                        |theme| theme.editor_highlighted_line_background,
13872                        cx,
13873                    );
13874                }
13875                MultibufferSelectionMode::All => {
13876                    editor.change_selections(None, window, cx, |selections| {
13877                        selections.clear_disjoint();
13878                        selections.select_anchor_ranges(ranges);
13879                    });
13880                }
13881            }
13882            editor.register_buffers_with_language_servers(cx);
13883        });
13884
13885        let item = Box::new(editor);
13886        let item_id = item.item_id();
13887
13888        if split {
13889            workspace.split_item(SplitDirection::Right, item.clone(), window, cx);
13890        } else {
13891            if PreviewTabsSettings::get_global(cx).enable_preview_from_code_navigation {
13892                let (preview_item_id, preview_item_idx) =
13893                    workspace.active_pane().update(cx, |pane, _| {
13894                        (pane.preview_item_id(), pane.preview_item_idx())
13895                    });
13896
13897                workspace.add_item_to_active_pane(item.clone(), preview_item_idx, true, window, cx);
13898
13899                if let Some(preview_item_id) = preview_item_id {
13900                    workspace.active_pane().update(cx, |pane, cx| {
13901                        pane.remove_item(preview_item_id, false, false, window, cx);
13902                    });
13903                }
13904            } else {
13905                workspace.add_item_to_active_pane(item.clone(), None, true, window, cx);
13906            }
13907        }
13908        workspace.active_pane().update(cx, |pane, cx| {
13909            pane.set_preview_item_id(Some(item_id), cx);
13910        });
13911    }
13912
13913    pub fn rename(
13914        &mut self,
13915        _: &Rename,
13916        window: &mut Window,
13917        cx: &mut Context<Self>,
13918    ) -> Option<Task<Result<()>>> {
13919        use language::ToOffset as _;
13920
13921        let provider = self.semantics_provider.clone()?;
13922        let selection = self.selections.newest_anchor().clone();
13923        let (cursor_buffer, cursor_buffer_position) = self
13924            .buffer
13925            .read(cx)
13926            .text_anchor_for_position(selection.head(), cx)?;
13927        let (tail_buffer, cursor_buffer_position_end) = self
13928            .buffer
13929            .read(cx)
13930            .text_anchor_for_position(selection.tail(), cx)?;
13931        if tail_buffer != cursor_buffer {
13932            return None;
13933        }
13934
13935        let snapshot = cursor_buffer.read(cx).snapshot();
13936        let cursor_buffer_offset = cursor_buffer_position.to_offset(&snapshot);
13937        let cursor_buffer_offset_end = cursor_buffer_position_end.to_offset(&snapshot);
13938        let prepare_rename = provider
13939            .range_for_rename(&cursor_buffer, cursor_buffer_position, cx)
13940            .unwrap_or_else(|| Task::ready(Ok(None)));
13941        drop(snapshot);
13942
13943        Some(cx.spawn_in(window, async move |this, cx| {
13944            let rename_range = if let Some(range) = prepare_rename.await? {
13945                Some(range)
13946            } else {
13947                this.update(cx, |this, cx| {
13948                    let buffer = this.buffer.read(cx).snapshot(cx);
13949                    let mut buffer_highlights = this
13950                        .document_highlights_for_position(selection.head(), &buffer)
13951                        .filter(|highlight| {
13952                            highlight.start.excerpt_id == selection.head().excerpt_id
13953                                && highlight.end.excerpt_id == selection.head().excerpt_id
13954                        });
13955                    buffer_highlights
13956                        .next()
13957                        .map(|highlight| highlight.start.text_anchor..highlight.end.text_anchor)
13958                })?
13959            };
13960            if let Some(rename_range) = rename_range {
13961                this.update_in(cx, |this, window, cx| {
13962                    let snapshot = cursor_buffer.read(cx).snapshot();
13963                    let rename_buffer_range = rename_range.to_offset(&snapshot);
13964                    let cursor_offset_in_rename_range =
13965                        cursor_buffer_offset.saturating_sub(rename_buffer_range.start);
13966                    let cursor_offset_in_rename_range_end =
13967                        cursor_buffer_offset_end.saturating_sub(rename_buffer_range.start);
13968
13969                    this.take_rename(false, window, cx);
13970                    let buffer = this.buffer.read(cx).read(cx);
13971                    let cursor_offset = selection.head().to_offset(&buffer);
13972                    let rename_start = cursor_offset.saturating_sub(cursor_offset_in_rename_range);
13973                    let rename_end = rename_start + rename_buffer_range.len();
13974                    let range = buffer.anchor_before(rename_start)..buffer.anchor_after(rename_end);
13975                    let mut old_highlight_id = None;
13976                    let old_name: Arc<str> = buffer
13977                        .chunks(rename_start..rename_end, true)
13978                        .map(|chunk| {
13979                            if old_highlight_id.is_none() {
13980                                old_highlight_id = chunk.syntax_highlight_id;
13981                            }
13982                            chunk.text
13983                        })
13984                        .collect::<String>()
13985                        .into();
13986
13987                    drop(buffer);
13988
13989                    // Position the selection in the rename editor so that it matches the current selection.
13990                    this.show_local_selections = false;
13991                    let rename_editor = cx.new(|cx| {
13992                        let mut editor = Editor::single_line(window, cx);
13993                        editor.buffer.update(cx, |buffer, cx| {
13994                            buffer.edit([(0..0, old_name.clone())], None, cx)
13995                        });
13996                        let rename_selection_range = match cursor_offset_in_rename_range
13997                            .cmp(&cursor_offset_in_rename_range_end)
13998                        {
13999                            Ordering::Equal => {
14000                                editor.select_all(&SelectAll, window, cx);
14001                                return editor;
14002                            }
14003                            Ordering::Less => {
14004                                cursor_offset_in_rename_range..cursor_offset_in_rename_range_end
14005                            }
14006                            Ordering::Greater => {
14007                                cursor_offset_in_rename_range_end..cursor_offset_in_rename_range
14008                            }
14009                        };
14010                        if rename_selection_range.end > old_name.len() {
14011                            editor.select_all(&SelectAll, window, cx);
14012                        } else {
14013                            editor.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
14014                                s.select_ranges([rename_selection_range]);
14015                            });
14016                        }
14017                        editor
14018                    });
14019                    cx.subscribe(&rename_editor, |_, _, e: &EditorEvent, cx| {
14020                        if e == &EditorEvent::Focused {
14021                            cx.emit(EditorEvent::FocusedIn)
14022                        }
14023                    })
14024                    .detach();
14025
14026                    let write_highlights =
14027                        this.clear_background_highlights::<DocumentHighlightWrite>(cx);
14028                    let read_highlights =
14029                        this.clear_background_highlights::<DocumentHighlightRead>(cx);
14030                    let ranges = write_highlights
14031                        .iter()
14032                        .flat_map(|(_, ranges)| ranges.iter())
14033                        .chain(read_highlights.iter().flat_map(|(_, ranges)| ranges.iter()))
14034                        .cloned()
14035                        .collect();
14036
14037                    this.highlight_text::<Rename>(
14038                        ranges,
14039                        HighlightStyle {
14040                            fade_out: Some(0.6),
14041                            ..Default::default()
14042                        },
14043                        cx,
14044                    );
14045                    let rename_focus_handle = rename_editor.focus_handle(cx);
14046                    window.focus(&rename_focus_handle);
14047                    let block_id = this.insert_blocks(
14048                        [BlockProperties {
14049                            style: BlockStyle::Flex,
14050                            placement: BlockPlacement::Below(range.start),
14051                            height: Some(1),
14052                            render: Arc::new({
14053                                let rename_editor = rename_editor.clone();
14054                                move |cx: &mut BlockContext| {
14055                                    let mut text_style = cx.editor_style.text.clone();
14056                                    if let Some(highlight_style) = old_highlight_id
14057                                        .and_then(|h| h.style(&cx.editor_style.syntax))
14058                                    {
14059                                        text_style = text_style.highlight(highlight_style);
14060                                    }
14061                                    div()
14062                                        .block_mouse_down()
14063                                        .pl(cx.anchor_x)
14064                                        .child(EditorElement::new(
14065                                            &rename_editor,
14066                                            EditorStyle {
14067                                                background: cx.theme().system().transparent,
14068                                                local_player: cx.editor_style.local_player,
14069                                                text: text_style,
14070                                                scrollbar_width: cx.editor_style.scrollbar_width,
14071                                                syntax: cx.editor_style.syntax.clone(),
14072                                                status: cx.editor_style.status.clone(),
14073                                                inlay_hints_style: HighlightStyle {
14074                                                    font_weight: Some(FontWeight::BOLD),
14075                                                    ..make_inlay_hints_style(cx.app)
14076                                                },
14077                                                inline_completion_styles: make_suggestion_styles(
14078                                                    cx.app,
14079                                                ),
14080                                                ..EditorStyle::default()
14081                                            },
14082                                        ))
14083                                        .into_any_element()
14084                                }
14085                            }),
14086                            priority: 0,
14087                        }],
14088                        Some(Autoscroll::fit()),
14089                        cx,
14090                    )[0];
14091                    this.pending_rename = Some(RenameState {
14092                        range,
14093                        old_name,
14094                        editor: rename_editor,
14095                        block_id,
14096                    });
14097                })?;
14098            }
14099
14100            Ok(())
14101        }))
14102    }
14103
14104    pub fn confirm_rename(
14105        &mut self,
14106        _: &ConfirmRename,
14107        window: &mut Window,
14108        cx: &mut Context<Self>,
14109    ) -> Option<Task<Result<()>>> {
14110        let rename = self.take_rename(false, window, cx)?;
14111        let workspace = self.workspace()?.downgrade();
14112        let (buffer, start) = self
14113            .buffer
14114            .read(cx)
14115            .text_anchor_for_position(rename.range.start, cx)?;
14116        let (end_buffer, _) = self
14117            .buffer
14118            .read(cx)
14119            .text_anchor_for_position(rename.range.end, cx)?;
14120        if buffer != end_buffer {
14121            return None;
14122        }
14123
14124        let old_name = rename.old_name;
14125        let new_name = rename.editor.read(cx).text(cx);
14126
14127        let rename = self.semantics_provider.as_ref()?.perform_rename(
14128            &buffer,
14129            start,
14130            new_name.clone(),
14131            cx,
14132        )?;
14133
14134        Some(cx.spawn_in(window, async move |editor, cx| {
14135            let project_transaction = rename.await?;
14136            Self::open_project_transaction(
14137                &editor,
14138                workspace,
14139                project_transaction,
14140                format!("Rename: {}{}", old_name, new_name),
14141                cx,
14142            )
14143            .await?;
14144
14145            editor.update(cx, |editor, cx| {
14146                editor.refresh_document_highlights(cx);
14147            })?;
14148            Ok(())
14149        }))
14150    }
14151
14152    fn take_rename(
14153        &mut self,
14154        moving_cursor: bool,
14155        window: &mut Window,
14156        cx: &mut Context<Self>,
14157    ) -> Option<RenameState> {
14158        let rename = self.pending_rename.take()?;
14159        if rename.editor.focus_handle(cx).is_focused(window) {
14160            window.focus(&self.focus_handle);
14161        }
14162
14163        self.remove_blocks(
14164            [rename.block_id].into_iter().collect(),
14165            Some(Autoscroll::fit()),
14166            cx,
14167        );
14168        self.clear_highlights::<Rename>(cx);
14169        self.show_local_selections = true;
14170
14171        if moving_cursor {
14172            let cursor_in_rename_editor = rename.editor.update(cx, |editor, cx| {
14173                editor.selections.newest::<usize>(cx).head()
14174            });
14175
14176            // Update the selection to match the position of the selection inside
14177            // the rename editor.
14178            let snapshot = self.buffer.read(cx).read(cx);
14179            let rename_range = rename.range.to_offset(&snapshot);
14180            let cursor_in_editor = snapshot
14181                .clip_offset(rename_range.start + cursor_in_rename_editor, Bias::Left)
14182                .min(rename_range.end);
14183            drop(snapshot);
14184
14185            self.change_selections(None, window, cx, |s| {
14186                s.select_ranges(vec![cursor_in_editor..cursor_in_editor])
14187            });
14188        } else {
14189            self.refresh_document_highlights(cx);
14190        }
14191
14192        Some(rename)
14193    }
14194
14195    pub fn pending_rename(&self) -> Option<&RenameState> {
14196        self.pending_rename.as_ref()
14197    }
14198
14199    fn format(
14200        &mut self,
14201        _: &Format,
14202        window: &mut Window,
14203        cx: &mut Context<Self>,
14204    ) -> Option<Task<Result<()>>> {
14205        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
14206
14207        let project = match &self.project {
14208            Some(project) => project.clone(),
14209            None => return None,
14210        };
14211
14212        Some(self.perform_format(
14213            project,
14214            FormatTrigger::Manual,
14215            FormatTarget::Buffers,
14216            window,
14217            cx,
14218        ))
14219    }
14220
14221    fn format_selections(
14222        &mut self,
14223        _: &FormatSelections,
14224        window: &mut Window,
14225        cx: &mut Context<Self>,
14226    ) -> Option<Task<Result<()>>> {
14227        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
14228
14229        let project = match &self.project {
14230            Some(project) => project.clone(),
14231            None => return None,
14232        };
14233
14234        let ranges = self
14235            .selections
14236            .all_adjusted(cx)
14237            .into_iter()
14238            .map(|selection| selection.range())
14239            .collect_vec();
14240
14241        Some(self.perform_format(
14242            project,
14243            FormatTrigger::Manual,
14244            FormatTarget::Ranges(ranges),
14245            window,
14246            cx,
14247        ))
14248    }
14249
14250    fn perform_format(
14251        &mut self,
14252        project: Entity<Project>,
14253        trigger: FormatTrigger,
14254        target: FormatTarget,
14255        window: &mut Window,
14256        cx: &mut Context<Self>,
14257    ) -> Task<Result<()>> {
14258        let buffer = self.buffer.clone();
14259        let (buffers, target) = match target {
14260            FormatTarget::Buffers => {
14261                let mut buffers = buffer.read(cx).all_buffers();
14262                if trigger == FormatTrigger::Save {
14263                    buffers.retain(|buffer| buffer.read(cx).is_dirty());
14264                }
14265                (buffers, LspFormatTarget::Buffers)
14266            }
14267            FormatTarget::Ranges(selection_ranges) => {
14268                let multi_buffer = buffer.read(cx);
14269                let snapshot = multi_buffer.read(cx);
14270                let mut buffers = HashSet::default();
14271                let mut buffer_id_to_ranges: BTreeMap<BufferId, Vec<Range<text::Anchor>>> =
14272                    BTreeMap::new();
14273                for selection_range in selection_ranges {
14274                    for (buffer, buffer_range, _) in
14275                        snapshot.range_to_buffer_ranges(selection_range)
14276                    {
14277                        let buffer_id = buffer.remote_id();
14278                        let start = buffer.anchor_before(buffer_range.start);
14279                        let end = buffer.anchor_after(buffer_range.end);
14280                        buffers.insert(multi_buffer.buffer(buffer_id).unwrap());
14281                        buffer_id_to_ranges
14282                            .entry(buffer_id)
14283                            .and_modify(|buffer_ranges| buffer_ranges.push(start..end))
14284                            .or_insert_with(|| vec![start..end]);
14285                    }
14286                }
14287                (buffers, LspFormatTarget::Ranges(buffer_id_to_ranges))
14288            }
14289        };
14290
14291        let transaction_id_prev = buffer.read_with(cx, |b, cx| b.last_transaction_id(cx));
14292        let selections_prev = transaction_id_prev
14293            .and_then(|transaction_id_prev| {
14294                // default to selections as they were after the last edit, if we have them,
14295                // instead of how they are now.
14296                // This will make it so that editing, moving somewhere else, formatting, then undoing the format
14297                // will take you back to where you made the last edit, instead of staying where you scrolled
14298                self.selection_history
14299                    .transaction(transaction_id_prev)
14300                    .map(|t| t.0.clone())
14301            })
14302            .unwrap_or_else(|| {
14303                log::info!("Failed to determine selections from before format. Falling back to selections when format was initiated");
14304                self.selections.disjoint_anchors()
14305            });
14306
14307        let mut timeout = cx.background_executor().timer(FORMAT_TIMEOUT).fuse();
14308        let format = project.update(cx, |project, cx| {
14309            project.format(buffers, target, true, trigger, cx)
14310        });
14311
14312        cx.spawn_in(window, async move |editor, cx| {
14313            let transaction = futures::select_biased! {
14314                transaction = format.log_err().fuse() => transaction,
14315                () = timeout => {
14316                    log::warn!("timed out waiting for formatting");
14317                    None
14318                }
14319            };
14320
14321            buffer
14322                .update(cx, |buffer, cx| {
14323                    if let Some(transaction) = transaction {
14324                        if !buffer.is_singleton() {
14325                            buffer.push_transaction(&transaction.0, cx);
14326                        }
14327                    }
14328                    cx.notify();
14329                })
14330                .ok();
14331
14332            if let Some(transaction_id_now) =
14333                buffer.read_with(cx, |b, cx| b.last_transaction_id(cx))?
14334            {
14335                let has_new_transaction = transaction_id_prev != Some(transaction_id_now);
14336                if has_new_transaction {
14337                    _ = editor.update(cx, |editor, _| {
14338                        editor
14339                            .selection_history
14340                            .insert_transaction(transaction_id_now, selections_prev);
14341                    });
14342                }
14343            }
14344
14345            Ok(())
14346        })
14347    }
14348
14349    fn organize_imports(
14350        &mut self,
14351        _: &OrganizeImports,
14352        window: &mut Window,
14353        cx: &mut Context<Self>,
14354    ) -> Option<Task<Result<()>>> {
14355        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
14356        let project = match &self.project {
14357            Some(project) => project.clone(),
14358            None => return None,
14359        };
14360        Some(self.perform_code_action_kind(
14361            project,
14362            CodeActionKind::SOURCE_ORGANIZE_IMPORTS,
14363            window,
14364            cx,
14365        ))
14366    }
14367
14368    fn perform_code_action_kind(
14369        &mut self,
14370        project: Entity<Project>,
14371        kind: CodeActionKind,
14372        window: &mut Window,
14373        cx: &mut Context<Self>,
14374    ) -> Task<Result<()>> {
14375        let buffer = self.buffer.clone();
14376        let buffers = buffer.read(cx).all_buffers();
14377        let mut timeout = cx.background_executor().timer(CODE_ACTION_TIMEOUT).fuse();
14378        let apply_action = project.update(cx, |project, cx| {
14379            project.apply_code_action_kind(buffers, kind, true, cx)
14380        });
14381        cx.spawn_in(window, async move |_, cx| {
14382            let transaction = futures::select_biased! {
14383                () = timeout => {
14384                    log::warn!("timed out waiting for executing code action");
14385                    None
14386                }
14387                transaction = apply_action.log_err().fuse() => transaction,
14388            };
14389            buffer
14390                .update(cx, |buffer, cx| {
14391                    // check if we need this
14392                    if let Some(transaction) = transaction {
14393                        if !buffer.is_singleton() {
14394                            buffer.push_transaction(&transaction.0, cx);
14395                        }
14396                    }
14397                    cx.notify();
14398                })
14399                .ok();
14400            Ok(())
14401        })
14402    }
14403
14404    fn restart_language_server(
14405        &mut self,
14406        _: &RestartLanguageServer,
14407        _: &mut Window,
14408        cx: &mut Context<Self>,
14409    ) {
14410        if let Some(project) = self.project.clone() {
14411            self.buffer.update(cx, |multi_buffer, cx| {
14412                project.update(cx, |project, cx| {
14413                    project.restart_language_servers_for_buffers(
14414                        multi_buffer.all_buffers().into_iter().collect(),
14415                        cx,
14416                    );
14417                });
14418            })
14419        }
14420    }
14421
14422    fn stop_language_server(
14423        &mut self,
14424        _: &StopLanguageServer,
14425        _: &mut Window,
14426        cx: &mut Context<Self>,
14427    ) {
14428        if let Some(project) = self.project.clone() {
14429            self.buffer.update(cx, |multi_buffer, cx| {
14430                project.update(cx, |project, cx| {
14431                    project.stop_language_servers_for_buffers(
14432                        multi_buffer.all_buffers().into_iter().collect(),
14433                        cx,
14434                    );
14435                    cx.emit(project::Event::RefreshInlayHints);
14436                });
14437            });
14438        }
14439    }
14440
14441    fn cancel_language_server_work(
14442        workspace: &mut Workspace,
14443        _: &actions::CancelLanguageServerWork,
14444        _: &mut Window,
14445        cx: &mut Context<Workspace>,
14446    ) {
14447        let project = workspace.project();
14448        let buffers = workspace
14449            .active_item(cx)
14450            .and_then(|item| item.act_as::<Editor>(cx))
14451            .map_or(HashSet::default(), |editor| {
14452                editor.read(cx).buffer.read(cx).all_buffers()
14453            });
14454        project.update(cx, |project, cx| {
14455            project.cancel_language_server_work_for_buffers(buffers, cx);
14456        });
14457    }
14458
14459    fn show_character_palette(
14460        &mut self,
14461        _: &ShowCharacterPalette,
14462        window: &mut Window,
14463        _: &mut Context<Self>,
14464    ) {
14465        window.show_character_palette();
14466    }
14467
14468    fn refresh_active_diagnostics(&mut self, cx: &mut Context<Editor>) {
14469        if let ActiveDiagnostic::Group(active_diagnostics) = &mut self.active_diagnostics {
14470            let buffer = self.buffer.read(cx).snapshot(cx);
14471            let primary_range_start = active_diagnostics.active_range.start.to_offset(&buffer);
14472            let primary_range_end = active_diagnostics.active_range.end.to_offset(&buffer);
14473            let is_valid = buffer
14474                .diagnostics_in_range::<usize>(primary_range_start..primary_range_end)
14475                .any(|entry| {
14476                    entry.diagnostic.is_primary
14477                        && !entry.range.is_empty()
14478                        && entry.range.start == primary_range_start
14479                        && entry.diagnostic.message == active_diagnostics.active_message
14480                });
14481
14482            if !is_valid {
14483                self.dismiss_diagnostics(cx);
14484            }
14485        }
14486    }
14487
14488    pub fn active_diagnostic_group(&self) -> Option<&ActiveDiagnosticGroup> {
14489        match &self.active_diagnostics {
14490            ActiveDiagnostic::Group(group) => Some(group),
14491            _ => None,
14492        }
14493    }
14494
14495    pub fn set_all_diagnostics_active(&mut self, cx: &mut Context<Self>) {
14496        self.dismiss_diagnostics(cx);
14497        self.active_diagnostics = ActiveDiagnostic::All;
14498    }
14499
14500    fn activate_diagnostics(
14501        &mut self,
14502        buffer_id: BufferId,
14503        diagnostic: DiagnosticEntry<usize>,
14504        window: &mut Window,
14505        cx: &mut Context<Self>,
14506    ) {
14507        if matches!(self.active_diagnostics, ActiveDiagnostic::All) {
14508            return;
14509        }
14510        self.dismiss_diagnostics(cx);
14511        let snapshot = self.snapshot(window, cx);
14512        let Some(diagnostic_renderer) = cx
14513            .try_global::<GlobalDiagnosticRenderer>()
14514            .map(|g| g.0.clone())
14515        else {
14516            return;
14517        };
14518        let buffer = self.buffer.read(cx).snapshot(cx);
14519
14520        let diagnostic_group = buffer
14521            .diagnostic_group(buffer_id, diagnostic.diagnostic.group_id)
14522            .collect::<Vec<_>>();
14523
14524        let blocks = diagnostic_renderer.render_group(
14525            diagnostic_group,
14526            buffer_id,
14527            snapshot,
14528            cx.weak_entity(),
14529            cx,
14530        );
14531
14532        let blocks = self.display_map.update(cx, |display_map, cx| {
14533            display_map.insert_blocks(blocks, cx).into_iter().collect()
14534        });
14535        self.active_diagnostics = ActiveDiagnostic::Group(ActiveDiagnosticGroup {
14536            active_range: buffer.anchor_before(diagnostic.range.start)
14537                ..buffer.anchor_after(diagnostic.range.end),
14538            active_message: diagnostic.diagnostic.message.clone(),
14539            group_id: diagnostic.diagnostic.group_id,
14540            blocks,
14541        });
14542        cx.notify();
14543    }
14544
14545    fn dismiss_diagnostics(&mut self, cx: &mut Context<Self>) {
14546        if matches!(self.active_diagnostics, ActiveDiagnostic::All) {
14547            return;
14548        };
14549
14550        let prev = mem::replace(&mut self.active_diagnostics, ActiveDiagnostic::None);
14551        if let ActiveDiagnostic::Group(group) = prev {
14552            self.display_map.update(cx, |display_map, cx| {
14553                display_map.remove_blocks(group.blocks, cx);
14554            });
14555            cx.notify();
14556        }
14557    }
14558
14559    /// Disable inline diagnostics rendering for this editor.
14560    pub fn disable_inline_diagnostics(&mut self) {
14561        self.inline_diagnostics_enabled = false;
14562        self.inline_diagnostics_update = Task::ready(());
14563        self.inline_diagnostics.clear();
14564    }
14565
14566    pub fn inline_diagnostics_enabled(&self) -> bool {
14567        self.inline_diagnostics_enabled
14568    }
14569
14570    pub fn show_inline_diagnostics(&self) -> bool {
14571        self.show_inline_diagnostics
14572    }
14573
14574    pub fn toggle_inline_diagnostics(
14575        &mut self,
14576        _: &ToggleInlineDiagnostics,
14577        window: &mut Window,
14578        cx: &mut Context<Editor>,
14579    ) {
14580        self.show_inline_diagnostics = !self.show_inline_diagnostics;
14581        self.refresh_inline_diagnostics(false, window, cx);
14582    }
14583
14584    fn refresh_inline_diagnostics(
14585        &mut self,
14586        debounce: bool,
14587        window: &mut Window,
14588        cx: &mut Context<Self>,
14589    ) {
14590        if !self.inline_diagnostics_enabled || !self.show_inline_diagnostics {
14591            self.inline_diagnostics_update = Task::ready(());
14592            self.inline_diagnostics.clear();
14593            return;
14594        }
14595
14596        let debounce_ms = ProjectSettings::get_global(cx)
14597            .diagnostics
14598            .inline
14599            .update_debounce_ms;
14600        let debounce = if debounce && debounce_ms > 0 {
14601            Some(Duration::from_millis(debounce_ms))
14602        } else {
14603            None
14604        };
14605        self.inline_diagnostics_update = cx.spawn_in(window, async move |editor, cx| {
14606            let editor = editor.upgrade().unwrap();
14607
14608            if let Some(debounce) = debounce {
14609                cx.background_executor().timer(debounce).await;
14610            }
14611            let Some(snapshot) = editor
14612                .update(cx, |editor, cx| editor.buffer().read(cx).snapshot(cx))
14613                .ok()
14614            else {
14615                return;
14616            };
14617
14618            let new_inline_diagnostics = cx
14619                .background_spawn(async move {
14620                    let mut inline_diagnostics = Vec::<(Anchor, InlineDiagnostic)>::new();
14621                    for diagnostic_entry in snapshot.diagnostics_in_range(0..snapshot.len()) {
14622                        let message = diagnostic_entry
14623                            .diagnostic
14624                            .message
14625                            .split_once('\n')
14626                            .map(|(line, _)| line)
14627                            .map(SharedString::new)
14628                            .unwrap_or_else(|| {
14629                                SharedString::from(diagnostic_entry.diagnostic.message)
14630                            });
14631                        let start_anchor = snapshot.anchor_before(diagnostic_entry.range.start);
14632                        let (Ok(i) | Err(i)) = inline_diagnostics
14633                            .binary_search_by(|(probe, _)| probe.cmp(&start_anchor, &snapshot));
14634                        inline_diagnostics.insert(
14635                            i,
14636                            (
14637                                start_anchor,
14638                                InlineDiagnostic {
14639                                    message,
14640                                    group_id: diagnostic_entry.diagnostic.group_id,
14641                                    start: diagnostic_entry.range.start.to_point(&snapshot),
14642                                    is_primary: diagnostic_entry.diagnostic.is_primary,
14643                                    severity: diagnostic_entry.diagnostic.severity,
14644                                },
14645                            ),
14646                        );
14647                    }
14648                    inline_diagnostics
14649                })
14650                .await;
14651
14652            editor
14653                .update(cx, |editor, cx| {
14654                    editor.inline_diagnostics = new_inline_diagnostics;
14655                    cx.notify();
14656                })
14657                .ok();
14658        });
14659    }
14660
14661    pub fn set_selections_from_remote(
14662        &mut self,
14663        selections: Vec<Selection<Anchor>>,
14664        pending_selection: Option<Selection<Anchor>>,
14665        window: &mut Window,
14666        cx: &mut Context<Self>,
14667    ) {
14668        let old_cursor_position = self.selections.newest_anchor().head();
14669        self.selections.change_with(cx, |s| {
14670            s.select_anchors(selections);
14671            if let Some(pending_selection) = pending_selection {
14672                s.set_pending(pending_selection, SelectMode::Character);
14673            } else {
14674                s.clear_pending();
14675            }
14676        });
14677        self.selections_did_change(false, &old_cursor_position, true, window, cx);
14678    }
14679
14680    fn push_to_selection_history(&mut self) {
14681        self.selection_history.push(SelectionHistoryEntry {
14682            selections: self.selections.disjoint_anchors(),
14683            select_next_state: self.select_next_state.clone(),
14684            select_prev_state: self.select_prev_state.clone(),
14685            add_selections_state: self.add_selections_state.clone(),
14686        });
14687    }
14688
14689    pub fn transact(
14690        &mut self,
14691        window: &mut Window,
14692        cx: &mut Context<Self>,
14693        update: impl FnOnce(&mut Self, &mut Window, &mut Context<Self>),
14694    ) -> Option<TransactionId> {
14695        self.start_transaction_at(Instant::now(), window, cx);
14696        update(self, window, cx);
14697        self.end_transaction_at(Instant::now(), cx)
14698    }
14699
14700    pub fn start_transaction_at(
14701        &mut self,
14702        now: Instant,
14703        window: &mut Window,
14704        cx: &mut Context<Self>,
14705    ) {
14706        self.end_selection(window, cx);
14707        if let Some(tx_id) = self
14708            .buffer
14709            .update(cx, |buffer, cx| buffer.start_transaction_at(now, cx))
14710        {
14711            self.selection_history
14712                .insert_transaction(tx_id, self.selections.disjoint_anchors());
14713            cx.emit(EditorEvent::TransactionBegun {
14714                transaction_id: tx_id,
14715            })
14716        }
14717    }
14718
14719    pub fn end_transaction_at(
14720        &mut self,
14721        now: Instant,
14722        cx: &mut Context<Self>,
14723    ) -> Option<TransactionId> {
14724        if let Some(transaction_id) = self
14725            .buffer
14726            .update(cx, |buffer, cx| buffer.end_transaction_at(now, cx))
14727        {
14728            if let Some((_, end_selections)) =
14729                self.selection_history.transaction_mut(transaction_id)
14730            {
14731                *end_selections = Some(self.selections.disjoint_anchors());
14732            } else {
14733                log::error!("unexpectedly ended a transaction that wasn't started by this editor");
14734            }
14735
14736            cx.emit(EditorEvent::Edited { transaction_id });
14737            Some(transaction_id)
14738        } else {
14739            None
14740        }
14741    }
14742
14743    pub fn set_mark(&mut self, _: &actions::SetMark, window: &mut Window, cx: &mut Context<Self>) {
14744        if self.selection_mark_mode {
14745            self.change_selections(None, window, cx, |s| {
14746                s.move_with(|_, sel| {
14747                    sel.collapse_to(sel.head(), SelectionGoal::None);
14748                });
14749            })
14750        }
14751        self.selection_mark_mode = true;
14752        cx.notify();
14753    }
14754
14755    pub fn swap_selection_ends(
14756        &mut self,
14757        _: &actions::SwapSelectionEnds,
14758        window: &mut Window,
14759        cx: &mut Context<Self>,
14760    ) {
14761        self.change_selections(None, window, cx, |s| {
14762            s.move_with(|_, sel| {
14763                if sel.start != sel.end {
14764                    sel.reversed = !sel.reversed
14765                }
14766            });
14767        });
14768        self.request_autoscroll(Autoscroll::newest(), cx);
14769        cx.notify();
14770    }
14771
14772    pub fn toggle_fold(
14773        &mut self,
14774        _: &actions::ToggleFold,
14775        window: &mut Window,
14776        cx: &mut Context<Self>,
14777    ) {
14778        if self.is_singleton(cx) {
14779            let selection = self.selections.newest::<Point>(cx);
14780
14781            let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
14782            let range = if selection.is_empty() {
14783                let point = selection.head().to_display_point(&display_map);
14784                let start = DisplayPoint::new(point.row(), 0).to_point(&display_map);
14785                let end = DisplayPoint::new(point.row(), display_map.line_len(point.row()))
14786                    .to_point(&display_map);
14787                start..end
14788            } else {
14789                selection.range()
14790            };
14791            if display_map.folds_in_range(range).next().is_some() {
14792                self.unfold_lines(&Default::default(), window, cx)
14793            } else {
14794                self.fold(&Default::default(), window, cx)
14795            }
14796        } else {
14797            let multi_buffer_snapshot = self.buffer.read(cx).snapshot(cx);
14798            let buffer_ids: HashSet<_> = self
14799                .selections
14800                .disjoint_anchor_ranges()
14801                .flat_map(|range| multi_buffer_snapshot.buffer_ids_for_range(range))
14802                .collect();
14803
14804            let should_unfold = buffer_ids
14805                .iter()
14806                .any(|buffer_id| self.is_buffer_folded(*buffer_id, cx));
14807
14808            for buffer_id in buffer_ids {
14809                if should_unfold {
14810                    self.unfold_buffer(buffer_id, cx);
14811                } else {
14812                    self.fold_buffer(buffer_id, cx);
14813                }
14814            }
14815        }
14816    }
14817
14818    pub fn toggle_fold_recursive(
14819        &mut self,
14820        _: &actions::ToggleFoldRecursive,
14821        window: &mut Window,
14822        cx: &mut Context<Self>,
14823    ) {
14824        let selection = self.selections.newest::<Point>(cx);
14825
14826        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
14827        let range = if selection.is_empty() {
14828            let point = selection.head().to_display_point(&display_map);
14829            let start = DisplayPoint::new(point.row(), 0).to_point(&display_map);
14830            let end = DisplayPoint::new(point.row(), display_map.line_len(point.row()))
14831                .to_point(&display_map);
14832            start..end
14833        } else {
14834            selection.range()
14835        };
14836        if display_map.folds_in_range(range).next().is_some() {
14837            self.unfold_recursive(&Default::default(), window, cx)
14838        } else {
14839            self.fold_recursive(&Default::default(), window, cx)
14840        }
14841    }
14842
14843    pub fn fold(&mut self, _: &actions::Fold, window: &mut Window, cx: &mut Context<Self>) {
14844        if self.is_singleton(cx) {
14845            let mut to_fold = Vec::new();
14846            let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
14847            let selections = self.selections.all_adjusted(cx);
14848
14849            for selection in selections {
14850                let range = selection.range().sorted();
14851                let buffer_start_row = range.start.row;
14852
14853                if range.start.row != range.end.row {
14854                    let mut found = false;
14855                    let mut row = range.start.row;
14856                    while row <= range.end.row {
14857                        if let Some(crease) = display_map.crease_for_buffer_row(MultiBufferRow(row))
14858                        {
14859                            found = true;
14860                            row = crease.range().end.row + 1;
14861                            to_fold.push(crease);
14862                        } else {
14863                            row += 1
14864                        }
14865                    }
14866                    if found {
14867                        continue;
14868                    }
14869                }
14870
14871                for row in (0..=range.start.row).rev() {
14872                    if let Some(crease) = display_map.crease_for_buffer_row(MultiBufferRow(row)) {
14873                        if crease.range().end.row >= buffer_start_row {
14874                            to_fold.push(crease);
14875                            if row <= range.start.row {
14876                                break;
14877                            }
14878                        }
14879                    }
14880                }
14881            }
14882
14883            self.fold_creases(to_fold, true, window, cx);
14884        } else {
14885            let multi_buffer_snapshot = self.buffer.read(cx).snapshot(cx);
14886            let buffer_ids = self
14887                .selections
14888                .disjoint_anchor_ranges()
14889                .flat_map(|range| multi_buffer_snapshot.buffer_ids_for_range(range))
14890                .collect::<HashSet<_>>();
14891            for buffer_id in buffer_ids {
14892                self.fold_buffer(buffer_id, cx);
14893            }
14894        }
14895    }
14896
14897    fn fold_at_level(
14898        &mut self,
14899        fold_at: &FoldAtLevel,
14900        window: &mut Window,
14901        cx: &mut Context<Self>,
14902    ) {
14903        if !self.buffer.read(cx).is_singleton() {
14904            return;
14905        }
14906
14907        let fold_at_level = fold_at.0;
14908        let snapshot = self.buffer.read(cx).snapshot(cx);
14909        let mut to_fold = Vec::new();
14910        let mut stack = vec![(0, snapshot.max_row().0, 1)];
14911
14912        while let Some((mut start_row, end_row, current_level)) = stack.pop() {
14913            while start_row < end_row {
14914                match self
14915                    .snapshot(window, cx)
14916                    .crease_for_buffer_row(MultiBufferRow(start_row))
14917                {
14918                    Some(crease) => {
14919                        let nested_start_row = crease.range().start.row + 1;
14920                        let nested_end_row = crease.range().end.row;
14921
14922                        if current_level < fold_at_level {
14923                            stack.push((nested_start_row, nested_end_row, current_level + 1));
14924                        } else if current_level == fold_at_level {
14925                            to_fold.push(crease);
14926                        }
14927
14928                        start_row = nested_end_row + 1;
14929                    }
14930                    None => start_row += 1,
14931                }
14932            }
14933        }
14934
14935        self.fold_creases(to_fold, true, window, cx);
14936    }
14937
14938    pub fn fold_all(&mut self, _: &actions::FoldAll, window: &mut Window, cx: &mut Context<Self>) {
14939        if self.buffer.read(cx).is_singleton() {
14940            let mut fold_ranges = Vec::new();
14941            let snapshot = self.buffer.read(cx).snapshot(cx);
14942
14943            for row in 0..snapshot.max_row().0 {
14944                if let Some(foldable_range) = self
14945                    .snapshot(window, cx)
14946                    .crease_for_buffer_row(MultiBufferRow(row))
14947                {
14948                    fold_ranges.push(foldable_range);
14949                }
14950            }
14951
14952            self.fold_creases(fold_ranges, true, window, cx);
14953        } else {
14954            self.toggle_fold_multiple_buffers = cx.spawn_in(window, async move |editor, cx| {
14955                editor
14956                    .update_in(cx, |editor, _, cx| {
14957                        for buffer_id in editor.buffer.read(cx).excerpt_buffer_ids() {
14958                            editor.fold_buffer(buffer_id, cx);
14959                        }
14960                    })
14961                    .ok();
14962            });
14963        }
14964    }
14965
14966    pub fn fold_function_bodies(
14967        &mut self,
14968        _: &actions::FoldFunctionBodies,
14969        window: &mut Window,
14970        cx: &mut Context<Self>,
14971    ) {
14972        let snapshot = self.buffer.read(cx).snapshot(cx);
14973
14974        let ranges = snapshot
14975            .text_object_ranges(0..snapshot.len(), TreeSitterOptions::default())
14976            .filter_map(|(range, obj)| (obj == TextObject::InsideFunction).then_some(range))
14977            .collect::<Vec<_>>();
14978
14979        let creases = ranges
14980            .into_iter()
14981            .map(|range| Crease::simple(range, self.display_map.read(cx).fold_placeholder.clone()))
14982            .collect();
14983
14984        self.fold_creases(creases, true, window, cx);
14985    }
14986
14987    pub fn fold_recursive(
14988        &mut self,
14989        _: &actions::FoldRecursive,
14990        window: &mut Window,
14991        cx: &mut Context<Self>,
14992    ) {
14993        let mut to_fold = Vec::new();
14994        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
14995        let selections = self.selections.all_adjusted(cx);
14996
14997        for selection in selections {
14998            let range = selection.range().sorted();
14999            let buffer_start_row = range.start.row;
15000
15001            if range.start.row != range.end.row {
15002                let mut found = false;
15003                for row in range.start.row..=range.end.row {
15004                    if let Some(crease) = display_map.crease_for_buffer_row(MultiBufferRow(row)) {
15005                        found = true;
15006                        to_fold.push(crease);
15007                    }
15008                }
15009                if found {
15010                    continue;
15011                }
15012            }
15013
15014            for row in (0..=range.start.row).rev() {
15015                if let Some(crease) = display_map.crease_for_buffer_row(MultiBufferRow(row)) {
15016                    if crease.range().end.row >= buffer_start_row {
15017                        to_fold.push(crease);
15018                    } else {
15019                        break;
15020                    }
15021                }
15022            }
15023        }
15024
15025        self.fold_creases(to_fold, true, window, cx);
15026    }
15027
15028    pub fn fold_at(
15029        &mut self,
15030        buffer_row: MultiBufferRow,
15031        window: &mut Window,
15032        cx: &mut Context<Self>,
15033    ) {
15034        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
15035
15036        if let Some(crease) = display_map.crease_for_buffer_row(buffer_row) {
15037            let autoscroll = self
15038                .selections
15039                .all::<Point>(cx)
15040                .iter()
15041                .any(|selection| crease.range().overlaps(&selection.range()));
15042
15043            self.fold_creases(vec![crease], autoscroll, window, cx);
15044        }
15045    }
15046
15047    pub fn unfold_lines(&mut self, _: &UnfoldLines, _window: &mut Window, cx: &mut Context<Self>) {
15048        if self.is_singleton(cx) {
15049            let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
15050            let buffer = &display_map.buffer_snapshot;
15051            let selections = self.selections.all::<Point>(cx);
15052            let ranges = selections
15053                .iter()
15054                .map(|s| {
15055                    let range = s.display_range(&display_map).sorted();
15056                    let mut start = range.start.to_point(&display_map);
15057                    let mut end = range.end.to_point(&display_map);
15058                    start.column = 0;
15059                    end.column = buffer.line_len(MultiBufferRow(end.row));
15060                    start..end
15061                })
15062                .collect::<Vec<_>>();
15063
15064            self.unfold_ranges(&ranges, true, true, cx);
15065        } else {
15066            let multi_buffer_snapshot = self.buffer.read(cx).snapshot(cx);
15067            let buffer_ids = self
15068                .selections
15069                .disjoint_anchor_ranges()
15070                .flat_map(|range| multi_buffer_snapshot.buffer_ids_for_range(range))
15071                .collect::<HashSet<_>>();
15072            for buffer_id in buffer_ids {
15073                self.unfold_buffer(buffer_id, cx);
15074            }
15075        }
15076    }
15077
15078    pub fn unfold_recursive(
15079        &mut self,
15080        _: &UnfoldRecursive,
15081        _window: &mut Window,
15082        cx: &mut Context<Self>,
15083    ) {
15084        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
15085        let selections = self.selections.all::<Point>(cx);
15086        let ranges = selections
15087            .iter()
15088            .map(|s| {
15089                let mut range = s.display_range(&display_map).sorted();
15090                *range.start.column_mut() = 0;
15091                *range.end.column_mut() = display_map.line_len(range.end.row());
15092                let start = range.start.to_point(&display_map);
15093                let end = range.end.to_point(&display_map);
15094                start..end
15095            })
15096            .collect::<Vec<_>>();
15097
15098        self.unfold_ranges(&ranges, true, true, cx);
15099    }
15100
15101    pub fn unfold_at(
15102        &mut self,
15103        buffer_row: MultiBufferRow,
15104        _window: &mut Window,
15105        cx: &mut Context<Self>,
15106    ) {
15107        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
15108
15109        let intersection_range = Point::new(buffer_row.0, 0)
15110            ..Point::new(
15111                buffer_row.0,
15112                display_map.buffer_snapshot.line_len(buffer_row),
15113            );
15114
15115        let autoscroll = self
15116            .selections
15117            .all::<Point>(cx)
15118            .iter()
15119            .any(|selection| RangeExt::overlaps(&selection.range(), &intersection_range));
15120
15121        self.unfold_ranges(&[intersection_range], true, autoscroll, cx);
15122    }
15123
15124    pub fn unfold_all(
15125        &mut self,
15126        _: &actions::UnfoldAll,
15127        _window: &mut Window,
15128        cx: &mut Context<Self>,
15129    ) {
15130        if self.buffer.read(cx).is_singleton() {
15131            let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
15132            self.unfold_ranges(&[0..display_map.buffer_snapshot.len()], true, true, cx);
15133        } else {
15134            self.toggle_fold_multiple_buffers = cx.spawn(async move |editor, cx| {
15135                editor
15136                    .update(cx, |editor, cx| {
15137                        for buffer_id in editor.buffer.read(cx).excerpt_buffer_ids() {
15138                            editor.unfold_buffer(buffer_id, cx);
15139                        }
15140                    })
15141                    .ok();
15142            });
15143        }
15144    }
15145
15146    pub fn fold_selected_ranges(
15147        &mut self,
15148        _: &FoldSelectedRanges,
15149        window: &mut Window,
15150        cx: &mut Context<Self>,
15151    ) {
15152        let selections = self.selections.all_adjusted(cx);
15153        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
15154        let ranges = selections
15155            .into_iter()
15156            .map(|s| Crease::simple(s.range(), display_map.fold_placeholder.clone()))
15157            .collect::<Vec<_>>();
15158        self.fold_creases(ranges, true, window, cx);
15159    }
15160
15161    pub fn fold_ranges<T: ToOffset + Clone>(
15162        &mut self,
15163        ranges: Vec<Range<T>>,
15164        auto_scroll: bool,
15165        window: &mut Window,
15166        cx: &mut Context<Self>,
15167    ) {
15168        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
15169        let ranges = ranges
15170            .into_iter()
15171            .map(|r| Crease::simple(r, display_map.fold_placeholder.clone()))
15172            .collect::<Vec<_>>();
15173        self.fold_creases(ranges, auto_scroll, window, cx);
15174    }
15175
15176    pub fn fold_creases<T: ToOffset + Clone>(
15177        &mut self,
15178        creases: Vec<Crease<T>>,
15179        auto_scroll: bool,
15180        _window: &mut Window,
15181        cx: &mut Context<Self>,
15182    ) {
15183        if creases.is_empty() {
15184            return;
15185        }
15186
15187        let mut buffers_affected = HashSet::default();
15188        let multi_buffer = self.buffer().read(cx);
15189        for crease in &creases {
15190            if let Some((_, buffer, _)) =
15191                multi_buffer.excerpt_containing(crease.range().start.clone(), cx)
15192            {
15193                buffers_affected.insert(buffer.read(cx).remote_id());
15194            };
15195        }
15196
15197        self.display_map.update(cx, |map, cx| map.fold(creases, cx));
15198
15199        if auto_scroll {
15200            self.request_autoscroll(Autoscroll::fit(), cx);
15201        }
15202
15203        cx.notify();
15204
15205        self.scrollbar_marker_state.dirty = true;
15206        self.folds_did_change(cx);
15207    }
15208
15209    /// Removes any folds whose ranges intersect any of the given ranges.
15210    pub fn unfold_ranges<T: ToOffset + Clone>(
15211        &mut self,
15212        ranges: &[Range<T>],
15213        inclusive: bool,
15214        auto_scroll: bool,
15215        cx: &mut Context<Self>,
15216    ) {
15217        self.remove_folds_with(ranges, auto_scroll, cx, |map, cx| {
15218            map.unfold_intersecting(ranges.iter().cloned(), inclusive, cx)
15219        });
15220        self.folds_did_change(cx);
15221    }
15222
15223    pub fn fold_buffer(&mut self, buffer_id: BufferId, cx: &mut Context<Self>) {
15224        if self.buffer().read(cx).is_singleton() || self.is_buffer_folded(buffer_id, cx) {
15225            return;
15226        }
15227        let folded_excerpts = self.buffer().read(cx).excerpts_for_buffer(buffer_id, cx);
15228        self.display_map.update(cx, |display_map, cx| {
15229            display_map.fold_buffers([buffer_id], cx)
15230        });
15231        cx.emit(EditorEvent::BufferFoldToggled {
15232            ids: folded_excerpts.iter().map(|&(id, _)| id).collect(),
15233            folded: true,
15234        });
15235        cx.notify();
15236    }
15237
15238    pub fn unfold_buffer(&mut self, buffer_id: BufferId, cx: &mut Context<Self>) {
15239        if self.buffer().read(cx).is_singleton() || !self.is_buffer_folded(buffer_id, cx) {
15240            return;
15241        }
15242        let unfolded_excerpts = self.buffer().read(cx).excerpts_for_buffer(buffer_id, cx);
15243        self.display_map.update(cx, |display_map, cx| {
15244            display_map.unfold_buffers([buffer_id], cx);
15245        });
15246        cx.emit(EditorEvent::BufferFoldToggled {
15247            ids: unfolded_excerpts.iter().map(|&(id, _)| id).collect(),
15248            folded: false,
15249        });
15250        cx.notify();
15251    }
15252
15253    pub fn is_buffer_folded(&self, buffer: BufferId, cx: &App) -> bool {
15254        self.display_map.read(cx).is_buffer_folded(buffer)
15255    }
15256
15257    pub fn folded_buffers<'a>(&self, cx: &'a App) -> &'a HashSet<BufferId> {
15258        self.display_map.read(cx).folded_buffers()
15259    }
15260
15261    pub fn disable_header_for_buffer(&mut self, buffer_id: BufferId, cx: &mut Context<Self>) {
15262        self.display_map.update(cx, |display_map, cx| {
15263            display_map.disable_header_for_buffer(buffer_id, cx);
15264        });
15265        cx.notify();
15266    }
15267
15268    /// Removes any folds with the given ranges.
15269    pub fn remove_folds_with_type<T: ToOffset + Clone>(
15270        &mut self,
15271        ranges: &[Range<T>],
15272        type_id: TypeId,
15273        auto_scroll: bool,
15274        cx: &mut Context<Self>,
15275    ) {
15276        self.remove_folds_with(ranges, auto_scroll, cx, |map, cx| {
15277            map.remove_folds_with_type(ranges.iter().cloned(), type_id, cx)
15278        });
15279        self.folds_did_change(cx);
15280    }
15281
15282    fn remove_folds_with<T: ToOffset + Clone>(
15283        &mut self,
15284        ranges: &[Range<T>],
15285        auto_scroll: bool,
15286        cx: &mut Context<Self>,
15287        update: impl FnOnce(&mut DisplayMap, &mut Context<DisplayMap>),
15288    ) {
15289        if ranges.is_empty() {
15290            return;
15291        }
15292
15293        let mut buffers_affected = HashSet::default();
15294        let multi_buffer = self.buffer().read(cx);
15295        for range in ranges {
15296            if let Some((_, buffer, _)) = multi_buffer.excerpt_containing(range.start.clone(), cx) {
15297                buffers_affected.insert(buffer.read(cx).remote_id());
15298            };
15299        }
15300
15301        self.display_map.update(cx, update);
15302
15303        if auto_scroll {
15304            self.request_autoscroll(Autoscroll::fit(), cx);
15305        }
15306
15307        cx.notify();
15308        self.scrollbar_marker_state.dirty = true;
15309        self.active_indent_guides_state.dirty = true;
15310    }
15311
15312    pub fn update_fold_widths(
15313        &mut self,
15314        widths: impl IntoIterator<Item = (FoldId, Pixels)>,
15315        cx: &mut Context<Self>,
15316    ) -> bool {
15317        self.display_map
15318            .update(cx, |map, cx| map.update_fold_widths(widths, cx))
15319    }
15320
15321    pub fn default_fold_placeholder(&self, cx: &App) -> FoldPlaceholder {
15322        self.display_map.read(cx).fold_placeholder.clone()
15323    }
15324
15325    pub fn set_expand_all_diff_hunks(&mut self, cx: &mut App) {
15326        self.buffer.update(cx, |buffer, cx| {
15327            buffer.set_all_diff_hunks_expanded(cx);
15328        });
15329    }
15330
15331    pub fn expand_all_diff_hunks(
15332        &mut self,
15333        _: &ExpandAllDiffHunks,
15334        _window: &mut Window,
15335        cx: &mut Context<Self>,
15336    ) {
15337        self.buffer.update(cx, |buffer, cx| {
15338            buffer.expand_diff_hunks(vec![Anchor::min()..Anchor::max()], cx)
15339        });
15340    }
15341
15342    pub fn toggle_selected_diff_hunks(
15343        &mut self,
15344        _: &ToggleSelectedDiffHunks,
15345        _window: &mut Window,
15346        cx: &mut Context<Self>,
15347    ) {
15348        let ranges: Vec<_> = self.selections.disjoint.iter().map(|s| s.range()).collect();
15349        self.toggle_diff_hunks_in_ranges(ranges, cx);
15350    }
15351
15352    pub fn diff_hunks_in_ranges<'a>(
15353        &'a self,
15354        ranges: &'a [Range<Anchor>],
15355        buffer: &'a MultiBufferSnapshot,
15356    ) -> impl 'a + Iterator<Item = MultiBufferDiffHunk> {
15357        ranges.iter().flat_map(move |range| {
15358            let end_excerpt_id = range.end.excerpt_id;
15359            let range = range.to_point(buffer);
15360            let mut peek_end = range.end;
15361            if range.end.row < buffer.max_row().0 {
15362                peek_end = Point::new(range.end.row + 1, 0);
15363            }
15364            buffer
15365                .diff_hunks_in_range(range.start..peek_end)
15366                .filter(move |hunk| hunk.excerpt_id.cmp(&end_excerpt_id, buffer).is_le())
15367        })
15368    }
15369
15370    pub fn has_stageable_diff_hunks_in_ranges(
15371        &self,
15372        ranges: &[Range<Anchor>],
15373        snapshot: &MultiBufferSnapshot,
15374    ) -> bool {
15375        let mut hunks = self.diff_hunks_in_ranges(ranges, &snapshot);
15376        hunks.any(|hunk| hunk.status().has_secondary_hunk())
15377    }
15378
15379    pub fn toggle_staged_selected_diff_hunks(
15380        &mut self,
15381        _: &::git::ToggleStaged,
15382        _: &mut Window,
15383        cx: &mut Context<Self>,
15384    ) {
15385        let snapshot = self.buffer.read(cx).snapshot(cx);
15386        let ranges: Vec<_> = self.selections.disjoint.iter().map(|s| s.range()).collect();
15387        let stage = self.has_stageable_diff_hunks_in_ranges(&ranges, &snapshot);
15388        self.stage_or_unstage_diff_hunks(stage, ranges, cx);
15389    }
15390
15391    pub fn set_render_diff_hunk_controls(
15392        &mut self,
15393        render_diff_hunk_controls: RenderDiffHunkControlsFn,
15394        cx: &mut Context<Self>,
15395    ) {
15396        self.render_diff_hunk_controls = render_diff_hunk_controls;
15397        cx.notify();
15398    }
15399
15400    pub fn stage_and_next(
15401        &mut self,
15402        _: &::git::StageAndNext,
15403        window: &mut Window,
15404        cx: &mut Context<Self>,
15405    ) {
15406        self.do_stage_or_unstage_and_next(true, window, cx);
15407    }
15408
15409    pub fn unstage_and_next(
15410        &mut self,
15411        _: &::git::UnstageAndNext,
15412        window: &mut Window,
15413        cx: &mut Context<Self>,
15414    ) {
15415        self.do_stage_or_unstage_and_next(false, window, cx);
15416    }
15417
15418    pub fn stage_or_unstage_diff_hunks(
15419        &mut self,
15420        stage: bool,
15421        ranges: Vec<Range<Anchor>>,
15422        cx: &mut Context<Self>,
15423    ) {
15424        let task = self.save_buffers_for_ranges_if_needed(&ranges, cx);
15425        cx.spawn(async move |this, cx| {
15426            task.await?;
15427            this.update(cx, |this, cx| {
15428                let snapshot = this.buffer.read(cx).snapshot(cx);
15429                let chunk_by = this
15430                    .diff_hunks_in_ranges(&ranges, &snapshot)
15431                    .chunk_by(|hunk| hunk.buffer_id);
15432                for (buffer_id, hunks) in &chunk_by {
15433                    this.do_stage_or_unstage(stage, buffer_id, hunks, cx);
15434                }
15435            })
15436        })
15437        .detach_and_log_err(cx);
15438    }
15439
15440    fn save_buffers_for_ranges_if_needed(
15441        &mut self,
15442        ranges: &[Range<Anchor>],
15443        cx: &mut Context<Editor>,
15444    ) -> Task<Result<()>> {
15445        let multibuffer = self.buffer.read(cx);
15446        let snapshot = multibuffer.read(cx);
15447        let buffer_ids: HashSet<_> = ranges
15448            .iter()
15449            .flat_map(|range| snapshot.buffer_ids_for_range(range.clone()))
15450            .collect();
15451        drop(snapshot);
15452
15453        let mut buffers = HashSet::default();
15454        for buffer_id in buffer_ids {
15455            if let Some(buffer_entity) = multibuffer.buffer(buffer_id) {
15456                let buffer = buffer_entity.read(cx);
15457                if buffer.file().is_some_and(|file| file.disk_state().exists()) && buffer.is_dirty()
15458                {
15459                    buffers.insert(buffer_entity);
15460                }
15461            }
15462        }
15463
15464        if let Some(project) = &self.project {
15465            project.update(cx, |project, cx| project.save_buffers(buffers, cx))
15466        } else {
15467            Task::ready(Ok(()))
15468        }
15469    }
15470
15471    fn do_stage_or_unstage_and_next(
15472        &mut self,
15473        stage: bool,
15474        window: &mut Window,
15475        cx: &mut Context<Self>,
15476    ) {
15477        let ranges = self.selections.disjoint_anchor_ranges().collect::<Vec<_>>();
15478
15479        if ranges.iter().any(|range| range.start != range.end) {
15480            self.stage_or_unstage_diff_hunks(stage, ranges, cx);
15481            return;
15482        }
15483
15484        self.stage_or_unstage_diff_hunks(stage, ranges, cx);
15485        let snapshot = self.snapshot(window, cx);
15486        let position = self.selections.newest::<Point>(cx).head();
15487        let mut row = snapshot
15488            .buffer_snapshot
15489            .diff_hunks_in_range(position..snapshot.buffer_snapshot.max_point())
15490            .find(|hunk| hunk.row_range.start.0 > position.row)
15491            .map(|hunk| hunk.row_range.start);
15492
15493        let all_diff_hunks_expanded = self.buffer().read(cx).all_diff_hunks_expanded();
15494        // Outside of the project diff editor, wrap around to the beginning.
15495        if !all_diff_hunks_expanded {
15496            row = row.or_else(|| {
15497                snapshot
15498                    .buffer_snapshot
15499                    .diff_hunks_in_range(Point::zero()..position)
15500                    .find(|hunk| hunk.row_range.end.0 < position.row)
15501                    .map(|hunk| hunk.row_range.start)
15502            });
15503        }
15504
15505        if let Some(row) = row {
15506            let destination = Point::new(row.0, 0);
15507            let autoscroll = Autoscroll::center();
15508
15509            self.unfold_ranges(&[destination..destination], false, false, cx);
15510            self.change_selections(Some(autoscroll), window, cx, |s| {
15511                s.select_ranges([destination..destination]);
15512            });
15513        }
15514    }
15515
15516    fn do_stage_or_unstage(
15517        &self,
15518        stage: bool,
15519        buffer_id: BufferId,
15520        hunks: impl Iterator<Item = MultiBufferDiffHunk>,
15521        cx: &mut App,
15522    ) -> Option<()> {
15523        let project = self.project.as_ref()?;
15524        let buffer = project.read(cx).buffer_for_id(buffer_id, cx)?;
15525        let diff = self.buffer.read(cx).diff_for(buffer_id)?;
15526        let buffer_snapshot = buffer.read(cx).snapshot();
15527        let file_exists = buffer_snapshot
15528            .file()
15529            .is_some_and(|file| file.disk_state().exists());
15530        diff.update(cx, |diff, cx| {
15531            diff.stage_or_unstage_hunks(
15532                stage,
15533                &hunks
15534                    .map(|hunk| buffer_diff::DiffHunk {
15535                        buffer_range: hunk.buffer_range,
15536                        diff_base_byte_range: hunk.diff_base_byte_range,
15537                        secondary_status: hunk.secondary_status,
15538                        range: Point::zero()..Point::zero(), // unused
15539                    })
15540                    .collect::<Vec<_>>(),
15541                &buffer_snapshot,
15542                file_exists,
15543                cx,
15544            )
15545        });
15546        None
15547    }
15548
15549    pub fn expand_selected_diff_hunks(&mut self, cx: &mut Context<Self>) {
15550        let ranges: Vec<_> = self.selections.disjoint.iter().map(|s| s.range()).collect();
15551        self.buffer
15552            .update(cx, |buffer, cx| buffer.expand_diff_hunks(ranges, cx))
15553    }
15554
15555    pub fn clear_expanded_diff_hunks(&mut self, cx: &mut Context<Self>) -> bool {
15556        self.buffer.update(cx, |buffer, cx| {
15557            let ranges = vec![Anchor::min()..Anchor::max()];
15558            if !buffer.all_diff_hunks_expanded()
15559                && buffer.has_expanded_diff_hunks_in_ranges(&ranges, cx)
15560            {
15561                buffer.collapse_diff_hunks(ranges, cx);
15562                true
15563            } else {
15564                false
15565            }
15566        })
15567    }
15568
15569    fn toggle_diff_hunks_in_ranges(
15570        &mut self,
15571        ranges: Vec<Range<Anchor>>,
15572        cx: &mut Context<Editor>,
15573    ) {
15574        self.buffer.update(cx, |buffer, cx| {
15575            let expand = !buffer.has_expanded_diff_hunks_in_ranges(&ranges, cx);
15576            buffer.expand_or_collapse_diff_hunks(ranges, expand, cx);
15577        })
15578    }
15579
15580    fn toggle_single_diff_hunk(&mut self, range: Range<Anchor>, cx: &mut Context<Self>) {
15581        self.buffer.update(cx, |buffer, cx| {
15582            let snapshot = buffer.snapshot(cx);
15583            let excerpt_id = range.end.excerpt_id;
15584            let point_range = range.to_point(&snapshot);
15585            let expand = !buffer.single_hunk_is_expanded(range, cx);
15586            buffer.expand_or_collapse_diff_hunks_inner([(point_range, excerpt_id)], expand, cx);
15587        })
15588    }
15589
15590    pub(crate) fn apply_all_diff_hunks(
15591        &mut self,
15592        _: &ApplyAllDiffHunks,
15593        window: &mut Window,
15594        cx: &mut Context<Self>,
15595    ) {
15596        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
15597
15598        let buffers = self.buffer.read(cx).all_buffers();
15599        for branch_buffer in buffers {
15600            branch_buffer.update(cx, |branch_buffer, cx| {
15601                branch_buffer.merge_into_base(Vec::new(), cx);
15602            });
15603        }
15604
15605        if let Some(project) = self.project.clone() {
15606            self.save(true, project, window, cx).detach_and_log_err(cx);
15607        }
15608    }
15609
15610    pub(crate) fn apply_selected_diff_hunks(
15611        &mut self,
15612        _: &ApplyDiffHunk,
15613        window: &mut Window,
15614        cx: &mut Context<Self>,
15615    ) {
15616        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
15617        let snapshot = self.snapshot(window, cx);
15618        let hunks = snapshot.hunks_for_ranges(self.selections.ranges(cx));
15619        let mut ranges_by_buffer = HashMap::default();
15620        self.transact(window, cx, |editor, _window, cx| {
15621            for hunk in hunks {
15622                if let Some(buffer) = editor.buffer.read(cx).buffer(hunk.buffer_id) {
15623                    ranges_by_buffer
15624                        .entry(buffer.clone())
15625                        .or_insert_with(Vec::new)
15626                        .push(hunk.buffer_range.to_offset(buffer.read(cx)));
15627                }
15628            }
15629
15630            for (buffer, ranges) in ranges_by_buffer {
15631                buffer.update(cx, |buffer, cx| {
15632                    buffer.merge_into_base(ranges, cx);
15633                });
15634            }
15635        });
15636
15637        if let Some(project) = self.project.clone() {
15638            self.save(true, project, window, cx).detach_and_log_err(cx);
15639        }
15640    }
15641
15642    pub fn set_gutter_hovered(&mut self, hovered: bool, cx: &mut Context<Self>) {
15643        if hovered != self.gutter_hovered {
15644            self.gutter_hovered = hovered;
15645            cx.notify();
15646        }
15647    }
15648
15649    pub fn insert_blocks(
15650        &mut self,
15651        blocks: impl IntoIterator<Item = BlockProperties<Anchor>>,
15652        autoscroll: Option<Autoscroll>,
15653        cx: &mut Context<Self>,
15654    ) -> Vec<CustomBlockId> {
15655        let blocks = self
15656            .display_map
15657            .update(cx, |display_map, cx| display_map.insert_blocks(blocks, cx));
15658        if let Some(autoscroll) = autoscroll {
15659            self.request_autoscroll(autoscroll, cx);
15660        }
15661        cx.notify();
15662        blocks
15663    }
15664
15665    pub fn resize_blocks(
15666        &mut self,
15667        heights: HashMap<CustomBlockId, u32>,
15668        autoscroll: Option<Autoscroll>,
15669        cx: &mut Context<Self>,
15670    ) {
15671        self.display_map
15672            .update(cx, |display_map, cx| display_map.resize_blocks(heights, cx));
15673        if let Some(autoscroll) = autoscroll {
15674            self.request_autoscroll(autoscroll, cx);
15675        }
15676        cx.notify();
15677    }
15678
15679    pub fn replace_blocks(
15680        &mut self,
15681        renderers: HashMap<CustomBlockId, RenderBlock>,
15682        autoscroll: Option<Autoscroll>,
15683        cx: &mut Context<Self>,
15684    ) {
15685        self.display_map
15686            .update(cx, |display_map, _cx| display_map.replace_blocks(renderers));
15687        if let Some(autoscroll) = autoscroll {
15688            self.request_autoscroll(autoscroll, cx);
15689        }
15690        cx.notify();
15691    }
15692
15693    pub fn remove_blocks(
15694        &mut self,
15695        block_ids: HashSet<CustomBlockId>,
15696        autoscroll: Option<Autoscroll>,
15697        cx: &mut Context<Self>,
15698    ) {
15699        self.display_map.update(cx, |display_map, cx| {
15700            display_map.remove_blocks(block_ids, cx)
15701        });
15702        if let Some(autoscroll) = autoscroll {
15703            self.request_autoscroll(autoscroll, cx);
15704        }
15705        cx.notify();
15706    }
15707
15708    pub fn row_for_block(
15709        &self,
15710        block_id: CustomBlockId,
15711        cx: &mut Context<Self>,
15712    ) -> Option<DisplayRow> {
15713        self.display_map
15714            .update(cx, |map, cx| map.row_for_block(block_id, cx))
15715    }
15716
15717    pub(crate) fn set_focused_block(&mut self, focused_block: FocusedBlock) {
15718        self.focused_block = Some(focused_block);
15719    }
15720
15721    pub(crate) fn take_focused_block(&mut self) -> Option<FocusedBlock> {
15722        self.focused_block.take()
15723    }
15724
15725    pub fn insert_creases(
15726        &mut self,
15727        creases: impl IntoIterator<Item = Crease<Anchor>>,
15728        cx: &mut Context<Self>,
15729    ) -> Vec<CreaseId> {
15730        self.display_map
15731            .update(cx, |map, cx| map.insert_creases(creases, cx))
15732    }
15733
15734    pub fn remove_creases(
15735        &mut self,
15736        ids: impl IntoIterator<Item = CreaseId>,
15737        cx: &mut Context<Self>,
15738    ) {
15739        self.display_map
15740            .update(cx, |map, cx| map.remove_creases(ids, cx));
15741    }
15742
15743    pub fn longest_row(&self, cx: &mut App) -> DisplayRow {
15744        self.display_map
15745            .update(cx, |map, cx| map.snapshot(cx))
15746            .longest_row()
15747    }
15748
15749    pub fn max_point(&self, cx: &mut App) -> DisplayPoint {
15750        self.display_map
15751            .update(cx, |map, cx| map.snapshot(cx))
15752            .max_point()
15753    }
15754
15755    pub fn text(&self, cx: &App) -> String {
15756        self.buffer.read(cx).read(cx).text()
15757    }
15758
15759    pub fn is_empty(&self, cx: &App) -> bool {
15760        self.buffer.read(cx).read(cx).is_empty()
15761    }
15762
15763    pub fn text_option(&self, cx: &App) -> Option<String> {
15764        let text = self.text(cx);
15765        let text = text.trim();
15766
15767        if text.is_empty() {
15768            return None;
15769        }
15770
15771        Some(text.to_string())
15772    }
15773
15774    pub fn set_text(
15775        &mut self,
15776        text: impl Into<Arc<str>>,
15777        window: &mut Window,
15778        cx: &mut Context<Self>,
15779    ) {
15780        self.transact(window, cx, |this, _, cx| {
15781            this.buffer
15782                .read(cx)
15783                .as_singleton()
15784                .expect("you can only call set_text on editors for singleton buffers")
15785                .update(cx, |buffer, cx| buffer.set_text(text, cx));
15786        });
15787    }
15788
15789    pub fn display_text(&self, cx: &mut App) -> String {
15790        self.display_map
15791            .update(cx, |map, cx| map.snapshot(cx))
15792            .text()
15793    }
15794
15795    pub fn wrap_guides(&self, cx: &App) -> SmallVec<[(usize, bool); 2]> {
15796        let mut wrap_guides = smallvec::smallvec![];
15797
15798        if self.show_wrap_guides == Some(false) {
15799            return wrap_guides;
15800        }
15801
15802        let settings = self.buffer.read(cx).language_settings(cx);
15803        if settings.show_wrap_guides {
15804            match self.soft_wrap_mode(cx) {
15805                SoftWrap::Column(soft_wrap) => {
15806                    wrap_guides.push((soft_wrap as usize, true));
15807                }
15808                SoftWrap::Bounded(soft_wrap) => {
15809                    wrap_guides.push((soft_wrap as usize, true));
15810                }
15811                SoftWrap::GitDiff | SoftWrap::None | SoftWrap::EditorWidth => {}
15812            }
15813            wrap_guides.extend(settings.wrap_guides.iter().map(|guide| (*guide, false)))
15814        }
15815
15816        wrap_guides
15817    }
15818
15819    pub fn soft_wrap_mode(&self, cx: &App) -> SoftWrap {
15820        let settings = self.buffer.read(cx).language_settings(cx);
15821        let mode = self.soft_wrap_mode_override.unwrap_or(settings.soft_wrap);
15822        match mode {
15823            language_settings::SoftWrap::PreferLine | language_settings::SoftWrap::None => {
15824                SoftWrap::None
15825            }
15826            language_settings::SoftWrap::EditorWidth => SoftWrap::EditorWidth,
15827            language_settings::SoftWrap::PreferredLineLength => {
15828                SoftWrap::Column(settings.preferred_line_length)
15829            }
15830            language_settings::SoftWrap::Bounded => {
15831                SoftWrap::Bounded(settings.preferred_line_length)
15832            }
15833        }
15834    }
15835
15836    pub fn set_soft_wrap_mode(
15837        &mut self,
15838        mode: language_settings::SoftWrap,
15839
15840        cx: &mut Context<Self>,
15841    ) {
15842        self.soft_wrap_mode_override = Some(mode);
15843        cx.notify();
15844    }
15845
15846    pub fn set_hard_wrap(&mut self, hard_wrap: Option<usize>, cx: &mut Context<Self>) {
15847        self.hard_wrap = hard_wrap;
15848        cx.notify();
15849    }
15850
15851    pub fn set_text_style_refinement(&mut self, style: TextStyleRefinement) {
15852        self.text_style_refinement = Some(style);
15853    }
15854
15855    /// called by the Element so we know what style we were most recently rendered with.
15856    pub(crate) fn set_style(
15857        &mut self,
15858        style: EditorStyle,
15859        window: &mut Window,
15860        cx: &mut Context<Self>,
15861    ) {
15862        let rem_size = window.rem_size();
15863        self.display_map.update(cx, |map, cx| {
15864            map.set_font(
15865                style.text.font(),
15866                style.text.font_size.to_pixels(rem_size),
15867                cx,
15868            )
15869        });
15870        self.style = Some(style);
15871    }
15872
15873    pub fn style(&self) -> Option<&EditorStyle> {
15874        self.style.as_ref()
15875    }
15876
15877    // Called by the element. This method is not designed to be called outside of the editor
15878    // element's layout code because it does not notify when rewrapping is computed synchronously.
15879    pub(crate) fn set_wrap_width(&self, width: Option<Pixels>, cx: &mut App) -> bool {
15880        self.display_map
15881            .update(cx, |map, cx| map.set_wrap_width(width, cx))
15882    }
15883
15884    pub fn set_soft_wrap(&mut self) {
15885        self.soft_wrap_mode_override = Some(language_settings::SoftWrap::EditorWidth)
15886    }
15887
15888    pub fn toggle_soft_wrap(&mut self, _: &ToggleSoftWrap, _: &mut Window, cx: &mut Context<Self>) {
15889        if self.soft_wrap_mode_override.is_some() {
15890            self.soft_wrap_mode_override.take();
15891        } else {
15892            let soft_wrap = match self.soft_wrap_mode(cx) {
15893                SoftWrap::GitDiff => return,
15894                SoftWrap::None => language_settings::SoftWrap::EditorWidth,
15895                SoftWrap::EditorWidth | SoftWrap::Column(_) | SoftWrap::Bounded(_) => {
15896                    language_settings::SoftWrap::None
15897                }
15898            };
15899            self.soft_wrap_mode_override = Some(soft_wrap);
15900        }
15901        cx.notify();
15902    }
15903
15904    pub fn toggle_tab_bar(&mut self, _: &ToggleTabBar, _: &mut Window, cx: &mut Context<Self>) {
15905        let Some(workspace) = self.workspace() else {
15906            return;
15907        };
15908        let fs = workspace.read(cx).app_state().fs.clone();
15909        let current_show = TabBarSettings::get_global(cx).show;
15910        update_settings_file::<TabBarSettings>(fs, cx, move |setting, _| {
15911            setting.show = Some(!current_show);
15912        });
15913    }
15914
15915    pub fn toggle_indent_guides(
15916        &mut self,
15917        _: &ToggleIndentGuides,
15918        _: &mut Window,
15919        cx: &mut Context<Self>,
15920    ) {
15921        let currently_enabled = self.should_show_indent_guides().unwrap_or_else(|| {
15922            self.buffer
15923                .read(cx)
15924                .language_settings(cx)
15925                .indent_guides
15926                .enabled
15927        });
15928        self.show_indent_guides = Some(!currently_enabled);
15929        cx.notify();
15930    }
15931
15932    fn should_show_indent_guides(&self) -> Option<bool> {
15933        self.show_indent_guides
15934    }
15935
15936    pub fn toggle_line_numbers(
15937        &mut self,
15938        _: &ToggleLineNumbers,
15939        _: &mut Window,
15940        cx: &mut Context<Self>,
15941    ) {
15942        let mut editor_settings = EditorSettings::get_global(cx).clone();
15943        editor_settings.gutter.line_numbers = !editor_settings.gutter.line_numbers;
15944        EditorSettings::override_global(editor_settings, cx);
15945    }
15946
15947    pub fn line_numbers_enabled(&self, cx: &App) -> bool {
15948        if let Some(show_line_numbers) = self.show_line_numbers {
15949            return show_line_numbers;
15950        }
15951        EditorSettings::get_global(cx).gutter.line_numbers
15952    }
15953
15954    pub fn should_use_relative_line_numbers(&self, cx: &mut App) -> bool {
15955        self.use_relative_line_numbers
15956            .unwrap_or(EditorSettings::get_global(cx).relative_line_numbers)
15957    }
15958
15959    pub fn toggle_relative_line_numbers(
15960        &mut self,
15961        _: &ToggleRelativeLineNumbers,
15962        _: &mut Window,
15963        cx: &mut Context<Self>,
15964    ) {
15965        let is_relative = self.should_use_relative_line_numbers(cx);
15966        self.set_relative_line_number(Some(!is_relative), cx)
15967    }
15968
15969    pub fn set_relative_line_number(&mut self, is_relative: Option<bool>, cx: &mut Context<Self>) {
15970        self.use_relative_line_numbers = is_relative;
15971        cx.notify();
15972    }
15973
15974    pub fn set_show_gutter(&mut self, show_gutter: bool, cx: &mut Context<Self>) {
15975        self.show_gutter = show_gutter;
15976        cx.notify();
15977    }
15978
15979    pub fn set_show_scrollbars(&mut self, show_scrollbars: bool, cx: &mut Context<Self>) {
15980        self.show_scrollbars = show_scrollbars;
15981        cx.notify();
15982    }
15983
15984    pub fn set_show_line_numbers(&mut self, show_line_numbers: bool, cx: &mut Context<Self>) {
15985        self.show_line_numbers = Some(show_line_numbers);
15986        cx.notify();
15987    }
15988
15989    pub fn set_show_git_diff_gutter(&mut self, show_git_diff_gutter: bool, cx: &mut Context<Self>) {
15990        self.show_git_diff_gutter = Some(show_git_diff_gutter);
15991        cx.notify();
15992    }
15993
15994    pub fn set_show_code_actions(&mut self, show_code_actions: bool, cx: &mut Context<Self>) {
15995        self.show_code_actions = Some(show_code_actions);
15996        cx.notify();
15997    }
15998
15999    pub fn set_show_runnables(&mut self, show_runnables: bool, cx: &mut Context<Self>) {
16000        self.show_runnables = Some(show_runnables);
16001        cx.notify();
16002    }
16003
16004    pub fn set_show_breakpoints(&mut self, show_breakpoints: bool, cx: &mut Context<Self>) {
16005        self.show_breakpoints = Some(show_breakpoints);
16006        cx.notify();
16007    }
16008
16009    pub fn set_masked(&mut self, masked: bool, cx: &mut Context<Self>) {
16010        if self.display_map.read(cx).masked != masked {
16011            self.display_map.update(cx, |map, _| map.masked = masked);
16012        }
16013        cx.notify()
16014    }
16015
16016    pub fn set_show_wrap_guides(&mut self, show_wrap_guides: bool, cx: &mut Context<Self>) {
16017        self.show_wrap_guides = Some(show_wrap_guides);
16018        cx.notify();
16019    }
16020
16021    pub fn set_show_indent_guides(&mut self, show_indent_guides: bool, cx: &mut Context<Self>) {
16022        self.show_indent_guides = Some(show_indent_guides);
16023        cx.notify();
16024    }
16025
16026    pub fn working_directory(&self, cx: &App) -> Option<PathBuf> {
16027        if let Some(buffer) = self.buffer().read(cx).as_singleton() {
16028            if let Some(file) = buffer.read(cx).file().and_then(|f| f.as_local()) {
16029                if let Some(dir) = file.abs_path(cx).parent() {
16030                    return Some(dir.to_owned());
16031                }
16032            }
16033
16034            if let Some(project_path) = buffer.read(cx).project_path(cx) {
16035                return Some(project_path.path.to_path_buf());
16036            }
16037        }
16038
16039        None
16040    }
16041
16042    fn target_file<'a>(&self, cx: &'a App) -> Option<&'a dyn language::LocalFile> {
16043        self.active_excerpt(cx)?
16044            .1
16045            .read(cx)
16046            .file()
16047            .and_then(|f| f.as_local())
16048    }
16049
16050    pub fn target_file_abs_path(&self, cx: &mut Context<Self>) -> Option<PathBuf> {
16051        self.active_excerpt(cx).and_then(|(_, buffer, _)| {
16052            let buffer = buffer.read(cx);
16053            if let Some(project_path) = buffer.project_path(cx) {
16054                let project = self.project.as_ref()?.read(cx);
16055                project.absolute_path(&project_path, cx)
16056            } else {
16057                buffer
16058                    .file()
16059                    .and_then(|file| file.as_local().map(|file| file.abs_path(cx)))
16060            }
16061        })
16062    }
16063
16064    fn target_file_path(&self, cx: &mut Context<Self>) -> Option<PathBuf> {
16065        self.active_excerpt(cx).and_then(|(_, buffer, _)| {
16066            let project_path = buffer.read(cx).project_path(cx)?;
16067            let project = self.project.as_ref()?.read(cx);
16068            let entry = project.entry_for_path(&project_path, cx)?;
16069            let path = entry.path.to_path_buf();
16070            Some(path)
16071        })
16072    }
16073
16074    pub fn reveal_in_finder(
16075        &mut self,
16076        _: &RevealInFileManager,
16077        _window: &mut Window,
16078        cx: &mut Context<Self>,
16079    ) {
16080        if let Some(target) = self.target_file(cx) {
16081            cx.reveal_path(&target.abs_path(cx));
16082        }
16083    }
16084
16085    pub fn copy_path(
16086        &mut self,
16087        _: &zed_actions::workspace::CopyPath,
16088        _window: &mut Window,
16089        cx: &mut Context<Self>,
16090    ) {
16091        if let Some(path) = self.target_file_abs_path(cx) {
16092            if let Some(path) = path.to_str() {
16093                cx.write_to_clipboard(ClipboardItem::new_string(path.to_string()));
16094            }
16095        }
16096    }
16097
16098    pub fn copy_relative_path(
16099        &mut self,
16100        _: &zed_actions::workspace::CopyRelativePath,
16101        _window: &mut Window,
16102        cx: &mut Context<Self>,
16103    ) {
16104        if let Some(path) = self.target_file_path(cx) {
16105            if let Some(path) = path.to_str() {
16106                cx.write_to_clipboard(ClipboardItem::new_string(path.to_string()));
16107            }
16108        }
16109    }
16110
16111    pub fn project_path(&self, cx: &App) -> Option<ProjectPath> {
16112        if let Some(buffer) = self.buffer.read(cx).as_singleton() {
16113            buffer.read(cx).project_path(cx)
16114        } else {
16115            None
16116        }
16117    }
16118
16119    // Returns true if the editor handled a go-to-line request
16120    pub fn go_to_active_debug_line(&mut self, window: &mut Window, cx: &mut Context<Self>) -> bool {
16121        maybe!({
16122            let breakpoint_store = self.breakpoint_store.as_ref()?;
16123
16124            let Some((_, _, active_position)) =
16125                breakpoint_store.read(cx).active_position().cloned()
16126            else {
16127                self.clear_row_highlights::<DebugCurrentRowHighlight>();
16128                return None;
16129            };
16130
16131            let snapshot = self
16132                .project
16133                .as_ref()?
16134                .read(cx)
16135                .buffer_for_id(active_position.buffer_id?, cx)?
16136                .read(cx)
16137                .snapshot();
16138
16139            let mut handled = false;
16140            for (id, ExcerptRange { context, .. }) in self
16141                .buffer
16142                .read(cx)
16143                .excerpts_for_buffer(active_position.buffer_id?, cx)
16144            {
16145                if context.start.cmp(&active_position, &snapshot).is_ge()
16146                    || context.end.cmp(&active_position, &snapshot).is_lt()
16147                {
16148                    continue;
16149                }
16150                let snapshot = self.buffer.read(cx).snapshot(cx);
16151                let multibuffer_anchor = snapshot.anchor_in_excerpt(id, active_position)?;
16152
16153                handled = true;
16154                self.clear_row_highlights::<DebugCurrentRowHighlight>();
16155                self.go_to_line::<DebugCurrentRowHighlight>(
16156                    multibuffer_anchor,
16157                    Some(cx.theme().colors().editor_debugger_active_line_background),
16158                    window,
16159                    cx,
16160                );
16161
16162                cx.notify();
16163            }
16164            handled.then_some(())
16165        })
16166        .is_some()
16167    }
16168
16169    pub fn copy_file_name_without_extension(
16170        &mut self,
16171        _: &CopyFileNameWithoutExtension,
16172        _: &mut Window,
16173        cx: &mut Context<Self>,
16174    ) {
16175        if let Some(file) = self.target_file(cx) {
16176            if let Some(file_stem) = file.path().file_stem() {
16177                if let Some(name) = file_stem.to_str() {
16178                    cx.write_to_clipboard(ClipboardItem::new_string(name.to_string()));
16179                }
16180            }
16181        }
16182    }
16183
16184    pub fn copy_file_name(&mut self, _: &CopyFileName, _: &mut Window, cx: &mut Context<Self>) {
16185        if let Some(file) = self.target_file(cx) {
16186            if let Some(file_name) = file.path().file_name() {
16187                if let Some(name) = file_name.to_str() {
16188                    cx.write_to_clipboard(ClipboardItem::new_string(name.to_string()));
16189                }
16190            }
16191        }
16192    }
16193
16194    pub fn toggle_git_blame(
16195        &mut self,
16196        _: &::git::Blame,
16197        window: &mut Window,
16198        cx: &mut Context<Self>,
16199    ) {
16200        self.show_git_blame_gutter = !self.show_git_blame_gutter;
16201
16202        if self.show_git_blame_gutter && !self.has_blame_entries(cx) {
16203            self.start_git_blame(true, window, cx);
16204        }
16205
16206        cx.notify();
16207    }
16208
16209    pub fn toggle_git_blame_inline(
16210        &mut self,
16211        _: &ToggleGitBlameInline,
16212        window: &mut Window,
16213        cx: &mut Context<Self>,
16214    ) {
16215        self.toggle_git_blame_inline_internal(true, window, cx);
16216        cx.notify();
16217    }
16218
16219    pub fn open_git_blame_commit(
16220        &mut self,
16221        _: &OpenGitBlameCommit,
16222        window: &mut Window,
16223        cx: &mut Context<Self>,
16224    ) {
16225        self.open_git_blame_commit_internal(window, cx);
16226    }
16227
16228    fn open_git_blame_commit_internal(
16229        &mut self,
16230        window: &mut Window,
16231        cx: &mut Context<Self>,
16232    ) -> Option<()> {
16233        let blame = self.blame.as_ref()?;
16234        let snapshot = self.snapshot(window, cx);
16235        let cursor = self.selections.newest::<Point>(cx).head();
16236        let (buffer, point, _) = snapshot.buffer_snapshot.point_to_buffer_point(cursor)?;
16237        let blame_entry = blame
16238            .update(cx, |blame, cx| {
16239                blame
16240                    .blame_for_rows(
16241                        &[RowInfo {
16242                            buffer_id: Some(buffer.remote_id()),
16243                            buffer_row: Some(point.row),
16244                            ..Default::default()
16245                        }],
16246                        cx,
16247                    )
16248                    .next()
16249            })
16250            .flatten()?;
16251        let renderer = cx.global::<GlobalBlameRenderer>().0.clone();
16252        let repo = blame.read(cx).repository(cx)?;
16253        let workspace = self.workspace()?.downgrade();
16254        renderer.open_blame_commit(blame_entry, repo, workspace, window, cx);
16255        None
16256    }
16257
16258    pub fn git_blame_inline_enabled(&self) -> bool {
16259        self.git_blame_inline_enabled
16260    }
16261
16262    pub fn toggle_selection_menu(
16263        &mut self,
16264        _: &ToggleSelectionMenu,
16265        _: &mut Window,
16266        cx: &mut Context<Self>,
16267    ) {
16268        self.show_selection_menu = self
16269            .show_selection_menu
16270            .map(|show_selections_menu| !show_selections_menu)
16271            .or_else(|| Some(!EditorSettings::get_global(cx).toolbar.selections_menu));
16272
16273        cx.notify();
16274    }
16275
16276    pub fn selection_menu_enabled(&self, cx: &App) -> bool {
16277        self.show_selection_menu
16278            .unwrap_or_else(|| EditorSettings::get_global(cx).toolbar.selections_menu)
16279    }
16280
16281    fn start_git_blame(
16282        &mut self,
16283        user_triggered: bool,
16284        window: &mut Window,
16285        cx: &mut Context<Self>,
16286    ) {
16287        if let Some(project) = self.project.as_ref() {
16288            let Some(buffer) = self.buffer().read(cx).as_singleton() else {
16289                return;
16290            };
16291
16292            if buffer.read(cx).file().is_none() {
16293                return;
16294            }
16295
16296            let focused = self.focus_handle(cx).contains_focused(window, cx);
16297
16298            let project = project.clone();
16299            let blame = cx.new(|cx| GitBlame::new(buffer, project, user_triggered, focused, cx));
16300            self.blame_subscription =
16301                Some(cx.observe_in(&blame, window, |_, _, _, cx| cx.notify()));
16302            self.blame = Some(blame);
16303        }
16304    }
16305
16306    fn toggle_git_blame_inline_internal(
16307        &mut self,
16308        user_triggered: bool,
16309        window: &mut Window,
16310        cx: &mut Context<Self>,
16311    ) {
16312        if self.git_blame_inline_enabled {
16313            self.git_blame_inline_enabled = false;
16314            self.show_git_blame_inline = false;
16315            self.show_git_blame_inline_delay_task.take();
16316        } else {
16317            self.git_blame_inline_enabled = true;
16318            self.start_git_blame_inline(user_triggered, window, cx);
16319        }
16320
16321        cx.notify();
16322    }
16323
16324    fn start_git_blame_inline(
16325        &mut self,
16326        user_triggered: bool,
16327        window: &mut Window,
16328        cx: &mut Context<Self>,
16329    ) {
16330        self.start_git_blame(user_triggered, window, cx);
16331
16332        if ProjectSettings::get_global(cx)
16333            .git
16334            .inline_blame_delay()
16335            .is_some()
16336        {
16337            self.start_inline_blame_timer(window, cx);
16338        } else {
16339            self.show_git_blame_inline = true
16340        }
16341    }
16342
16343    pub fn blame(&self) -> Option<&Entity<GitBlame>> {
16344        self.blame.as_ref()
16345    }
16346
16347    pub fn show_git_blame_gutter(&self) -> bool {
16348        self.show_git_blame_gutter
16349    }
16350
16351    pub fn render_git_blame_gutter(&self, cx: &App) -> bool {
16352        self.show_git_blame_gutter && self.has_blame_entries(cx)
16353    }
16354
16355    pub fn render_git_blame_inline(&self, window: &Window, cx: &App) -> bool {
16356        self.show_git_blame_inline
16357            && (self.focus_handle.is_focused(window)
16358                || self
16359                    .git_blame_inline_tooltip
16360                    .as_ref()
16361                    .and_then(|t| t.upgrade())
16362                    .is_some())
16363            && !self.newest_selection_head_on_empty_line(cx)
16364            && self.has_blame_entries(cx)
16365    }
16366
16367    fn has_blame_entries(&self, cx: &App) -> bool {
16368        self.blame()
16369            .map_or(false, |blame| blame.read(cx).has_generated_entries())
16370    }
16371
16372    fn newest_selection_head_on_empty_line(&self, cx: &App) -> bool {
16373        let cursor_anchor = self.selections.newest_anchor().head();
16374
16375        let snapshot = self.buffer.read(cx).snapshot(cx);
16376        let buffer_row = MultiBufferRow(cursor_anchor.to_point(&snapshot).row);
16377
16378        snapshot.line_len(buffer_row) == 0
16379    }
16380
16381    fn get_permalink_to_line(&self, cx: &mut Context<Self>) -> Task<Result<url::Url>> {
16382        let buffer_and_selection = maybe!({
16383            let selection = self.selections.newest::<Point>(cx);
16384            let selection_range = selection.range();
16385
16386            let multi_buffer = self.buffer().read(cx);
16387            let multi_buffer_snapshot = multi_buffer.snapshot(cx);
16388            let buffer_ranges = multi_buffer_snapshot.range_to_buffer_ranges(selection_range);
16389
16390            let (buffer, range, _) = if selection.reversed {
16391                buffer_ranges.first()
16392            } else {
16393                buffer_ranges.last()
16394            }?;
16395
16396            let selection = text::ToPoint::to_point(&range.start, &buffer).row
16397                ..text::ToPoint::to_point(&range.end, &buffer).row;
16398            Some((
16399                multi_buffer.buffer(buffer.remote_id()).unwrap().clone(),
16400                selection,
16401            ))
16402        });
16403
16404        let Some((buffer, selection)) = buffer_and_selection else {
16405            return Task::ready(Err(anyhow!("failed to determine buffer and selection")));
16406        };
16407
16408        let Some(project) = self.project.as_ref() else {
16409            return Task::ready(Err(anyhow!("editor does not have project")));
16410        };
16411
16412        project.update(cx, |project, cx| {
16413            project.get_permalink_to_line(&buffer, selection, cx)
16414        })
16415    }
16416
16417    pub fn copy_permalink_to_line(
16418        &mut self,
16419        _: &CopyPermalinkToLine,
16420        window: &mut Window,
16421        cx: &mut Context<Self>,
16422    ) {
16423        let permalink_task = self.get_permalink_to_line(cx);
16424        let workspace = self.workspace();
16425
16426        cx.spawn_in(window, async move |_, cx| match permalink_task.await {
16427            Ok(permalink) => {
16428                cx.update(|_, cx| {
16429                    cx.write_to_clipboard(ClipboardItem::new_string(permalink.to_string()));
16430                })
16431                .ok();
16432            }
16433            Err(err) => {
16434                let message = format!("Failed to copy permalink: {err}");
16435
16436                Err::<(), anyhow::Error>(err).log_err();
16437
16438                if let Some(workspace) = workspace {
16439                    workspace
16440                        .update_in(cx, |workspace, _, cx| {
16441                            struct CopyPermalinkToLine;
16442
16443                            workspace.show_toast(
16444                                Toast::new(
16445                                    NotificationId::unique::<CopyPermalinkToLine>(),
16446                                    message,
16447                                ),
16448                                cx,
16449                            )
16450                        })
16451                        .ok();
16452                }
16453            }
16454        })
16455        .detach();
16456    }
16457
16458    pub fn copy_file_location(
16459        &mut self,
16460        _: &CopyFileLocation,
16461        _: &mut Window,
16462        cx: &mut Context<Self>,
16463    ) {
16464        let selection = self.selections.newest::<Point>(cx).start.row + 1;
16465        if let Some(file) = self.target_file(cx) {
16466            if let Some(path) = file.path().to_str() {
16467                cx.write_to_clipboard(ClipboardItem::new_string(format!("{path}:{selection}")));
16468            }
16469        }
16470    }
16471
16472    pub fn open_permalink_to_line(
16473        &mut self,
16474        _: &OpenPermalinkToLine,
16475        window: &mut Window,
16476        cx: &mut Context<Self>,
16477    ) {
16478        let permalink_task = self.get_permalink_to_line(cx);
16479        let workspace = self.workspace();
16480
16481        cx.spawn_in(window, async move |_, cx| match permalink_task.await {
16482            Ok(permalink) => {
16483                cx.update(|_, cx| {
16484                    cx.open_url(permalink.as_ref());
16485                })
16486                .ok();
16487            }
16488            Err(err) => {
16489                let message = format!("Failed to open permalink: {err}");
16490
16491                Err::<(), anyhow::Error>(err).log_err();
16492
16493                if let Some(workspace) = workspace {
16494                    workspace
16495                        .update(cx, |workspace, cx| {
16496                            struct OpenPermalinkToLine;
16497
16498                            workspace.show_toast(
16499                                Toast::new(
16500                                    NotificationId::unique::<OpenPermalinkToLine>(),
16501                                    message,
16502                                ),
16503                                cx,
16504                            )
16505                        })
16506                        .ok();
16507                }
16508            }
16509        })
16510        .detach();
16511    }
16512
16513    pub fn insert_uuid_v4(
16514        &mut self,
16515        _: &InsertUuidV4,
16516        window: &mut Window,
16517        cx: &mut Context<Self>,
16518    ) {
16519        self.insert_uuid(UuidVersion::V4, window, cx);
16520    }
16521
16522    pub fn insert_uuid_v7(
16523        &mut self,
16524        _: &InsertUuidV7,
16525        window: &mut Window,
16526        cx: &mut Context<Self>,
16527    ) {
16528        self.insert_uuid(UuidVersion::V7, window, cx);
16529    }
16530
16531    fn insert_uuid(&mut self, version: UuidVersion, window: &mut Window, cx: &mut Context<Self>) {
16532        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
16533        self.transact(window, cx, |this, window, cx| {
16534            let edits = this
16535                .selections
16536                .all::<Point>(cx)
16537                .into_iter()
16538                .map(|selection| {
16539                    let uuid = match version {
16540                        UuidVersion::V4 => uuid::Uuid::new_v4(),
16541                        UuidVersion::V7 => uuid::Uuid::now_v7(),
16542                    };
16543
16544                    (selection.range(), uuid.to_string())
16545                });
16546            this.edit(edits, cx);
16547            this.refresh_inline_completion(true, false, window, cx);
16548        });
16549    }
16550
16551    pub fn open_selections_in_multibuffer(
16552        &mut self,
16553        _: &OpenSelectionsInMultibuffer,
16554        window: &mut Window,
16555        cx: &mut Context<Self>,
16556    ) {
16557        let multibuffer = self.buffer.read(cx);
16558
16559        let Some(buffer) = multibuffer.as_singleton() else {
16560            return;
16561        };
16562
16563        let Some(workspace) = self.workspace() else {
16564            return;
16565        };
16566
16567        let locations = self
16568            .selections
16569            .disjoint_anchors()
16570            .iter()
16571            .map(|range| Location {
16572                buffer: buffer.clone(),
16573                range: range.start.text_anchor..range.end.text_anchor,
16574            })
16575            .collect::<Vec<_>>();
16576
16577        let title = multibuffer.title(cx).to_string();
16578
16579        cx.spawn_in(window, async move |_, cx| {
16580            workspace.update_in(cx, |workspace, window, cx| {
16581                Self::open_locations_in_multibuffer(
16582                    workspace,
16583                    locations,
16584                    format!("Selections for '{title}'"),
16585                    false,
16586                    MultibufferSelectionMode::All,
16587                    window,
16588                    cx,
16589                );
16590            })
16591        })
16592        .detach();
16593    }
16594
16595    /// Adds a row highlight for the given range. If a row has multiple highlights, the
16596    /// last highlight added will be used.
16597    ///
16598    /// If the range ends at the beginning of a line, then that line will not be highlighted.
16599    pub fn highlight_rows<T: 'static>(
16600        &mut self,
16601        range: Range<Anchor>,
16602        color: Hsla,
16603        should_autoscroll: bool,
16604        cx: &mut Context<Self>,
16605    ) {
16606        let snapshot = self.buffer().read(cx).snapshot(cx);
16607        let row_highlights = self.highlighted_rows.entry(TypeId::of::<T>()).or_default();
16608        let ix = row_highlights.binary_search_by(|highlight| {
16609            Ordering::Equal
16610                .then_with(|| highlight.range.start.cmp(&range.start, &snapshot))
16611                .then_with(|| highlight.range.end.cmp(&range.end, &snapshot))
16612        });
16613
16614        if let Err(mut ix) = ix {
16615            let index = post_inc(&mut self.highlight_order);
16616
16617            // If this range intersects with the preceding highlight, then merge it with
16618            // the preceding highlight. Otherwise insert a new highlight.
16619            let mut merged = false;
16620            if ix > 0 {
16621                let prev_highlight = &mut row_highlights[ix - 1];
16622                if prev_highlight
16623                    .range
16624                    .end
16625                    .cmp(&range.start, &snapshot)
16626                    .is_ge()
16627                {
16628                    ix -= 1;
16629                    if prev_highlight.range.end.cmp(&range.end, &snapshot).is_lt() {
16630                        prev_highlight.range.end = range.end;
16631                    }
16632                    merged = true;
16633                    prev_highlight.index = index;
16634                    prev_highlight.color = color;
16635                    prev_highlight.should_autoscroll = should_autoscroll;
16636                }
16637            }
16638
16639            if !merged {
16640                row_highlights.insert(
16641                    ix,
16642                    RowHighlight {
16643                        range: range.clone(),
16644                        index,
16645                        color,
16646                        should_autoscroll,
16647                    },
16648                );
16649            }
16650
16651            // If any of the following highlights intersect with this one, merge them.
16652            while let Some(next_highlight) = row_highlights.get(ix + 1) {
16653                let highlight = &row_highlights[ix];
16654                if next_highlight
16655                    .range
16656                    .start
16657                    .cmp(&highlight.range.end, &snapshot)
16658                    .is_le()
16659                {
16660                    if next_highlight
16661                        .range
16662                        .end
16663                        .cmp(&highlight.range.end, &snapshot)
16664                        .is_gt()
16665                    {
16666                        row_highlights[ix].range.end = next_highlight.range.end;
16667                    }
16668                    row_highlights.remove(ix + 1);
16669                } else {
16670                    break;
16671                }
16672            }
16673        }
16674    }
16675
16676    /// Remove any highlighted row ranges of the given type that intersect the
16677    /// given ranges.
16678    pub fn remove_highlighted_rows<T: 'static>(
16679        &mut self,
16680        ranges_to_remove: Vec<Range<Anchor>>,
16681        cx: &mut Context<Self>,
16682    ) {
16683        let snapshot = self.buffer().read(cx).snapshot(cx);
16684        let row_highlights = self.highlighted_rows.entry(TypeId::of::<T>()).or_default();
16685        let mut ranges_to_remove = ranges_to_remove.iter().peekable();
16686        row_highlights.retain(|highlight| {
16687            while let Some(range_to_remove) = ranges_to_remove.peek() {
16688                match range_to_remove.end.cmp(&highlight.range.start, &snapshot) {
16689                    Ordering::Less | Ordering::Equal => {
16690                        ranges_to_remove.next();
16691                    }
16692                    Ordering::Greater => {
16693                        match range_to_remove.start.cmp(&highlight.range.end, &snapshot) {
16694                            Ordering::Less | Ordering::Equal => {
16695                                return false;
16696                            }
16697                            Ordering::Greater => break,
16698                        }
16699                    }
16700                }
16701            }
16702
16703            true
16704        })
16705    }
16706
16707    /// Clear all anchor ranges for a certain highlight context type, so no corresponding rows will be highlighted.
16708    pub fn clear_row_highlights<T: 'static>(&mut self) {
16709        self.highlighted_rows.remove(&TypeId::of::<T>());
16710    }
16711
16712    /// For a highlight given context type, gets all anchor ranges that will be used for row highlighting.
16713    pub fn highlighted_rows<T: 'static>(&self) -> impl '_ + Iterator<Item = (Range<Anchor>, Hsla)> {
16714        self.highlighted_rows
16715            .get(&TypeId::of::<T>())
16716            .map_or(&[] as &[_], |vec| vec.as_slice())
16717            .iter()
16718            .map(|highlight| (highlight.range.clone(), highlight.color))
16719    }
16720
16721    /// Merges all anchor ranges for all context types ever set, picking the last highlight added in case of a row conflict.
16722    /// Returns a map of display rows that are highlighted and their corresponding highlight color.
16723    /// Allows to ignore certain kinds of highlights.
16724    pub fn highlighted_display_rows(
16725        &self,
16726        window: &mut Window,
16727        cx: &mut App,
16728    ) -> BTreeMap<DisplayRow, LineHighlight> {
16729        let snapshot = self.snapshot(window, cx);
16730        let mut used_highlight_orders = HashMap::default();
16731        self.highlighted_rows
16732            .iter()
16733            .flat_map(|(_, highlighted_rows)| highlighted_rows.iter())
16734            .fold(
16735                BTreeMap::<DisplayRow, LineHighlight>::new(),
16736                |mut unique_rows, highlight| {
16737                    let start = highlight.range.start.to_display_point(&snapshot);
16738                    let end = highlight.range.end.to_display_point(&snapshot);
16739                    let start_row = start.row().0;
16740                    let end_row = if highlight.range.end.text_anchor != text::Anchor::MAX
16741                        && end.column() == 0
16742                    {
16743                        end.row().0.saturating_sub(1)
16744                    } else {
16745                        end.row().0
16746                    };
16747                    for row in start_row..=end_row {
16748                        let used_index =
16749                            used_highlight_orders.entry(row).or_insert(highlight.index);
16750                        if highlight.index >= *used_index {
16751                            *used_index = highlight.index;
16752                            unique_rows.insert(DisplayRow(row), highlight.color.into());
16753                        }
16754                    }
16755                    unique_rows
16756                },
16757            )
16758    }
16759
16760    pub fn highlighted_display_row_for_autoscroll(
16761        &self,
16762        snapshot: &DisplaySnapshot,
16763    ) -> Option<DisplayRow> {
16764        self.highlighted_rows
16765            .values()
16766            .flat_map(|highlighted_rows| highlighted_rows.iter())
16767            .filter_map(|highlight| {
16768                if highlight.should_autoscroll {
16769                    Some(highlight.range.start.to_display_point(snapshot).row())
16770                } else {
16771                    None
16772                }
16773            })
16774            .min()
16775    }
16776
16777    pub fn set_search_within_ranges(&mut self, ranges: &[Range<Anchor>], cx: &mut Context<Self>) {
16778        self.highlight_background::<SearchWithinRange>(
16779            ranges,
16780            |colors| colors.editor_document_highlight_read_background,
16781            cx,
16782        )
16783    }
16784
16785    pub fn set_breadcrumb_header(&mut self, new_header: String) {
16786        self.breadcrumb_header = Some(new_header);
16787    }
16788
16789    pub fn clear_search_within_ranges(&mut self, cx: &mut Context<Self>) {
16790        self.clear_background_highlights::<SearchWithinRange>(cx);
16791    }
16792
16793    pub fn highlight_background<T: 'static>(
16794        &mut self,
16795        ranges: &[Range<Anchor>],
16796        color_fetcher: fn(&ThemeColors) -> Hsla,
16797        cx: &mut Context<Self>,
16798    ) {
16799        self.background_highlights
16800            .insert(TypeId::of::<T>(), (color_fetcher, Arc::from(ranges)));
16801        self.scrollbar_marker_state.dirty = true;
16802        cx.notify();
16803    }
16804
16805    pub fn clear_background_highlights<T: 'static>(
16806        &mut self,
16807        cx: &mut Context<Self>,
16808    ) -> Option<BackgroundHighlight> {
16809        let text_highlights = self.background_highlights.remove(&TypeId::of::<T>())?;
16810        if !text_highlights.1.is_empty() {
16811            self.scrollbar_marker_state.dirty = true;
16812            cx.notify();
16813        }
16814        Some(text_highlights)
16815    }
16816
16817    pub fn highlight_gutter<T: 'static>(
16818        &mut self,
16819        ranges: &[Range<Anchor>],
16820        color_fetcher: fn(&App) -> Hsla,
16821        cx: &mut Context<Self>,
16822    ) {
16823        self.gutter_highlights
16824            .insert(TypeId::of::<T>(), (color_fetcher, Arc::from(ranges)));
16825        cx.notify();
16826    }
16827
16828    pub fn clear_gutter_highlights<T: 'static>(
16829        &mut self,
16830        cx: &mut Context<Self>,
16831    ) -> Option<GutterHighlight> {
16832        cx.notify();
16833        self.gutter_highlights.remove(&TypeId::of::<T>())
16834    }
16835
16836    #[cfg(feature = "test-support")]
16837    pub fn all_text_background_highlights(
16838        &self,
16839        window: &mut Window,
16840        cx: &mut Context<Self>,
16841    ) -> Vec<(Range<DisplayPoint>, Hsla)> {
16842        let snapshot = self.snapshot(window, cx);
16843        let buffer = &snapshot.buffer_snapshot;
16844        let start = buffer.anchor_before(0);
16845        let end = buffer.anchor_after(buffer.len());
16846        let theme = cx.theme().colors();
16847        self.background_highlights_in_range(start..end, &snapshot, theme)
16848    }
16849
16850    #[cfg(feature = "test-support")]
16851    pub fn search_background_highlights(&mut self, cx: &mut Context<Self>) -> Vec<Range<Point>> {
16852        let snapshot = self.buffer().read(cx).snapshot(cx);
16853
16854        let highlights = self
16855            .background_highlights
16856            .get(&TypeId::of::<items::BufferSearchHighlights>());
16857
16858        if let Some((_color, ranges)) = highlights {
16859            ranges
16860                .iter()
16861                .map(|range| range.start.to_point(&snapshot)..range.end.to_point(&snapshot))
16862                .collect_vec()
16863        } else {
16864            vec![]
16865        }
16866    }
16867
16868    fn document_highlights_for_position<'a>(
16869        &'a self,
16870        position: Anchor,
16871        buffer: &'a MultiBufferSnapshot,
16872    ) -> impl 'a + Iterator<Item = &'a Range<Anchor>> {
16873        let read_highlights = self
16874            .background_highlights
16875            .get(&TypeId::of::<DocumentHighlightRead>())
16876            .map(|h| &h.1);
16877        let write_highlights = self
16878            .background_highlights
16879            .get(&TypeId::of::<DocumentHighlightWrite>())
16880            .map(|h| &h.1);
16881        let left_position = position.bias_left(buffer);
16882        let right_position = position.bias_right(buffer);
16883        read_highlights
16884            .into_iter()
16885            .chain(write_highlights)
16886            .flat_map(move |ranges| {
16887                let start_ix = match ranges.binary_search_by(|probe| {
16888                    let cmp = probe.end.cmp(&left_position, buffer);
16889                    if cmp.is_ge() {
16890                        Ordering::Greater
16891                    } else {
16892                        Ordering::Less
16893                    }
16894                }) {
16895                    Ok(i) | Err(i) => i,
16896                };
16897
16898                ranges[start_ix..]
16899                    .iter()
16900                    .take_while(move |range| range.start.cmp(&right_position, buffer).is_le())
16901            })
16902    }
16903
16904    pub fn has_background_highlights<T: 'static>(&self) -> bool {
16905        self.background_highlights
16906            .get(&TypeId::of::<T>())
16907            .map_or(false, |(_, highlights)| !highlights.is_empty())
16908    }
16909
16910    pub fn background_highlights_in_range(
16911        &self,
16912        search_range: Range<Anchor>,
16913        display_snapshot: &DisplaySnapshot,
16914        theme: &ThemeColors,
16915    ) -> Vec<(Range<DisplayPoint>, Hsla)> {
16916        let mut results = Vec::new();
16917        for (color_fetcher, ranges) in self.background_highlights.values() {
16918            let color = color_fetcher(theme);
16919            let start_ix = match ranges.binary_search_by(|probe| {
16920                let cmp = probe
16921                    .end
16922                    .cmp(&search_range.start, &display_snapshot.buffer_snapshot);
16923                if cmp.is_gt() {
16924                    Ordering::Greater
16925                } else {
16926                    Ordering::Less
16927                }
16928            }) {
16929                Ok(i) | Err(i) => i,
16930            };
16931            for range in &ranges[start_ix..] {
16932                if range
16933                    .start
16934                    .cmp(&search_range.end, &display_snapshot.buffer_snapshot)
16935                    .is_ge()
16936                {
16937                    break;
16938                }
16939
16940                let start = range.start.to_display_point(display_snapshot);
16941                let end = range.end.to_display_point(display_snapshot);
16942                results.push((start..end, color))
16943            }
16944        }
16945        results
16946    }
16947
16948    pub fn background_highlight_row_ranges<T: 'static>(
16949        &self,
16950        search_range: Range<Anchor>,
16951        display_snapshot: &DisplaySnapshot,
16952        count: usize,
16953    ) -> Vec<RangeInclusive<DisplayPoint>> {
16954        let mut results = Vec::new();
16955        let Some((_, ranges)) = self.background_highlights.get(&TypeId::of::<T>()) else {
16956            return vec![];
16957        };
16958
16959        let start_ix = match ranges.binary_search_by(|probe| {
16960            let cmp = probe
16961                .end
16962                .cmp(&search_range.start, &display_snapshot.buffer_snapshot);
16963            if cmp.is_gt() {
16964                Ordering::Greater
16965            } else {
16966                Ordering::Less
16967            }
16968        }) {
16969            Ok(i) | Err(i) => i,
16970        };
16971        let mut push_region = |start: Option<Point>, end: Option<Point>| {
16972            if let (Some(start_display), Some(end_display)) = (start, end) {
16973                results.push(
16974                    start_display.to_display_point(display_snapshot)
16975                        ..=end_display.to_display_point(display_snapshot),
16976                );
16977            }
16978        };
16979        let mut start_row: Option<Point> = None;
16980        let mut end_row: Option<Point> = None;
16981        if ranges.len() > count {
16982            return Vec::new();
16983        }
16984        for range in &ranges[start_ix..] {
16985            if range
16986                .start
16987                .cmp(&search_range.end, &display_snapshot.buffer_snapshot)
16988                .is_ge()
16989            {
16990                break;
16991            }
16992            let end = range.end.to_point(&display_snapshot.buffer_snapshot);
16993            if let Some(current_row) = &end_row {
16994                if end.row == current_row.row {
16995                    continue;
16996                }
16997            }
16998            let start = range.start.to_point(&display_snapshot.buffer_snapshot);
16999            if start_row.is_none() {
17000                assert_eq!(end_row, None);
17001                start_row = Some(start);
17002                end_row = Some(end);
17003                continue;
17004            }
17005            if let Some(current_end) = end_row.as_mut() {
17006                if start.row > current_end.row + 1 {
17007                    push_region(start_row, end_row);
17008                    start_row = Some(start);
17009                    end_row = Some(end);
17010                } else {
17011                    // Merge two hunks.
17012                    *current_end = end;
17013                }
17014            } else {
17015                unreachable!();
17016            }
17017        }
17018        // We might still have a hunk that was not rendered (if there was a search hit on the last line)
17019        push_region(start_row, end_row);
17020        results
17021    }
17022
17023    pub fn gutter_highlights_in_range(
17024        &self,
17025        search_range: Range<Anchor>,
17026        display_snapshot: &DisplaySnapshot,
17027        cx: &App,
17028    ) -> Vec<(Range<DisplayPoint>, Hsla)> {
17029        let mut results = Vec::new();
17030        for (color_fetcher, ranges) in self.gutter_highlights.values() {
17031            let color = color_fetcher(cx);
17032            let start_ix = match ranges.binary_search_by(|probe| {
17033                let cmp = probe
17034                    .end
17035                    .cmp(&search_range.start, &display_snapshot.buffer_snapshot);
17036                if cmp.is_gt() {
17037                    Ordering::Greater
17038                } else {
17039                    Ordering::Less
17040                }
17041            }) {
17042                Ok(i) | Err(i) => i,
17043            };
17044            for range in &ranges[start_ix..] {
17045                if range
17046                    .start
17047                    .cmp(&search_range.end, &display_snapshot.buffer_snapshot)
17048                    .is_ge()
17049                {
17050                    break;
17051                }
17052
17053                let start = range.start.to_display_point(display_snapshot);
17054                let end = range.end.to_display_point(display_snapshot);
17055                results.push((start..end, color))
17056            }
17057        }
17058        results
17059    }
17060
17061    /// Get the text ranges corresponding to the redaction query
17062    pub fn redacted_ranges(
17063        &self,
17064        search_range: Range<Anchor>,
17065        display_snapshot: &DisplaySnapshot,
17066        cx: &App,
17067    ) -> Vec<Range<DisplayPoint>> {
17068        display_snapshot
17069            .buffer_snapshot
17070            .redacted_ranges(search_range, |file| {
17071                if let Some(file) = file {
17072                    file.is_private()
17073                        && EditorSettings::get(
17074                            Some(SettingsLocation {
17075                                worktree_id: file.worktree_id(cx),
17076                                path: file.path().as_ref(),
17077                            }),
17078                            cx,
17079                        )
17080                        .redact_private_values
17081                } else {
17082                    false
17083                }
17084            })
17085            .map(|range| {
17086                range.start.to_display_point(display_snapshot)
17087                    ..range.end.to_display_point(display_snapshot)
17088            })
17089            .collect()
17090    }
17091
17092    pub fn highlight_text<T: 'static>(
17093        &mut self,
17094        ranges: Vec<Range<Anchor>>,
17095        style: HighlightStyle,
17096        cx: &mut Context<Self>,
17097    ) {
17098        self.display_map.update(cx, |map, _| {
17099            map.highlight_text(TypeId::of::<T>(), ranges, style)
17100        });
17101        cx.notify();
17102    }
17103
17104    pub(crate) fn highlight_inlays<T: 'static>(
17105        &mut self,
17106        highlights: Vec<InlayHighlight>,
17107        style: HighlightStyle,
17108        cx: &mut Context<Self>,
17109    ) {
17110        self.display_map.update(cx, |map, _| {
17111            map.highlight_inlays(TypeId::of::<T>(), highlights, style)
17112        });
17113        cx.notify();
17114    }
17115
17116    pub fn text_highlights<'a, T: 'static>(
17117        &'a self,
17118        cx: &'a App,
17119    ) -> Option<(HighlightStyle, &'a [Range<Anchor>])> {
17120        self.display_map.read(cx).text_highlights(TypeId::of::<T>())
17121    }
17122
17123    pub fn clear_highlights<T: 'static>(&mut self, cx: &mut Context<Self>) {
17124        let cleared = self
17125            .display_map
17126            .update(cx, |map, _| map.clear_highlights(TypeId::of::<T>()));
17127        if cleared {
17128            cx.notify();
17129        }
17130    }
17131
17132    pub fn show_local_cursors(&self, window: &mut Window, cx: &mut App) -> bool {
17133        (self.read_only(cx) || self.blink_manager.read(cx).visible())
17134            && self.focus_handle.is_focused(window)
17135    }
17136
17137    pub fn set_show_cursor_when_unfocused(&mut self, is_enabled: bool, cx: &mut Context<Self>) {
17138        self.show_cursor_when_unfocused = is_enabled;
17139        cx.notify();
17140    }
17141
17142    fn on_buffer_changed(&mut self, _: Entity<MultiBuffer>, cx: &mut Context<Self>) {
17143        cx.notify();
17144    }
17145
17146    fn on_buffer_event(
17147        &mut self,
17148        multibuffer: &Entity<MultiBuffer>,
17149        event: &multi_buffer::Event,
17150        window: &mut Window,
17151        cx: &mut Context<Self>,
17152    ) {
17153        match event {
17154            multi_buffer::Event::Edited {
17155                singleton_buffer_edited,
17156                edited_buffer: buffer_edited,
17157            } => {
17158                self.scrollbar_marker_state.dirty = true;
17159                self.active_indent_guides_state.dirty = true;
17160                self.refresh_active_diagnostics(cx);
17161                self.refresh_code_actions(window, cx);
17162                if self.has_active_inline_completion() {
17163                    self.update_visible_inline_completion(window, cx);
17164                }
17165                if let Some(buffer) = buffer_edited {
17166                    let buffer_id = buffer.read(cx).remote_id();
17167                    if !self.registered_buffers.contains_key(&buffer_id) {
17168                        if let Some(project) = self.project.as_ref() {
17169                            project.update(cx, |project, cx| {
17170                                self.registered_buffers.insert(
17171                                    buffer_id,
17172                                    project.register_buffer_with_language_servers(&buffer, cx),
17173                                );
17174                            })
17175                        }
17176                    }
17177                }
17178                cx.emit(EditorEvent::BufferEdited);
17179                cx.emit(SearchEvent::MatchesInvalidated);
17180                if *singleton_buffer_edited {
17181                    if let Some(project) = &self.project {
17182                        #[allow(clippy::mutable_key_type)]
17183                        let languages_affected = multibuffer.update(cx, |multibuffer, cx| {
17184                            multibuffer
17185                                .all_buffers()
17186                                .into_iter()
17187                                .filter_map(|buffer| {
17188                                    buffer.update(cx, |buffer, cx| {
17189                                        let language = buffer.language()?;
17190                                        let should_discard = project.update(cx, |project, cx| {
17191                                            project.is_local()
17192                                                && !project.has_language_servers_for(buffer, cx)
17193                                        });
17194                                        should_discard.not().then_some(language.clone())
17195                                    })
17196                                })
17197                                .collect::<HashSet<_>>()
17198                        });
17199                        if !languages_affected.is_empty() {
17200                            self.refresh_inlay_hints(
17201                                InlayHintRefreshReason::BufferEdited(languages_affected),
17202                                cx,
17203                            );
17204                        }
17205                    }
17206                }
17207
17208                let Some(project) = &self.project else { return };
17209                let (telemetry, is_via_ssh) = {
17210                    let project = project.read(cx);
17211                    let telemetry = project.client().telemetry().clone();
17212                    let is_via_ssh = project.is_via_ssh();
17213                    (telemetry, is_via_ssh)
17214                };
17215                refresh_linked_ranges(self, window, cx);
17216                telemetry.log_edit_event("editor", is_via_ssh);
17217            }
17218            multi_buffer::Event::ExcerptsAdded {
17219                buffer,
17220                predecessor,
17221                excerpts,
17222            } => {
17223                self.tasks_update_task = Some(self.refresh_runnables(window, cx));
17224                let buffer_id = buffer.read(cx).remote_id();
17225                if self.buffer.read(cx).diff_for(buffer_id).is_none() {
17226                    if let Some(project) = &self.project {
17227                        get_uncommitted_diff_for_buffer(
17228                            project,
17229                            [buffer.clone()],
17230                            self.buffer.clone(),
17231                            cx,
17232                        )
17233                        .detach();
17234                    }
17235                }
17236                cx.emit(EditorEvent::ExcerptsAdded {
17237                    buffer: buffer.clone(),
17238                    predecessor: *predecessor,
17239                    excerpts: excerpts.clone(),
17240                });
17241                self.refresh_inlay_hints(InlayHintRefreshReason::NewLinesShown, cx);
17242            }
17243            multi_buffer::Event::ExcerptsRemoved { ids } => {
17244                self.refresh_inlay_hints(InlayHintRefreshReason::ExcerptsRemoved(ids.clone()), cx);
17245                let buffer = self.buffer.read(cx);
17246                self.registered_buffers
17247                    .retain(|buffer_id, _| buffer.buffer(*buffer_id).is_some());
17248                jsx_tag_auto_close::refresh_enabled_in_any_buffer(self, multibuffer, cx);
17249                cx.emit(EditorEvent::ExcerptsRemoved { ids: ids.clone() })
17250            }
17251            multi_buffer::Event::ExcerptsEdited {
17252                excerpt_ids,
17253                buffer_ids,
17254            } => {
17255                self.display_map.update(cx, |map, cx| {
17256                    map.unfold_buffers(buffer_ids.iter().copied(), cx)
17257                });
17258                cx.emit(EditorEvent::ExcerptsEdited {
17259                    ids: excerpt_ids.clone(),
17260                })
17261            }
17262            multi_buffer::Event::ExcerptsExpanded { ids } => {
17263                self.refresh_inlay_hints(InlayHintRefreshReason::NewLinesShown, cx);
17264                cx.emit(EditorEvent::ExcerptsExpanded { ids: ids.clone() })
17265            }
17266            multi_buffer::Event::Reparsed(buffer_id) => {
17267                self.tasks_update_task = Some(self.refresh_runnables(window, cx));
17268                jsx_tag_auto_close::refresh_enabled_in_any_buffer(self, multibuffer, cx);
17269
17270                cx.emit(EditorEvent::Reparsed(*buffer_id));
17271            }
17272            multi_buffer::Event::DiffHunksToggled => {
17273                self.tasks_update_task = Some(self.refresh_runnables(window, cx));
17274            }
17275            multi_buffer::Event::LanguageChanged(buffer_id) => {
17276                linked_editing_ranges::refresh_linked_ranges(self, window, cx);
17277                jsx_tag_auto_close::refresh_enabled_in_any_buffer(self, multibuffer, cx);
17278                cx.emit(EditorEvent::Reparsed(*buffer_id));
17279                cx.notify();
17280            }
17281            multi_buffer::Event::DirtyChanged => cx.emit(EditorEvent::DirtyChanged),
17282            multi_buffer::Event::Saved => cx.emit(EditorEvent::Saved),
17283            multi_buffer::Event::FileHandleChanged
17284            | multi_buffer::Event::Reloaded
17285            | multi_buffer::Event::BufferDiffChanged => cx.emit(EditorEvent::TitleChanged),
17286            multi_buffer::Event::Closed => cx.emit(EditorEvent::Closed),
17287            multi_buffer::Event::DiagnosticsUpdated => {
17288                self.refresh_active_diagnostics(cx);
17289                self.refresh_inline_diagnostics(true, window, cx);
17290                self.scrollbar_marker_state.dirty = true;
17291                cx.notify();
17292            }
17293            _ => {}
17294        };
17295    }
17296
17297    fn on_display_map_changed(
17298        &mut self,
17299        _: Entity<DisplayMap>,
17300        _: &mut Window,
17301        cx: &mut Context<Self>,
17302    ) {
17303        cx.notify();
17304    }
17305
17306    fn settings_changed(&mut self, window: &mut Window, cx: &mut Context<Self>) {
17307        self.tasks_update_task = Some(self.refresh_runnables(window, cx));
17308        self.update_edit_prediction_settings(cx);
17309        self.refresh_inline_completion(true, false, window, cx);
17310        self.refresh_inlay_hints(
17311            InlayHintRefreshReason::SettingsChange(inlay_hint_settings(
17312                self.selections.newest_anchor().head(),
17313                &self.buffer.read(cx).snapshot(cx),
17314                cx,
17315            )),
17316            cx,
17317        );
17318
17319        let old_cursor_shape = self.cursor_shape;
17320
17321        {
17322            let editor_settings = EditorSettings::get_global(cx);
17323            self.scroll_manager.vertical_scroll_margin = editor_settings.vertical_scroll_margin;
17324            self.show_breadcrumbs = editor_settings.toolbar.breadcrumbs;
17325            self.cursor_shape = editor_settings.cursor_shape.unwrap_or_default();
17326            self.hide_mouse_mode = editor_settings.hide_mouse.unwrap_or_default();
17327        }
17328
17329        if old_cursor_shape != self.cursor_shape {
17330            cx.emit(EditorEvent::CursorShapeChanged);
17331        }
17332
17333        let project_settings = ProjectSettings::get_global(cx);
17334        self.serialize_dirty_buffers = project_settings.session.restore_unsaved_buffers;
17335
17336        if self.mode.is_full() {
17337            let show_inline_diagnostics = project_settings.diagnostics.inline.enabled;
17338            let inline_blame_enabled = project_settings.git.inline_blame_enabled();
17339            if self.show_inline_diagnostics != show_inline_diagnostics {
17340                self.show_inline_diagnostics = show_inline_diagnostics;
17341                self.refresh_inline_diagnostics(false, window, cx);
17342            }
17343
17344            if self.git_blame_inline_enabled != inline_blame_enabled {
17345                self.toggle_git_blame_inline_internal(false, window, cx);
17346            }
17347        }
17348
17349        cx.notify();
17350    }
17351
17352    pub fn set_searchable(&mut self, searchable: bool) {
17353        self.searchable = searchable;
17354    }
17355
17356    pub fn searchable(&self) -> bool {
17357        self.searchable
17358    }
17359
17360    fn open_proposed_changes_editor(
17361        &mut self,
17362        _: &OpenProposedChangesEditor,
17363        window: &mut Window,
17364        cx: &mut Context<Self>,
17365    ) {
17366        let Some(workspace) = self.workspace() else {
17367            cx.propagate();
17368            return;
17369        };
17370
17371        let selections = self.selections.all::<usize>(cx);
17372        let multi_buffer = self.buffer.read(cx);
17373        let multi_buffer_snapshot = multi_buffer.snapshot(cx);
17374        let mut new_selections_by_buffer = HashMap::default();
17375        for selection in selections {
17376            for (buffer, range, _) in
17377                multi_buffer_snapshot.range_to_buffer_ranges(selection.start..selection.end)
17378            {
17379                let mut range = range.to_point(buffer);
17380                range.start.column = 0;
17381                range.end.column = buffer.line_len(range.end.row);
17382                new_selections_by_buffer
17383                    .entry(multi_buffer.buffer(buffer.remote_id()).unwrap())
17384                    .or_insert(Vec::new())
17385                    .push(range)
17386            }
17387        }
17388
17389        let proposed_changes_buffers = new_selections_by_buffer
17390            .into_iter()
17391            .map(|(buffer, ranges)| ProposedChangeLocation { buffer, ranges })
17392            .collect::<Vec<_>>();
17393        let proposed_changes_editor = cx.new(|cx| {
17394            ProposedChangesEditor::new(
17395                "Proposed changes",
17396                proposed_changes_buffers,
17397                self.project.clone(),
17398                window,
17399                cx,
17400            )
17401        });
17402
17403        window.defer(cx, move |window, cx| {
17404            workspace.update(cx, |workspace, cx| {
17405                workspace.active_pane().update(cx, |pane, cx| {
17406                    pane.add_item(
17407                        Box::new(proposed_changes_editor),
17408                        true,
17409                        true,
17410                        None,
17411                        window,
17412                        cx,
17413                    );
17414                });
17415            });
17416        });
17417    }
17418
17419    pub fn open_excerpts_in_split(
17420        &mut self,
17421        _: &OpenExcerptsSplit,
17422        window: &mut Window,
17423        cx: &mut Context<Self>,
17424    ) {
17425        self.open_excerpts_common(None, true, window, cx)
17426    }
17427
17428    pub fn open_excerpts(&mut self, _: &OpenExcerpts, window: &mut Window, cx: &mut Context<Self>) {
17429        self.open_excerpts_common(None, false, window, cx)
17430    }
17431
17432    fn open_excerpts_common(
17433        &mut self,
17434        jump_data: Option<JumpData>,
17435        split: bool,
17436        window: &mut Window,
17437        cx: &mut Context<Self>,
17438    ) {
17439        let Some(workspace) = self.workspace() else {
17440            cx.propagate();
17441            return;
17442        };
17443
17444        if self.buffer.read(cx).is_singleton() {
17445            cx.propagate();
17446            return;
17447        }
17448
17449        let mut new_selections_by_buffer = HashMap::default();
17450        match &jump_data {
17451            Some(JumpData::MultiBufferPoint {
17452                excerpt_id,
17453                position,
17454                anchor,
17455                line_offset_from_top,
17456            }) => {
17457                let multi_buffer_snapshot = self.buffer.read(cx).snapshot(cx);
17458                if let Some(buffer) = multi_buffer_snapshot
17459                    .buffer_id_for_excerpt(*excerpt_id)
17460                    .and_then(|buffer_id| self.buffer.read(cx).buffer(buffer_id))
17461                {
17462                    let buffer_snapshot = buffer.read(cx).snapshot();
17463                    let jump_to_point = if buffer_snapshot.can_resolve(anchor) {
17464                        language::ToPoint::to_point(anchor, &buffer_snapshot)
17465                    } else {
17466                        buffer_snapshot.clip_point(*position, Bias::Left)
17467                    };
17468                    let jump_to_offset = buffer_snapshot.point_to_offset(jump_to_point);
17469                    new_selections_by_buffer.insert(
17470                        buffer,
17471                        (
17472                            vec![jump_to_offset..jump_to_offset],
17473                            Some(*line_offset_from_top),
17474                        ),
17475                    );
17476                }
17477            }
17478            Some(JumpData::MultiBufferRow {
17479                row,
17480                line_offset_from_top,
17481            }) => {
17482                let point = MultiBufferPoint::new(row.0, 0);
17483                if let Some((buffer, buffer_point, _)) =
17484                    self.buffer.read(cx).point_to_buffer_point(point, cx)
17485                {
17486                    let buffer_offset = buffer.read(cx).point_to_offset(buffer_point);
17487                    new_selections_by_buffer
17488                        .entry(buffer)
17489                        .or_insert((Vec::new(), Some(*line_offset_from_top)))
17490                        .0
17491                        .push(buffer_offset..buffer_offset)
17492                }
17493            }
17494            None => {
17495                let selections = self.selections.all::<usize>(cx);
17496                let multi_buffer = self.buffer.read(cx);
17497                for selection in selections {
17498                    for (snapshot, range, _, anchor) in multi_buffer
17499                        .snapshot(cx)
17500                        .range_to_buffer_ranges_with_deleted_hunks(selection.range())
17501                    {
17502                        if let Some(anchor) = anchor {
17503                            // selection is in a deleted hunk
17504                            let Some(buffer_id) = anchor.buffer_id else {
17505                                continue;
17506                            };
17507                            let Some(buffer_handle) = multi_buffer.buffer(buffer_id) else {
17508                                continue;
17509                            };
17510                            let offset = text::ToOffset::to_offset(
17511                                &anchor.text_anchor,
17512                                &buffer_handle.read(cx).snapshot(),
17513                            );
17514                            let range = offset..offset;
17515                            new_selections_by_buffer
17516                                .entry(buffer_handle)
17517                                .or_insert((Vec::new(), None))
17518                                .0
17519                                .push(range)
17520                        } else {
17521                            let Some(buffer_handle) = multi_buffer.buffer(snapshot.remote_id())
17522                            else {
17523                                continue;
17524                            };
17525                            new_selections_by_buffer
17526                                .entry(buffer_handle)
17527                                .or_insert((Vec::new(), None))
17528                                .0
17529                                .push(range)
17530                        }
17531                    }
17532                }
17533            }
17534        }
17535
17536        new_selections_by_buffer
17537            .retain(|buffer, _| Self::can_open_excerpts_in_file(buffer.read(cx).file()));
17538
17539        if new_selections_by_buffer.is_empty() {
17540            return;
17541        }
17542
17543        // We defer the pane interaction because we ourselves are a workspace item
17544        // and activating a new item causes the pane to call a method on us reentrantly,
17545        // which panics if we're on the stack.
17546        window.defer(cx, move |window, cx| {
17547            workspace.update(cx, |workspace, cx| {
17548                let pane = if split {
17549                    workspace.adjacent_pane(window, cx)
17550                } else {
17551                    workspace.active_pane().clone()
17552                };
17553
17554                for (buffer, (ranges, scroll_offset)) in new_selections_by_buffer {
17555                    let editor = buffer
17556                        .read(cx)
17557                        .file()
17558                        .is_none()
17559                        .then(|| {
17560                            // Handle file-less buffers separately: those are not really the project items, so won't have a project path or entity id,
17561                            // so `workspace.open_project_item` will never find them, always opening a new editor.
17562                            // Instead, we try to activate the existing editor in the pane first.
17563                            let (editor, pane_item_index) =
17564                                pane.read(cx).items().enumerate().find_map(|(i, item)| {
17565                                    let editor = item.downcast::<Editor>()?;
17566                                    let singleton_buffer =
17567                                        editor.read(cx).buffer().read(cx).as_singleton()?;
17568                                    if singleton_buffer == buffer {
17569                                        Some((editor, i))
17570                                    } else {
17571                                        None
17572                                    }
17573                                })?;
17574                            pane.update(cx, |pane, cx| {
17575                                pane.activate_item(pane_item_index, true, true, window, cx)
17576                            });
17577                            Some(editor)
17578                        })
17579                        .flatten()
17580                        .unwrap_or_else(|| {
17581                            workspace.open_project_item::<Self>(
17582                                pane.clone(),
17583                                buffer,
17584                                true,
17585                                true,
17586                                window,
17587                                cx,
17588                            )
17589                        });
17590
17591                    editor.update(cx, |editor, cx| {
17592                        let autoscroll = match scroll_offset {
17593                            Some(scroll_offset) => Autoscroll::top_relative(scroll_offset as usize),
17594                            None => Autoscroll::newest(),
17595                        };
17596                        let nav_history = editor.nav_history.take();
17597                        editor.change_selections(Some(autoscroll), window, cx, |s| {
17598                            s.select_ranges(ranges);
17599                        });
17600                        editor.nav_history = nav_history;
17601                    });
17602                }
17603            })
17604        });
17605    }
17606
17607    // For now, don't allow opening excerpts in buffers that aren't backed by
17608    // regular project files.
17609    fn can_open_excerpts_in_file(file: Option<&Arc<dyn language::File>>) -> bool {
17610        file.map_or(true, |file| project::File::from_dyn(Some(file)).is_some())
17611    }
17612
17613    fn marked_text_ranges(&self, cx: &App) -> Option<Vec<Range<OffsetUtf16>>> {
17614        let snapshot = self.buffer.read(cx).read(cx);
17615        let (_, ranges) = self.text_highlights::<InputComposition>(cx)?;
17616        Some(
17617            ranges
17618                .iter()
17619                .map(move |range| {
17620                    range.start.to_offset_utf16(&snapshot)..range.end.to_offset_utf16(&snapshot)
17621                })
17622                .collect(),
17623        )
17624    }
17625
17626    fn selection_replacement_ranges(
17627        &self,
17628        range: Range<OffsetUtf16>,
17629        cx: &mut App,
17630    ) -> Vec<Range<OffsetUtf16>> {
17631        let selections = self.selections.all::<OffsetUtf16>(cx);
17632        let newest_selection = selections
17633            .iter()
17634            .max_by_key(|selection| selection.id)
17635            .unwrap();
17636        let start_delta = range.start.0 as isize - newest_selection.start.0 as isize;
17637        let end_delta = range.end.0 as isize - newest_selection.end.0 as isize;
17638        let snapshot = self.buffer.read(cx).read(cx);
17639        selections
17640            .into_iter()
17641            .map(|mut selection| {
17642                selection.start.0 =
17643                    (selection.start.0 as isize).saturating_add(start_delta) as usize;
17644                selection.end.0 = (selection.end.0 as isize).saturating_add(end_delta) as usize;
17645                snapshot.clip_offset_utf16(selection.start, Bias::Left)
17646                    ..snapshot.clip_offset_utf16(selection.end, Bias::Right)
17647            })
17648            .collect()
17649    }
17650
17651    fn report_editor_event(
17652        &self,
17653        event_type: &'static str,
17654        file_extension: Option<String>,
17655        cx: &App,
17656    ) {
17657        if cfg!(any(test, feature = "test-support")) {
17658            return;
17659        }
17660
17661        let Some(project) = &self.project else { return };
17662
17663        // If None, we are in a file without an extension
17664        let file = self
17665            .buffer
17666            .read(cx)
17667            .as_singleton()
17668            .and_then(|b| b.read(cx).file());
17669        let file_extension = file_extension.or(file
17670            .as_ref()
17671            .and_then(|file| Path::new(file.file_name(cx)).extension())
17672            .and_then(|e| e.to_str())
17673            .map(|a| a.to_string()));
17674
17675        let vim_mode = cx
17676            .global::<SettingsStore>()
17677            .raw_user_settings()
17678            .get("vim_mode")
17679            == Some(&serde_json::Value::Bool(true));
17680
17681        let edit_predictions_provider = all_language_settings(file, cx).edit_predictions.provider;
17682        let copilot_enabled = edit_predictions_provider
17683            == language::language_settings::EditPredictionProvider::Copilot;
17684        let copilot_enabled_for_language = self
17685            .buffer
17686            .read(cx)
17687            .language_settings(cx)
17688            .show_edit_predictions;
17689
17690        let project = project.read(cx);
17691        telemetry::event!(
17692            event_type,
17693            file_extension,
17694            vim_mode,
17695            copilot_enabled,
17696            copilot_enabled_for_language,
17697            edit_predictions_provider,
17698            is_via_ssh = project.is_via_ssh(),
17699        );
17700    }
17701
17702    /// Copy the highlighted chunks to the clipboard as JSON. The format is an array of lines,
17703    /// with each line being an array of {text, highlight} objects.
17704    fn copy_highlight_json(
17705        &mut self,
17706        _: &CopyHighlightJson,
17707        window: &mut Window,
17708        cx: &mut Context<Self>,
17709    ) {
17710        #[derive(Serialize)]
17711        struct Chunk<'a> {
17712            text: String,
17713            highlight: Option<&'a str>,
17714        }
17715
17716        let snapshot = self.buffer.read(cx).snapshot(cx);
17717        let range = self
17718            .selected_text_range(false, window, cx)
17719            .and_then(|selection| {
17720                if selection.range.is_empty() {
17721                    None
17722                } else {
17723                    Some(selection.range)
17724                }
17725            })
17726            .unwrap_or_else(|| 0..snapshot.len());
17727
17728        let chunks = snapshot.chunks(range, true);
17729        let mut lines = Vec::new();
17730        let mut line: VecDeque<Chunk> = VecDeque::new();
17731
17732        let Some(style) = self.style.as_ref() else {
17733            return;
17734        };
17735
17736        for chunk in chunks {
17737            let highlight = chunk
17738                .syntax_highlight_id
17739                .and_then(|id| id.name(&style.syntax));
17740            let mut chunk_lines = chunk.text.split('\n').peekable();
17741            while let Some(text) = chunk_lines.next() {
17742                let mut merged_with_last_token = false;
17743                if let Some(last_token) = line.back_mut() {
17744                    if last_token.highlight == highlight {
17745                        last_token.text.push_str(text);
17746                        merged_with_last_token = true;
17747                    }
17748                }
17749
17750                if !merged_with_last_token {
17751                    line.push_back(Chunk {
17752                        text: text.into(),
17753                        highlight,
17754                    });
17755                }
17756
17757                if chunk_lines.peek().is_some() {
17758                    if line.len() > 1 && line.front().unwrap().text.is_empty() {
17759                        line.pop_front();
17760                    }
17761                    if line.len() > 1 && line.back().unwrap().text.is_empty() {
17762                        line.pop_back();
17763                    }
17764
17765                    lines.push(mem::take(&mut line));
17766                }
17767            }
17768        }
17769
17770        let Some(lines) = serde_json::to_string_pretty(&lines).log_err() else {
17771            return;
17772        };
17773        cx.write_to_clipboard(ClipboardItem::new_string(lines));
17774    }
17775
17776    pub fn open_context_menu(
17777        &mut self,
17778        _: &OpenContextMenu,
17779        window: &mut Window,
17780        cx: &mut Context<Self>,
17781    ) {
17782        self.request_autoscroll(Autoscroll::newest(), cx);
17783        let position = self.selections.newest_display(cx).start;
17784        mouse_context_menu::deploy_context_menu(self, None, position, window, cx);
17785    }
17786
17787    pub fn inlay_hint_cache(&self) -> &InlayHintCache {
17788        &self.inlay_hint_cache
17789    }
17790
17791    pub fn replay_insert_event(
17792        &mut self,
17793        text: &str,
17794        relative_utf16_range: Option<Range<isize>>,
17795        window: &mut Window,
17796        cx: &mut Context<Self>,
17797    ) {
17798        if !self.input_enabled {
17799            cx.emit(EditorEvent::InputIgnored { text: text.into() });
17800            return;
17801        }
17802        if let Some(relative_utf16_range) = relative_utf16_range {
17803            let selections = self.selections.all::<OffsetUtf16>(cx);
17804            self.change_selections(None, window, cx, |s| {
17805                let new_ranges = selections.into_iter().map(|range| {
17806                    let start = OffsetUtf16(
17807                        range
17808                            .head()
17809                            .0
17810                            .saturating_add_signed(relative_utf16_range.start),
17811                    );
17812                    let end = OffsetUtf16(
17813                        range
17814                            .head()
17815                            .0
17816                            .saturating_add_signed(relative_utf16_range.end),
17817                    );
17818                    start..end
17819                });
17820                s.select_ranges(new_ranges);
17821            });
17822        }
17823
17824        self.handle_input(text, window, cx);
17825    }
17826
17827    pub fn supports_inlay_hints(&self, cx: &mut App) -> bool {
17828        let Some(provider) = self.semantics_provider.as_ref() else {
17829            return false;
17830        };
17831
17832        let mut supports = false;
17833        self.buffer().update(cx, |this, cx| {
17834            this.for_each_buffer(|buffer| {
17835                supports |= provider.supports_inlay_hints(buffer, cx);
17836            });
17837        });
17838
17839        supports
17840    }
17841
17842    pub fn is_focused(&self, window: &Window) -> bool {
17843        self.focus_handle.is_focused(window)
17844    }
17845
17846    fn handle_focus(&mut self, window: &mut Window, cx: &mut Context<Self>) {
17847        cx.emit(EditorEvent::Focused);
17848
17849        if let Some(descendant) = self
17850            .last_focused_descendant
17851            .take()
17852            .and_then(|descendant| descendant.upgrade())
17853        {
17854            window.focus(&descendant);
17855        } else {
17856            if let Some(blame) = self.blame.as_ref() {
17857                blame.update(cx, GitBlame::focus)
17858            }
17859
17860            self.blink_manager.update(cx, BlinkManager::enable);
17861            self.show_cursor_names(window, cx);
17862            self.buffer.update(cx, |buffer, cx| {
17863                buffer.finalize_last_transaction(cx);
17864                if self.leader_peer_id.is_none() {
17865                    buffer.set_active_selections(
17866                        &self.selections.disjoint_anchors(),
17867                        self.selections.line_mode,
17868                        self.cursor_shape,
17869                        cx,
17870                    );
17871                }
17872            });
17873        }
17874    }
17875
17876    fn handle_focus_in(&mut self, _: &mut Window, cx: &mut Context<Self>) {
17877        cx.emit(EditorEvent::FocusedIn)
17878    }
17879
17880    fn handle_focus_out(
17881        &mut self,
17882        event: FocusOutEvent,
17883        _window: &mut Window,
17884        cx: &mut Context<Self>,
17885    ) {
17886        if event.blurred != self.focus_handle {
17887            self.last_focused_descendant = Some(event.blurred);
17888        }
17889        self.refresh_inlay_hints(InlayHintRefreshReason::ModifiersChanged(false), cx);
17890    }
17891
17892    pub fn handle_blur(&mut self, window: &mut Window, cx: &mut Context<Self>) {
17893        self.blink_manager.update(cx, BlinkManager::disable);
17894        self.buffer
17895            .update(cx, |buffer, cx| buffer.remove_active_selections(cx));
17896
17897        if let Some(blame) = self.blame.as_ref() {
17898            blame.update(cx, GitBlame::blur)
17899        }
17900        if !self.hover_state.focused(window, cx) {
17901            hide_hover(self, cx);
17902        }
17903        if !self
17904            .context_menu
17905            .borrow()
17906            .as_ref()
17907            .is_some_and(|context_menu| context_menu.focused(window, cx))
17908        {
17909            self.hide_context_menu(window, cx);
17910        }
17911        self.discard_inline_completion(false, cx);
17912        cx.emit(EditorEvent::Blurred);
17913        cx.notify();
17914    }
17915
17916    pub fn register_action<A: Action>(
17917        &mut self,
17918        listener: impl Fn(&A, &mut Window, &mut App) + 'static,
17919    ) -> Subscription {
17920        let id = self.next_editor_action_id.post_inc();
17921        let listener = Arc::new(listener);
17922        self.editor_actions.borrow_mut().insert(
17923            id,
17924            Box::new(move |window, _| {
17925                let listener = listener.clone();
17926                window.on_action(TypeId::of::<A>(), move |action, phase, window, cx| {
17927                    let action = action.downcast_ref().unwrap();
17928                    if phase == DispatchPhase::Bubble {
17929                        listener(action, window, cx)
17930                    }
17931                })
17932            }),
17933        );
17934
17935        let editor_actions = self.editor_actions.clone();
17936        Subscription::new(move || {
17937            editor_actions.borrow_mut().remove(&id);
17938        })
17939    }
17940
17941    pub fn file_header_size(&self) -> u32 {
17942        FILE_HEADER_HEIGHT
17943    }
17944
17945    pub fn restore(
17946        &mut self,
17947        revert_changes: HashMap<BufferId, Vec<(Range<text::Anchor>, Rope)>>,
17948        window: &mut Window,
17949        cx: &mut Context<Self>,
17950    ) {
17951        let workspace = self.workspace();
17952        let project = self.project.as_ref();
17953        let save_tasks = self.buffer().update(cx, |multi_buffer, cx| {
17954            let mut tasks = Vec::new();
17955            for (buffer_id, changes) in revert_changes {
17956                if let Some(buffer) = multi_buffer.buffer(buffer_id) {
17957                    buffer.update(cx, |buffer, cx| {
17958                        buffer.edit(
17959                            changes
17960                                .into_iter()
17961                                .map(|(range, text)| (range, text.to_string())),
17962                            None,
17963                            cx,
17964                        );
17965                    });
17966
17967                    if let Some(project) =
17968                        project.filter(|_| multi_buffer.all_diff_hunks_expanded())
17969                    {
17970                        project.update(cx, |project, cx| {
17971                            tasks.push((buffer.clone(), project.save_buffer(buffer, cx)));
17972                        })
17973                    }
17974                }
17975            }
17976            tasks
17977        });
17978        cx.spawn_in(window, async move |_, cx| {
17979            for (buffer, task) in save_tasks {
17980                let result = task.await;
17981                if result.is_err() {
17982                    let Some(path) = buffer
17983                        .read_with(cx, |buffer, cx| buffer.project_path(cx))
17984                        .ok()
17985                    else {
17986                        continue;
17987                    };
17988                    if let Some((workspace, path)) = workspace.as_ref().zip(path) {
17989                        let Some(task) = cx
17990                            .update_window_entity(&workspace, |workspace, window, cx| {
17991                                workspace
17992                                    .open_path_preview(path, None, false, false, false, window, cx)
17993                            })
17994                            .ok()
17995                        else {
17996                            continue;
17997                        };
17998                        task.await.log_err();
17999                    }
18000                }
18001            }
18002        })
18003        .detach();
18004        self.change_selections(None, window, cx, |selections| selections.refresh());
18005    }
18006
18007    pub fn to_pixel_point(
18008        &self,
18009        source: multi_buffer::Anchor,
18010        editor_snapshot: &EditorSnapshot,
18011        window: &mut Window,
18012    ) -> Option<gpui::Point<Pixels>> {
18013        let source_point = source.to_display_point(editor_snapshot);
18014        self.display_to_pixel_point(source_point, editor_snapshot, window)
18015    }
18016
18017    pub fn display_to_pixel_point(
18018        &self,
18019        source: DisplayPoint,
18020        editor_snapshot: &EditorSnapshot,
18021        window: &mut Window,
18022    ) -> Option<gpui::Point<Pixels>> {
18023        let line_height = self.style()?.text.line_height_in_pixels(window.rem_size());
18024        let text_layout_details = self.text_layout_details(window);
18025        let scroll_top = text_layout_details
18026            .scroll_anchor
18027            .scroll_position(editor_snapshot)
18028            .y;
18029
18030        if source.row().as_f32() < scroll_top.floor() {
18031            return None;
18032        }
18033        let source_x = editor_snapshot.x_for_display_point(source, &text_layout_details);
18034        let source_y = line_height * (source.row().as_f32() - scroll_top);
18035        Some(gpui::Point::new(source_x, source_y))
18036    }
18037
18038    pub fn has_visible_completions_menu(&self) -> bool {
18039        !self.edit_prediction_preview_is_active()
18040            && self.context_menu.borrow().as_ref().map_or(false, |menu| {
18041                menu.visible() && matches!(menu, CodeContextMenu::Completions(_))
18042            })
18043    }
18044
18045    pub fn register_addon<T: Addon>(&mut self, instance: T) {
18046        self.addons
18047            .insert(std::any::TypeId::of::<T>(), Box::new(instance));
18048    }
18049
18050    pub fn unregister_addon<T: Addon>(&mut self) {
18051        self.addons.remove(&std::any::TypeId::of::<T>());
18052    }
18053
18054    pub fn addon<T: Addon>(&self) -> Option<&T> {
18055        let type_id = std::any::TypeId::of::<T>();
18056        self.addons
18057            .get(&type_id)
18058            .and_then(|item| item.to_any().downcast_ref::<T>())
18059    }
18060
18061    fn character_size(&self, window: &mut Window) -> gpui::Size<Pixels> {
18062        let text_layout_details = self.text_layout_details(window);
18063        let style = &text_layout_details.editor_style;
18064        let font_id = window.text_system().resolve_font(&style.text.font());
18065        let font_size = style.text.font_size.to_pixels(window.rem_size());
18066        let line_height = style.text.line_height_in_pixels(window.rem_size());
18067        let em_width = window.text_system().em_width(font_id, font_size).unwrap();
18068
18069        gpui::Size::new(em_width, line_height)
18070    }
18071
18072    pub fn wait_for_diff_to_load(&self) -> Option<Shared<Task<()>>> {
18073        self.load_diff_task.clone()
18074    }
18075
18076    fn read_metadata_from_db(
18077        &mut self,
18078        item_id: u64,
18079        workspace_id: WorkspaceId,
18080        window: &mut Window,
18081        cx: &mut Context<Editor>,
18082    ) {
18083        if self.is_singleton(cx)
18084            && WorkspaceSettings::get(None, cx).restore_on_startup != RestoreOnStartupBehavior::None
18085        {
18086            let buffer_snapshot = OnceCell::new();
18087
18088            if let Some(folds) = DB.get_editor_folds(item_id, workspace_id).log_err() {
18089                if !folds.is_empty() {
18090                    let snapshot =
18091                        buffer_snapshot.get_or_init(|| self.buffer.read(cx).snapshot(cx));
18092                    self.fold_ranges(
18093                        folds
18094                            .into_iter()
18095                            .map(|(start, end)| {
18096                                snapshot.clip_offset(start, Bias::Left)
18097                                    ..snapshot.clip_offset(end, Bias::Right)
18098                            })
18099                            .collect(),
18100                        false,
18101                        window,
18102                        cx,
18103                    );
18104                }
18105            }
18106
18107            if let Some(selections) = DB.get_editor_selections(item_id, workspace_id).log_err() {
18108                if !selections.is_empty() {
18109                    let snapshot =
18110                        buffer_snapshot.get_or_init(|| self.buffer.read(cx).snapshot(cx));
18111                    self.change_selections(None, window, cx, |s| {
18112                        s.select_ranges(selections.into_iter().map(|(start, end)| {
18113                            snapshot.clip_offset(start, Bias::Left)
18114                                ..snapshot.clip_offset(end, Bias::Right)
18115                        }));
18116                    });
18117                }
18118            };
18119        }
18120
18121        self.read_scroll_position_from_db(item_id, workspace_id, window, cx);
18122    }
18123}
18124
18125// Consider user intent and default settings
18126fn choose_completion_range(
18127    completion: &Completion,
18128    intent: CompletionIntent,
18129    buffer: &Entity<Buffer>,
18130    cx: &mut Context<Editor>,
18131) -> Range<usize> {
18132    fn should_replace(
18133        completion: &Completion,
18134        insert_range: &Range<text::Anchor>,
18135        intent: CompletionIntent,
18136        completion_mode_setting: LspInsertMode,
18137        buffer: &Buffer,
18138    ) -> bool {
18139        // specific actions take precedence over settings
18140        match intent {
18141            CompletionIntent::CompleteWithInsert => return false,
18142            CompletionIntent::CompleteWithReplace => return true,
18143            CompletionIntent::Complete | CompletionIntent::Compose => {}
18144        }
18145
18146        match completion_mode_setting {
18147            LspInsertMode::Insert => false,
18148            LspInsertMode::Replace => true,
18149            LspInsertMode::ReplaceSubsequence => {
18150                let mut text_to_replace = buffer.chars_for_range(
18151                    buffer.anchor_before(completion.replace_range.start)
18152                        ..buffer.anchor_after(completion.replace_range.end),
18153                );
18154                let mut completion_text = completion.new_text.chars();
18155
18156                // is `text_to_replace` a subsequence of `completion_text`
18157                text_to_replace
18158                    .all(|needle_ch| completion_text.any(|haystack_ch| haystack_ch == needle_ch))
18159            }
18160            LspInsertMode::ReplaceSuffix => {
18161                let range_after_cursor = insert_range.end..completion.replace_range.end;
18162
18163                let text_after_cursor = buffer
18164                    .text_for_range(
18165                        buffer.anchor_before(range_after_cursor.start)
18166                            ..buffer.anchor_after(range_after_cursor.end),
18167                    )
18168                    .collect::<String>();
18169                completion.new_text.ends_with(&text_after_cursor)
18170            }
18171        }
18172    }
18173
18174    let buffer = buffer.read(cx);
18175
18176    if let CompletionSource::Lsp {
18177        insert_range: Some(insert_range),
18178        ..
18179    } = &completion.source
18180    {
18181        let completion_mode_setting =
18182            language_settings(buffer.language().map(|l| l.name()), buffer.file(), cx)
18183                .completions
18184                .lsp_insert_mode;
18185
18186        if !should_replace(
18187            completion,
18188            &insert_range,
18189            intent,
18190            completion_mode_setting,
18191            buffer,
18192        ) {
18193            return insert_range.to_offset(buffer);
18194        }
18195    }
18196
18197    completion.replace_range.to_offset(buffer)
18198}
18199
18200fn insert_extra_newline_brackets(
18201    buffer: &MultiBufferSnapshot,
18202    range: Range<usize>,
18203    language: &language::LanguageScope,
18204) -> bool {
18205    let leading_whitespace_len = buffer
18206        .reversed_chars_at(range.start)
18207        .take_while(|c| c.is_whitespace() && *c != '\n')
18208        .map(|c| c.len_utf8())
18209        .sum::<usize>();
18210    let trailing_whitespace_len = buffer
18211        .chars_at(range.end)
18212        .take_while(|c| c.is_whitespace() && *c != '\n')
18213        .map(|c| c.len_utf8())
18214        .sum::<usize>();
18215    let range = range.start - leading_whitespace_len..range.end + trailing_whitespace_len;
18216
18217    language.brackets().any(|(pair, enabled)| {
18218        let pair_start = pair.start.trim_end();
18219        let pair_end = pair.end.trim_start();
18220
18221        enabled
18222            && pair.newline
18223            && buffer.contains_str_at(range.end, pair_end)
18224            && buffer.contains_str_at(range.start.saturating_sub(pair_start.len()), pair_start)
18225    })
18226}
18227
18228fn insert_extra_newline_tree_sitter(buffer: &MultiBufferSnapshot, range: Range<usize>) -> bool {
18229    let (buffer, range) = match buffer.range_to_buffer_ranges(range).as_slice() {
18230        [(buffer, range, _)] => (*buffer, range.clone()),
18231        _ => return false,
18232    };
18233    let pair = {
18234        let mut result: Option<BracketMatch> = None;
18235
18236        for pair in buffer
18237            .all_bracket_ranges(range.clone())
18238            .filter(move |pair| {
18239                pair.open_range.start <= range.start && pair.close_range.end >= range.end
18240            })
18241        {
18242            let len = pair.close_range.end - pair.open_range.start;
18243
18244            if let Some(existing) = &result {
18245                let existing_len = existing.close_range.end - existing.open_range.start;
18246                if len > existing_len {
18247                    continue;
18248                }
18249            }
18250
18251            result = Some(pair);
18252        }
18253
18254        result
18255    };
18256    let Some(pair) = pair else {
18257        return false;
18258    };
18259    pair.newline_only
18260        && buffer
18261            .chars_for_range(pair.open_range.end..range.start)
18262            .chain(buffer.chars_for_range(range.end..pair.close_range.start))
18263            .all(|c| c.is_whitespace() && c != '\n')
18264}
18265
18266fn get_uncommitted_diff_for_buffer(
18267    project: &Entity<Project>,
18268    buffers: impl IntoIterator<Item = Entity<Buffer>>,
18269    buffer: Entity<MultiBuffer>,
18270    cx: &mut App,
18271) -> Task<()> {
18272    let mut tasks = Vec::new();
18273    project.update(cx, |project, cx| {
18274        for buffer in buffers {
18275            if project::File::from_dyn(buffer.read(cx).file()).is_some() {
18276                tasks.push(project.open_uncommitted_diff(buffer.clone(), cx))
18277            }
18278        }
18279    });
18280    cx.spawn(async move |cx| {
18281        let diffs = future::join_all(tasks).await;
18282        buffer
18283            .update(cx, |buffer, cx| {
18284                for diff in diffs.into_iter().flatten() {
18285                    buffer.add_diff(diff, cx);
18286                }
18287            })
18288            .ok();
18289    })
18290}
18291
18292fn char_len_with_expanded_tabs(offset: usize, text: &str, tab_size: NonZeroU32) -> usize {
18293    let tab_size = tab_size.get() as usize;
18294    let mut width = offset;
18295
18296    for ch in text.chars() {
18297        width += if ch == '\t' {
18298            tab_size - (width % tab_size)
18299        } else {
18300            1
18301        };
18302    }
18303
18304    width - offset
18305}
18306
18307#[cfg(test)]
18308mod tests {
18309    use super::*;
18310
18311    #[test]
18312    fn test_string_size_with_expanded_tabs() {
18313        let nz = |val| NonZeroU32::new(val).unwrap();
18314        assert_eq!(char_len_with_expanded_tabs(0, "", nz(4)), 0);
18315        assert_eq!(char_len_with_expanded_tabs(0, "hello", nz(4)), 5);
18316        assert_eq!(char_len_with_expanded_tabs(0, "\thello", nz(4)), 9);
18317        assert_eq!(char_len_with_expanded_tabs(0, "abc\tab", nz(4)), 6);
18318        assert_eq!(char_len_with_expanded_tabs(0, "hello\t", nz(4)), 8);
18319        assert_eq!(char_len_with_expanded_tabs(0, "\t\t", nz(8)), 16);
18320        assert_eq!(char_len_with_expanded_tabs(0, "x\t", nz(8)), 8);
18321        assert_eq!(char_len_with_expanded_tabs(7, "x\t", nz(8)), 9);
18322    }
18323}
18324
18325/// Tokenizes a string into runs of text that should stick together, or that is whitespace.
18326struct WordBreakingTokenizer<'a> {
18327    input: &'a str,
18328}
18329
18330impl<'a> WordBreakingTokenizer<'a> {
18331    fn new(input: &'a str) -> Self {
18332        Self { input }
18333    }
18334}
18335
18336fn is_char_ideographic(ch: char) -> bool {
18337    use unicode_script::Script::*;
18338    use unicode_script::UnicodeScript;
18339    matches!(ch.script(), Han | Tangut | Yi)
18340}
18341
18342fn is_grapheme_ideographic(text: &str) -> bool {
18343    text.chars().any(is_char_ideographic)
18344}
18345
18346fn is_grapheme_whitespace(text: &str) -> bool {
18347    text.chars().any(|x| x.is_whitespace())
18348}
18349
18350fn should_stay_with_preceding_ideograph(text: &str) -> bool {
18351    text.chars().next().map_or(false, |ch| {
18352        matches!(ch, '。' | '、' | ',' | '?' | '!' | ':' | ';' | '…')
18353    })
18354}
18355
18356#[derive(PartialEq, Eq, Debug, Clone, Copy)]
18357enum WordBreakToken<'a> {
18358    Word { token: &'a str, grapheme_len: usize },
18359    InlineWhitespace { token: &'a str, grapheme_len: usize },
18360    Newline,
18361}
18362
18363impl<'a> Iterator for WordBreakingTokenizer<'a> {
18364    /// Yields a span, the count of graphemes in the token, and whether it was
18365    /// whitespace. Note that it also breaks at word boundaries.
18366    type Item = WordBreakToken<'a>;
18367
18368    fn next(&mut self) -> Option<Self::Item> {
18369        use unicode_segmentation::UnicodeSegmentation;
18370        if self.input.is_empty() {
18371            return None;
18372        }
18373
18374        let mut iter = self.input.graphemes(true).peekable();
18375        let mut offset = 0;
18376        let mut grapheme_len = 0;
18377        if let Some(first_grapheme) = iter.next() {
18378            let is_newline = first_grapheme == "\n";
18379            let is_whitespace = is_grapheme_whitespace(first_grapheme);
18380            offset += first_grapheme.len();
18381            grapheme_len += 1;
18382            if is_grapheme_ideographic(first_grapheme) && !is_whitespace {
18383                if let Some(grapheme) = iter.peek().copied() {
18384                    if should_stay_with_preceding_ideograph(grapheme) {
18385                        offset += grapheme.len();
18386                        grapheme_len += 1;
18387                    }
18388                }
18389            } else {
18390                let mut words = self.input[offset..].split_word_bound_indices().peekable();
18391                let mut next_word_bound = words.peek().copied();
18392                if next_word_bound.map_or(false, |(i, _)| i == 0) {
18393                    next_word_bound = words.next();
18394                }
18395                while let Some(grapheme) = iter.peek().copied() {
18396                    if next_word_bound.map_or(false, |(i, _)| i == offset) {
18397                        break;
18398                    };
18399                    if is_grapheme_whitespace(grapheme) != is_whitespace
18400                        || (grapheme == "\n") != is_newline
18401                    {
18402                        break;
18403                    };
18404                    offset += grapheme.len();
18405                    grapheme_len += 1;
18406                    iter.next();
18407                }
18408            }
18409            let token = &self.input[..offset];
18410            self.input = &self.input[offset..];
18411            if token == "\n" {
18412                Some(WordBreakToken::Newline)
18413            } else if is_whitespace {
18414                Some(WordBreakToken::InlineWhitespace {
18415                    token,
18416                    grapheme_len,
18417                })
18418            } else {
18419                Some(WordBreakToken::Word {
18420                    token,
18421                    grapheme_len,
18422                })
18423            }
18424        } else {
18425            None
18426        }
18427    }
18428}
18429
18430#[test]
18431fn test_word_breaking_tokenizer() {
18432    let tests: &[(&str, &[WordBreakToken<'static>])] = &[
18433        ("", &[]),
18434        ("  ", &[whitespace("  ", 2)]),
18435        ("Ʒ", &[word("Ʒ", 1)]),
18436        ("Ǽ", &[word("Ǽ", 1)]),
18437        ("", &[word("", 1)]),
18438        ("⋑⋑", &[word("⋑⋑", 2)]),
18439        (
18440            "原理,进而",
18441            &[word("", 1), word("理,", 2), word("", 1), word("", 1)],
18442        ),
18443        (
18444            "hello world",
18445            &[word("hello", 5), whitespace(" ", 1), word("world", 5)],
18446        ),
18447        (
18448            "hello, world",
18449            &[word("hello,", 6), whitespace(" ", 1), word("world", 5)],
18450        ),
18451        (
18452            "  hello world",
18453            &[
18454                whitespace("  ", 2),
18455                word("hello", 5),
18456                whitespace(" ", 1),
18457                word("world", 5),
18458            ],
18459        ),
18460        (
18461            "这是什么 \n 钢笔",
18462            &[
18463                word("", 1),
18464                word("", 1),
18465                word("", 1),
18466                word("", 1),
18467                whitespace(" ", 1),
18468                newline(),
18469                whitespace(" ", 1),
18470                word("", 1),
18471                word("", 1),
18472            ],
18473        ),
18474        (" mutton", &[whitespace("", 1), word("mutton", 6)]),
18475    ];
18476
18477    fn word(token: &'static str, grapheme_len: usize) -> WordBreakToken<'static> {
18478        WordBreakToken::Word {
18479            token,
18480            grapheme_len,
18481        }
18482    }
18483
18484    fn whitespace(token: &'static str, grapheme_len: usize) -> WordBreakToken<'static> {
18485        WordBreakToken::InlineWhitespace {
18486            token,
18487            grapheme_len,
18488        }
18489    }
18490
18491    fn newline() -> WordBreakToken<'static> {
18492        WordBreakToken::Newline
18493    }
18494
18495    for (input, result) in tests {
18496        assert_eq!(
18497            WordBreakingTokenizer::new(input)
18498                .collect::<Vec<_>>()
18499                .as_slice(),
18500            *result,
18501        );
18502    }
18503}
18504
18505fn wrap_with_prefix(
18506    line_prefix: String,
18507    unwrapped_text: String,
18508    wrap_column: usize,
18509    tab_size: NonZeroU32,
18510    preserve_existing_whitespace: bool,
18511) -> String {
18512    let line_prefix_len = char_len_with_expanded_tabs(0, &line_prefix, tab_size);
18513    let mut wrapped_text = String::new();
18514    let mut current_line = line_prefix.clone();
18515
18516    let tokenizer = WordBreakingTokenizer::new(&unwrapped_text);
18517    let mut current_line_len = line_prefix_len;
18518    let mut in_whitespace = false;
18519    for token in tokenizer {
18520        let have_preceding_whitespace = in_whitespace;
18521        match token {
18522            WordBreakToken::Word {
18523                token,
18524                grapheme_len,
18525            } => {
18526                in_whitespace = false;
18527                if current_line_len + grapheme_len > wrap_column
18528                    && current_line_len != line_prefix_len
18529                {
18530                    wrapped_text.push_str(current_line.trim_end());
18531                    wrapped_text.push('\n');
18532                    current_line.truncate(line_prefix.len());
18533                    current_line_len = line_prefix_len;
18534                }
18535                current_line.push_str(token);
18536                current_line_len += grapheme_len;
18537            }
18538            WordBreakToken::InlineWhitespace {
18539                mut token,
18540                mut grapheme_len,
18541            } => {
18542                in_whitespace = true;
18543                if have_preceding_whitespace && !preserve_existing_whitespace {
18544                    continue;
18545                }
18546                if !preserve_existing_whitespace {
18547                    token = " ";
18548                    grapheme_len = 1;
18549                }
18550                if current_line_len + grapheme_len > wrap_column {
18551                    wrapped_text.push_str(current_line.trim_end());
18552                    wrapped_text.push('\n');
18553                    current_line.truncate(line_prefix.len());
18554                    current_line_len = line_prefix_len;
18555                } else if current_line_len != line_prefix_len || preserve_existing_whitespace {
18556                    current_line.push_str(token);
18557                    current_line_len += grapheme_len;
18558                }
18559            }
18560            WordBreakToken::Newline => {
18561                in_whitespace = true;
18562                if preserve_existing_whitespace {
18563                    wrapped_text.push_str(current_line.trim_end());
18564                    wrapped_text.push('\n');
18565                    current_line.truncate(line_prefix.len());
18566                    current_line_len = line_prefix_len;
18567                } else if have_preceding_whitespace {
18568                    continue;
18569                } else if current_line_len + 1 > wrap_column && current_line_len != line_prefix_len
18570                {
18571                    wrapped_text.push_str(current_line.trim_end());
18572                    wrapped_text.push('\n');
18573                    current_line.truncate(line_prefix.len());
18574                    current_line_len = line_prefix_len;
18575                } else if current_line_len != line_prefix_len {
18576                    current_line.push(' ');
18577                    current_line_len += 1;
18578                }
18579            }
18580        }
18581    }
18582
18583    if !current_line.is_empty() {
18584        wrapped_text.push_str(&current_line);
18585    }
18586    wrapped_text
18587}
18588
18589#[test]
18590fn test_wrap_with_prefix() {
18591    assert_eq!(
18592        wrap_with_prefix(
18593            "# ".to_string(),
18594            "abcdefg".to_string(),
18595            4,
18596            NonZeroU32::new(4).unwrap(),
18597            false,
18598        ),
18599        "# abcdefg"
18600    );
18601    assert_eq!(
18602        wrap_with_prefix(
18603            "".to_string(),
18604            "\thello world".to_string(),
18605            8,
18606            NonZeroU32::new(4).unwrap(),
18607            false,
18608        ),
18609        "hello\nworld"
18610    );
18611    assert_eq!(
18612        wrap_with_prefix(
18613            "// ".to_string(),
18614            "xx \nyy zz aa bb cc".to_string(),
18615            12,
18616            NonZeroU32::new(4).unwrap(),
18617            false,
18618        ),
18619        "// xx yy zz\n// aa bb cc"
18620    );
18621    assert_eq!(
18622        wrap_with_prefix(
18623            String::new(),
18624            "这是什么 \n 钢笔".to_string(),
18625            3,
18626            NonZeroU32::new(4).unwrap(),
18627            false,
18628        ),
18629        "这是什\n么 钢\n"
18630    );
18631}
18632
18633pub trait CollaborationHub {
18634    fn collaborators<'a>(&self, cx: &'a App) -> &'a HashMap<PeerId, Collaborator>;
18635    fn user_participant_indices<'a>(&self, cx: &'a App) -> &'a HashMap<u64, ParticipantIndex>;
18636    fn user_names(&self, cx: &App) -> HashMap<u64, SharedString>;
18637}
18638
18639impl CollaborationHub for Entity<Project> {
18640    fn collaborators<'a>(&self, cx: &'a App) -> &'a HashMap<PeerId, Collaborator> {
18641        self.read(cx).collaborators()
18642    }
18643
18644    fn user_participant_indices<'a>(&self, cx: &'a App) -> &'a HashMap<u64, ParticipantIndex> {
18645        self.read(cx).user_store().read(cx).participant_indices()
18646    }
18647
18648    fn user_names(&self, cx: &App) -> HashMap<u64, SharedString> {
18649        let this = self.read(cx);
18650        let user_ids = this.collaborators().values().map(|c| c.user_id);
18651        this.user_store().read_with(cx, |user_store, cx| {
18652            user_store.participant_names(user_ids, cx)
18653        })
18654    }
18655}
18656
18657pub trait SemanticsProvider {
18658    fn hover(
18659        &self,
18660        buffer: &Entity<Buffer>,
18661        position: text::Anchor,
18662        cx: &mut App,
18663    ) -> Option<Task<Vec<project::Hover>>>;
18664
18665    fn inlay_hints(
18666        &self,
18667        buffer_handle: Entity<Buffer>,
18668        range: Range<text::Anchor>,
18669        cx: &mut App,
18670    ) -> Option<Task<anyhow::Result<Vec<InlayHint>>>>;
18671
18672    fn resolve_inlay_hint(
18673        &self,
18674        hint: InlayHint,
18675        buffer_handle: Entity<Buffer>,
18676        server_id: LanguageServerId,
18677        cx: &mut App,
18678    ) -> Option<Task<anyhow::Result<InlayHint>>>;
18679
18680    fn supports_inlay_hints(&self, buffer: &Entity<Buffer>, cx: &mut App) -> bool;
18681
18682    fn document_highlights(
18683        &self,
18684        buffer: &Entity<Buffer>,
18685        position: text::Anchor,
18686        cx: &mut App,
18687    ) -> Option<Task<Result<Vec<DocumentHighlight>>>>;
18688
18689    fn definitions(
18690        &self,
18691        buffer: &Entity<Buffer>,
18692        position: text::Anchor,
18693        kind: GotoDefinitionKind,
18694        cx: &mut App,
18695    ) -> Option<Task<Result<Vec<LocationLink>>>>;
18696
18697    fn range_for_rename(
18698        &self,
18699        buffer: &Entity<Buffer>,
18700        position: text::Anchor,
18701        cx: &mut App,
18702    ) -> Option<Task<Result<Option<Range<text::Anchor>>>>>;
18703
18704    fn perform_rename(
18705        &self,
18706        buffer: &Entity<Buffer>,
18707        position: text::Anchor,
18708        new_name: String,
18709        cx: &mut App,
18710    ) -> Option<Task<Result<ProjectTransaction>>>;
18711}
18712
18713pub trait CompletionProvider {
18714    fn completions(
18715        &self,
18716        excerpt_id: ExcerptId,
18717        buffer: &Entity<Buffer>,
18718        buffer_position: text::Anchor,
18719        trigger: CompletionContext,
18720        window: &mut Window,
18721        cx: &mut Context<Editor>,
18722    ) -> Task<Result<Option<Vec<Completion>>>>;
18723
18724    fn resolve_completions(
18725        &self,
18726        buffer: Entity<Buffer>,
18727        completion_indices: Vec<usize>,
18728        completions: Rc<RefCell<Box<[Completion]>>>,
18729        cx: &mut Context<Editor>,
18730    ) -> Task<Result<bool>>;
18731
18732    fn apply_additional_edits_for_completion(
18733        &self,
18734        _buffer: Entity<Buffer>,
18735        _completions: Rc<RefCell<Box<[Completion]>>>,
18736        _completion_index: usize,
18737        _push_to_history: bool,
18738        _cx: &mut Context<Editor>,
18739    ) -> Task<Result<Option<language::Transaction>>> {
18740        Task::ready(Ok(None))
18741    }
18742
18743    fn is_completion_trigger(
18744        &self,
18745        buffer: &Entity<Buffer>,
18746        position: language::Anchor,
18747        text: &str,
18748        trigger_in_words: bool,
18749        cx: &mut Context<Editor>,
18750    ) -> bool;
18751
18752    fn sort_completions(&self) -> bool {
18753        true
18754    }
18755
18756    fn filter_completions(&self) -> bool {
18757        true
18758    }
18759}
18760
18761pub trait CodeActionProvider {
18762    fn id(&self) -> Arc<str>;
18763
18764    fn code_actions(
18765        &self,
18766        buffer: &Entity<Buffer>,
18767        range: Range<text::Anchor>,
18768        window: &mut Window,
18769        cx: &mut App,
18770    ) -> Task<Result<Vec<CodeAction>>>;
18771
18772    fn apply_code_action(
18773        &self,
18774        buffer_handle: Entity<Buffer>,
18775        action: CodeAction,
18776        excerpt_id: ExcerptId,
18777        push_to_history: bool,
18778        window: &mut Window,
18779        cx: &mut App,
18780    ) -> Task<Result<ProjectTransaction>>;
18781}
18782
18783impl CodeActionProvider for Entity<Project> {
18784    fn id(&self) -> Arc<str> {
18785        "project".into()
18786    }
18787
18788    fn code_actions(
18789        &self,
18790        buffer: &Entity<Buffer>,
18791        range: Range<text::Anchor>,
18792        _window: &mut Window,
18793        cx: &mut App,
18794    ) -> Task<Result<Vec<CodeAction>>> {
18795        self.update(cx, |project, cx| {
18796            let code_lens = project.code_lens(buffer, range.clone(), cx);
18797            let code_actions = project.code_actions(buffer, range, None, cx);
18798            cx.background_spawn(async move {
18799                let (code_lens, code_actions) = join(code_lens, code_actions).await;
18800                Ok(code_lens
18801                    .context("code lens fetch")?
18802                    .into_iter()
18803                    .chain(code_actions.context("code action fetch")?)
18804                    .collect())
18805            })
18806        })
18807    }
18808
18809    fn apply_code_action(
18810        &self,
18811        buffer_handle: Entity<Buffer>,
18812        action: CodeAction,
18813        _excerpt_id: ExcerptId,
18814        push_to_history: bool,
18815        _window: &mut Window,
18816        cx: &mut App,
18817    ) -> Task<Result<ProjectTransaction>> {
18818        self.update(cx, |project, cx| {
18819            project.apply_code_action(buffer_handle, action, push_to_history, cx)
18820        })
18821    }
18822}
18823
18824fn snippet_completions(
18825    project: &Project,
18826    buffer: &Entity<Buffer>,
18827    buffer_position: text::Anchor,
18828    cx: &mut App,
18829) -> Task<Result<Vec<Completion>>> {
18830    let languages = buffer.read(cx).languages_at(buffer_position);
18831    let snippet_store = project.snippets().read(cx);
18832
18833    let scopes: Vec<_> = languages
18834        .iter()
18835        .filter_map(|language| {
18836            let language_name = language.lsp_id();
18837            let snippets = snippet_store.snippets_for(Some(language_name), cx);
18838
18839            if snippets.is_empty() {
18840                None
18841            } else {
18842                Some((language.default_scope(), snippets))
18843            }
18844        })
18845        .collect();
18846
18847    if scopes.is_empty() {
18848        return Task::ready(Ok(vec![]));
18849    }
18850
18851    let snapshot = buffer.read(cx).text_snapshot();
18852    let chars: String = snapshot
18853        .reversed_chars_for_range(text::Anchor::MIN..buffer_position)
18854        .collect();
18855    let executor = cx.background_executor().clone();
18856
18857    cx.background_spawn(async move {
18858        let mut all_results: Vec<Completion> = Vec::new();
18859        for (scope, snippets) in scopes.into_iter() {
18860            let classifier = CharClassifier::new(Some(scope)).for_completion(true);
18861            let mut last_word = chars
18862                .chars()
18863                .take_while(|c| classifier.is_word(*c))
18864                .collect::<String>();
18865            last_word = last_word.chars().rev().collect();
18866
18867            if last_word.is_empty() {
18868                return Ok(vec![]);
18869            }
18870
18871            let as_offset = text::ToOffset::to_offset(&buffer_position, &snapshot);
18872            let to_lsp = |point: &text::Anchor| {
18873                let end = text::ToPointUtf16::to_point_utf16(point, &snapshot);
18874                point_to_lsp(end)
18875            };
18876            let lsp_end = to_lsp(&buffer_position);
18877
18878            let candidates = snippets
18879                .iter()
18880                .enumerate()
18881                .flat_map(|(ix, snippet)| {
18882                    snippet
18883                        .prefix
18884                        .iter()
18885                        .map(move |prefix| StringMatchCandidate::new(ix, &prefix))
18886                })
18887                .collect::<Vec<StringMatchCandidate>>();
18888
18889            let mut matches = fuzzy::match_strings(
18890                &candidates,
18891                &last_word,
18892                last_word.chars().any(|c| c.is_uppercase()),
18893                100,
18894                &Default::default(),
18895                executor.clone(),
18896            )
18897            .await;
18898
18899            // Remove all candidates where the query's start does not match the start of any word in the candidate
18900            if let Some(query_start) = last_word.chars().next() {
18901                matches.retain(|string_match| {
18902                    split_words(&string_match.string).any(|word| {
18903                        // Check that the first codepoint of the word as lowercase matches the first
18904                        // codepoint of the query as lowercase
18905                        word.chars()
18906                            .flat_map(|codepoint| codepoint.to_lowercase())
18907                            .zip(query_start.to_lowercase())
18908                            .all(|(word_cp, query_cp)| word_cp == query_cp)
18909                    })
18910                });
18911            }
18912
18913            let matched_strings = matches
18914                .into_iter()
18915                .map(|m| m.string)
18916                .collect::<HashSet<_>>();
18917
18918            let mut result: Vec<Completion> = snippets
18919                .iter()
18920                .filter_map(|snippet| {
18921                    let matching_prefix = snippet
18922                        .prefix
18923                        .iter()
18924                        .find(|prefix| matched_strings.contains(*prefix))?;
18925                    let start = as_offset - last_word.len();
18926                    let start = snapshot.anchor_before(start);
18927                    let range = start..buffer_position;
18928                    let lsp_start = to_lsp(&start);
18929                    let lsp_range = lsp::Range {
18930                        start: lsp_start,
18931                        end: lsp_end,
18932                    };
18933                    Some(Completion {
18934                        replace_range: range,
18935                        new_text: snippet.body.clone(),
18936                        source: CompletionSource::Lsp {
18937                            insert_range: None,
18938                            server_id: LanguageServerId(usize::MAX),
18939                            resolved: true,
18940                            lsp_completion: Box::new(lsp::CompletionItem {
18941                                label: snippet.prefix.first().unwrap().clone(),
18942                                kind: Some(CompletionItemKind::SNIPPET),
18943                                label_details: snippet.description.as_ref().map(|description| {
18944                                    lsp::CompletionItemLabelDetails {
18945                                        detail: Some(description.clone()),
18946                                        description: None,
18947                                    }
18948                                }),
18949                                insert_text_format: Some(InsertTextFormat::SNIPPET),
18950                                text_edit: Some(lsp::CompletionTextEdit::InsertAndReplace(
18951                                    lsp::InsertReplaceEdit {
18952                                        new_text: snippet.body.clone(),
18953                                        insert: lsp_range,
18954                                        replace: lsp_range,
18955                                    },
18956                                )),
18957                                filter_text: Some(snippet.body.clone()),
18958                                sort_text: Some(char::MAX.to_string()),
18959                                ..lsp::CompletionItem::default()
18960                            }),
18961                            lsp_defaults: None,
18962                        },
18963                        label: CodeLabel {
18964                            text: matching_prefix.clone(),
18965                            runs: Vec::new(),
18966                            filter_range: 0..matching_prefix.len(),
18967                        },
18968                        icon_path: None,
18969                        documentation: snippet.description.clone().map(|description| {
18970                            CompletionDocumentation::SingleLine(description.into())
18971                        }),
18972                        insert_text_mode: None,
18973                        confirm: None,
18974                    })
18975                })
18976                .collect();
18977
18978            all_results.append(&mut result);
18979        }
18980
18981        Ok(all_results)
18982    })
18983}
18984
18985impl CompletionProvider for Entity<Project> {
18986    fn completions(
18987        &self,
18988        _excerpt_id: ExcerptId,
18989        buffer: &Entity<Buffer>,
18990        buffer_position: text::Anchor,
18991        options: CompletionContext,
18992        _window: &mut Window,
18993        cx: &mut Context<Editor>,
18994    ) -> Task<Result<Option<Vec<Completion>>>> {
18995        self.update(cx, |project, cx| {
18996            let snippets = snippet_completions(project, buffer, buffer_position, cx);
18997            let project_completions = project.completions(buffer, buffer_position, options, cx);
18998            cx.background_spawn(async move {
18999                let snippets_completions = snippets.await?;
19000                match project_completions.await? {
19001                    Some(mut completions) => {
19002                        completions.extend(snippets_completions);
19003                        Ok(Some(completions))
19004                    }
19005                    None => {
19006                        if snippets_completions.is_empty() {
19007                            Ok(None)
19008                        } else {
19009                            Ok(Some(snippets_completions))
19010                        }
19011                    }
19012                }
19013            })
19014        })
19015    }
19016
19017    fn resolve_completions(
19018        &self,
19019        buffer: Entity<Buffer>,
19020        completion_indices: Vec<usize>,
19021        completions: Rc<RefCell<Box<[Completion]>>>,
19022        cx: &mut Context<Editor>,
19023    ) -> Task<Result<bool>> {
19024        self.update(cx, |project, cx| {
19025            project.lsp_store().update(cx, |lsp_store, cx| {
19026                lsp_store.resolve_completions(buffer, completion_indices, completions, cx)
19027            })
19028        })
19029    }
19030
19031    fn apply_additional_edits_for_completion(
19032        &self,
19033        buffer: Entity<Buffer>,
19034        completions: Rc<RefCell<Box<[Completion]>>>,
19035        completion_index: usize,
19036        push_to_history: bool,
19037        cx: &mut Context<Editor>,
19038    ) -> Task<Result<Option<language::Transaction>>> {
19039        self.update(cx, |project, cx| {
19040            project.lsp_store().update(cx, |lsp_store, cx| {
19041                lsp_store.apply_additional_edits_for_completion(
19042                    buffer,
19043                    completions,
19044                    completion_index,
19045                    push_to_history,
19046                    cx,
19047                )
19048            })
19049        })
19050    }
19051
19052    fn is_completion_trigger(
19053        &self,
19054        buffer: &Entity<Buffer>,
19055        position: language::Anchor,
19056        text: &str,
19057        trigger_in_words: bool,
19058        cx: &mut Context<Editor>,
19059    ) -> bool {
19060        let mut chars = text.chars();
19061        let char = if let Some(char) = chars.next() {
19062            char
19063        } else {
19064            return false;
19065        };
19066        if chars.next().is_some() {
19067            return false;
19068        }
19069
19070        let buffer = buffer.read(cx);
19071        let snapshot = buffer.snapshot();
19072        if !snapshot.settings_at(position, cx).show_completions_on_input {
19073            return false;
19074        }
19075        let classifier = snapshot.char_classifier_at(position).for_completion(true);
19076        if trigger_in_words && classifier.is_word(char) {
19077            return true;
19078        }
19079
19080        buffer.completion_triggers().contains(text)
19081    }
19082}
19083
19084impl SemanticsProvider for Entity<Project> {
19085    fn hover(
19086        &self,
19087        buffer: &Entity<Buffer>,
19088        position: text::Anchor,
19089        cx: &mut App,
19090    ) -> Option<Task<Vec<project::Hover>>> {
19091        Some(self.update(cx, |project, cx| project.hover(buffer, position, cx)))
19092    }
19093
19094    fn document_highlights(
19095        &self,
19096        buffer: &Entity<Buffer>,
19097        position: text::Anchor,
19098        cx: &mut App,
19099    ) -> Option<Task<Result<Vec<DocumentHighlight>>>> {
19100        Some(self.update(cx, |project, cx| {
19101            project.document_highlights(buffer, position, cx)
19102        }))
19103    }
19104
19105    fn definitions(
19106        &self,
19107        buffer: &Entity<Buffer>,
19108        position: text::Anchor,
19109        kind: GotoDefinitionKind,
19110        cx: &mut App,
19111    ) -> Option<Task<Result<Vec<LocationLink>>>> {
19112        Some(self.update(cx, |project, cx| match kind {
19113            GotoDefinitionKind::Symbol => project.definition(&buffer, position, cx),
19114            GotoDefinitionKind::Declaration => project.declaration(&buffer, position, cx),
19115            GotoDefinitionKind::Type => project.type_definition(&buffer, position, cx),
19116            GotoDefinitionKind::Implementation => project.implementation(&buffer, position, cx),
19117        }))
19118    }
19119
19120    fn supports_inlay_hints(&self, buffer: &Entity<Buffer>, cx: &mut App) -> bool {
19121        // TODO: make this work for remote projects
19122        self.update(cx, |this, cx| {
19123            buffer.update(cx, |buffer, cx| {
19124                this.any_language_server_supports_inlay_hints(buffer, cx)
19125            })
19126        })
19127    }
19128
19129    fn inlay_hints(
19130        &self,
19131        buffer_handle: Entity<Buffer>,
19132        range: Range<text::Anchor>,
19133        cx: &mut App,
19134    ) -> Option<Task<anyhow::Result<Vec<InlayHint>>>> {
19135        Some(self.update(cx, |project, cx| {
19136            project.inlay_hints(buffer_handle, range, cx)
19137        }))
19138    }
19139
19140    fn resolve_inlay_hint(
19141        &self,
19142        hint: InlayHint,
19143        buffer_handle: Entity<Buffer>,
19144        server_id: LanguageServerId,
19145        cx: &mut App,
19146    ) -> Option<Task<anyhow::Result<InlayHint>>> {
19147        Some(self.update(cx, |project, cx| {
19148            project.resolve_inlay_hint(hint, buffer_handle, server_id, cx)
19149        }))
19150    }
19151
19152    fn range_for_rename(
19153        &self,
19154        buffer: &Entity<Buffer>,
19155        position: text::Anchor,
19156        cx: &mut App,
19157    ) -> Option<Task<Result<Option<Range<text::Anchor>>>>> {
19158        Some(self.update(cx, |project, cx| {
19159            let buffer = buffer.clone();
19160            let task = project.prepare_rename(buffer.clone(), position, cx);
19161            cx.spawn(async move |_, cx| {
19162                Ok(match task.await? {
19163                    PrepareRenameResponse::Success(range) => Some(range),
19164                    PrepareRenameResponse::InvalidPosition => None,
19165                    PrepareRenameResponse::OnlyUnpreparedRenameSupported => {
19166                        // Fallback on using TreeSitter info to determine identifier range
19167                        buffer.update(cx, |buffer, _| {
19168                            let snapshot = buffer.snapshot();
19169                            let (range, kind) = snapshot.surrounding_word(position);
19170                            if kind != Some(CharKind::Word) {
19171                                return None;
19172                            }
19173                            Some(
19174                                snapshot.anchor_before(range.start)
19175                                    ..snapshot.anchor_after(range.end),
19176                            )
19177                        })?
19178                    }
19179                })
19180            })
19181        }))
19182    }
19183
19184    fn perform_rename(
19185        &self,
19186        buffer: &Entity<Buffer>,
19187        position: text::Anchor,
19188        new_name: String,
19189        cx: &mut App,
19190    ) -> Option<Task<Result<ProjectTransaction>>> {
19191        Some(self.update(cx, |project, cx| {
19192            project.perform_rename(buffer.clone(), position, new_name, cx)
19193        }))
19194    }
19195}
19196
19197fn inlay_hint_settings(
19198    location: Anchor,
19199    snapshot: &MultiBufferSnapshot,
19200    cx: &mut Context<Editor>,
19201) -> InlayHintSettings {
19202    let file = snapshot.file_at(location);
19203    let language = snapshot.language_at(location).map(|l| l.name());
19204    language_settings(language, file, cx).inlay_hints
19205}
19206
19207fn consume_contiguous_rows(
19208    contiguous_row_selections: &mut Vec<Selection<Point>>,
19209    selection: &Selection<Point>,
19210    display_map: &DisplaySnapshot,
19211    selections: &mut Peekable<std::slice::Iter<Selection<Point>>>,
19212) -> (MultiBufferRow, MultiBufferRow) {
19213    contiguous_row_selections.push(selection.clone());
19214    let start_row = MultiBufferRow(selection.start.row);
19215    let mut end_row = ending_row(selection, display_map);
19216
19217    while let Some(next_selection) = selections.peek() {
19218        if next_selection.start.row <= end_row.0 {
19219            end_row = ending_row(next_selection, display_map);
19220            contiguous_row_selections.push(selections.next().unwrap().clone());
19221        } else {
19222            break;
19223        }
19224    }
19225    (start_row, end_row)
19226}
19227
19228fn ending_row(next_selection: &Selection<Point>, display_map: &DisplaySnapshot) -> MultiBufferRow {
19229    if next_selection.end.column > 0 || next_selection.is_empty() {
19230        MultiBufferRow(display_map.next_line_boundary(next_selection.end).0.row + 1)
19231    } else {
19232        MultiBufferRow(next_selection.end.row)
19233    }
19234}
19235
19236impl EditorSnapshot {
19237    pub fn remote_selections_in_range<'a>(
19238        &'a self,
19239        range: &'a Range<Anchor>,
19240        collaboration_hub: &dyn CollaborationHub,
19241        cx: &'a App,
19242    ) -> impl 'a + Iterator<Item = RemoteSelection> {
19243        let participant_names = collaboration_hub.user_names(cx);
19244        let participant_indices = collaboration_hub.user_participant_indices(cx);
19245        let collaborators_by_peer_id = collaboration_hub.collaborators(cx);
19246        let collaborators_by_replica_id = collaborators_by_peer_id
19247            .iter()
19248            .map(|(_, collaborator)| (collaborator.replica_id, collaborator))
19249            .collect::<HashMap<_, _>>();
19250        self.buffer_snapshot
19251            .selections_in_range(range, false)
19252            .filter_map(move |(replica_id, line_mode, cursor_shape, selection)| {
19253                let collaborator = collaborators_by_replica_id.get(&replica_id)?;
19254                let participant_index = participant_indices.get(&collaborator.user_id).copied();
19255                let user_name = participant_names.get(&collaborator.user_id).cloned();
19256                Some(RemoteSelection {
19257                    replica_id,
19258                    selection,
19259                    cursor_shape,
19260                    line_mode,
19261                    participant_index,
19262                    peer_id: collaborator.peer_id,
19263                    user_name,
19264                })
19265            })
19266    }
19267
19268    pub fn hunks_for_ranges(
19269        &self,
19270        ranges: impl IntoIterator<Item = Range<Point>>,
19271    ) -> Vec<MultiBufferDiffHunk> {
19272        let mut hunks = Vec::new();
19273        let mut processed_buffer_rows: HashMap<BufferId, HashSet<Range<text::Anchor>>> =
19274            HashMap::default();
19275        for query_range in ranges {
19276            let query_rows =
19277                MultiBufferRow(query_range.start.row)..MultiBufferRow(query_range.end.row + 1);
19278            for hunk in self.buffer_snapshot.diff_hunks_in_range(
19279                Point::new(query_rows.start.0, 0)..Point::new(query_rows.end.0, 0),
19280            ) {
19281                // Include deleted hunks that are adjacent to the query range, because
19282                // otherwise they would be missed.
19283                let mut intersects_range = hunk.row_range.overlaps(&query_rows);
19284                if hunk.status().is_deleted() {
19285                    intersects_range |= hunk.row_range.start == query_rows.end;
19286                    intersects_range |= hunk.row_range.end == query_rows.start;
19287                }
19288                if intersects_range {
19289                    if !processed_buffer_rows
19290                        .entry(hunk.buffer_id)
19291                        .or_default()
19292                        .insert(hunk.buffer_range.start..hunk.buffer_range.end)
19293                    {
19294                        continue;
19295                    }
19296                    hunks.push(hunk);
19297                }
19298            }
19299        }
19300
19301        hunks
19302    }
19303
19304    fn display_diff_hunks_for_rows<'a>(
19305        &'a self,
19306        display_rows: Range<DisplayRow>,
19307        folded_buffers: &'a HashSet<BufferId>,
19308    ) -> impl 'a + Iterator<Item = DisplayDiffHunk> {
19309        let buffer_start = DisplayPoint::new(display_rows.start, 0).to_point(self);
19310        let buffer_end = DisplayPoint::new(display_rows.end, 0).to_point(self);
19311
19312        self.buffer_snapshot
19313            .diff_hunks_in_range(buffer_start..buffer_end)
19314            .filter_map(|hunk| {
19315                if folded_buffers.contains(&hunk.buffer_id) {
19316                    return None;
19317                }
19318
19319                let hunk_start_point = Point::new(hunk.row_range.start.0, 0);
19320                let hunk_end_point = Point::new(hunk.row_range.end.0, 0);
19321
19322                let hunk_display_start = self.point_to_display_point(hunk_start_point, Bias::Left);
19323                let hunk_display_end = self.point_to_display_point(hunk_end_point, Bias::Right);
19324
19325                let display_hunk = if hunk_display_start.column() != 0 {
19326                    DisplayDiffHunk::Folded {
19327                        display_row: hunk_display_start.row(),
19328                    }
19329                } else {
19330                    let mut end_row = hunk_display_end.row();
19331                    if hunk_display_end.column() > 0 {
19332                        end_row.0 += 1;
19333                    }
19334                    let is_created_file = hunk.is_created_file();
19335                    DisplayDiffHunk::Unfolded {
19336                        status: hunk.status(),
19337                        diff_base_byte_range: hunk.diff_base_byte_range,
19338                        display_row_range: hunk_display_start.row()..end_row,
19339                        multi_buffer_range: Anchor::range_in_buffer(
19340                            hunk.excerpt_id,
19341                            hunk.buffer_id,
19342                            hunk.buffer_range,
19343                        ),
19344                        is_created_file,
19345                    }
19346                };
19347
19348                Some(display_hunk)
19349            })
19350    }
19351
19352    pub fn language_at<T: ToOffset>(&self, position: T) -> Option<&Arc<Language>> {
19353        self.display_snapshot.buffer_snapshot.language_at(position)
19354    }
19355
19356    pub fn is_focused(&self) -> bool {
19357        self.is_focused
19358    }
19359
19360    pub fn placeholder_text(&self) -> Option<&Arc<str>> {
19361        self.placeholder_text.as_ref()
19362    }
19363
19364    pub fn scroll_position(&self) -> gpui::Point<f32> {
19365        self.scroll_anchor.scroll_position(&self.display_snapshot)
19366    }
19367
19368    fn gutter_dimensions(
19369        &self,
19370        font_id: FontId,
19371        font_size: Pixels,
19372        max_line_number_width: Pixels,
19373        cx: &App,
19374    ) -> Option<GutterDimensions> {
19375        if !self.show_gutter {
19376            return None;
19377        }
19378
19379        let descent = cx.text_system().descent(font_id, font_size);
19380        let em_width = cx.text_system().em_width(font_id, font_size).log_err()?;
19381        let em_advance = cx.text_system().em_advance(font_id, font_size).log_err()?;
19382
19383        let show_git_gutter = self.show_git_diff_gutter.unwrap_or_else(|| {
19384            matches!(
19385                ProjectSettings::get_global(cx).git.git_gutter,
19386                Some(GitGutterSetting::TrackedFiles)
19387            )
19388        });
19389        let gutter_settings = EditorSettings::get_global(cx).gutter;
19390        let show_line_numbers = self
19391            .show_line_numbers
19392            .unwrap_or(gutter_settings.line_numbers);
19393        let line_gutter_width = if show_line_numbers {
19394            // Avoid flicker-like gutter resizes when the line number gains another digit and only resize the gutter on files with N*10^5 lines.
19395            let min_width_for_number_on_gutter = em_advance * MIN_LINE_NUMBER_DIGITS as f32;
19396            max_line_number_width.max(min_width_for_number_on_gutter)
19397        } else {
19398            0.0.into()
19399        };
19400
19401        let show_code_actions = self
19402            .show_code_actions
19403            .unwrap_or(gutter_settings.code_actions);
19404
19405        let show_runnables = self.show_runnables.unwrap_or(gutter_settings.runnables);
19406        let show_breakpoints = self.show_breakpoints.unwrap_or(gutter_settings.breakpoints);
19407
19408        let git_blame_entries_width =
19409            self.git_blame_gutter_max_author_length
19410                .map(|max_author_length| {
19411                    let renderer = cx.global::<GlobalBlameRenderer>().0.clone();
19412                    const MAX_RELATIVE_TIMESTAMP: &str = "60 minutes ago";
19413
19414                    /// The number of characters to dedicate to gaps and margins.
19415                    const SPACING_WIDTH: usize = 4;
19416
19417                    let max_char_count = max_author_length.min(renderer.max_author_length())
19418                        + ::git::SHORT_SHA_LENGTH
19419                        + MAX_RELATIVE_TIMESTAMP.len()
19420                        + SPACING_WIDTH;
19421
19422                    em_advance * max_char_count
19423                });
19424
19425        let is_singleton = self.buffer_snapshot.is_singleton();
19426
19427        let mut left_padding = git_blame_entries_width.unwrap_or(Pixels::ZERO);
19428        left_padding += if !is_singleton {
19429            em_width * 4.0
19430        } else if show_code_actions || show_runnables || show_breakpoints {
19431            em_width * 3.0
19432        } else if show_git_gutter && show_line_numbers {
19433            em_width * 2.0
19434        } else if show_git_gutter || show_line_numbers {
19435            em_width
19436        } else {
19437            px(0.)
19438        };
19439
19440        let shows_folds = is_singleton && gutter_settings.folds;
19441
19442        let right_padding = if shows_folds && show_line_numbers {
19443            em_width * 4.0
19444        } else if shows_folds || (!is_singleton && show_line_numbers) {
19445            em_width * 3.0
19446        } else if show_line_numbers {
19447            em_width
19448        } else {
19449            px(0.)
19450        };
19451
19452        Some(GutterDimensions {
19453            left_padding,
19454            right_padding,
19455            width: line_gutter_width + left_padding + right_padding,
19456            margin: -descent,
19457            git_blame_entries_width,
19458        })
19459    }
19460
19461    pub fn render_crease_toggle(
19462        &self,
19463        buffer_row: MultiBufferRow,
19464        row_contains_cursor: bool,
19465        editor: Entity<Editor>,
19466        window: &mut Window,
19467        cx: &mut App,
19468    ) -> Option<AnyElement> {
19469        let folded = self.is_line_folded(buffer_row);
19470        let mut is_foldable = false;
19471
19472        if let Some(crease) = self
19473            .crease_snapshot
19474            .query_row(buffer_row, &self.buffer_snapshot)
19475        {
19476            is_foldable = true;
19477            match crease {
19478                Crease::Inline { render_toggle, .. } | Crease::Block { render_toggle, .. } => {
19479                    if let Some(render_toggle) = render_toggle {
19480                        let toggle_callback =
19481                            Arc::new(move |folded, window: &mut Window, cx: &mut App| {
19482                                if folded {
19483                                    editor.update(cx, |editor, cx| {
19484                                        editor.fold_at(buffer_row, window, cx)
19485                                    });
19486                                } else {
19487                                    editor.update(cx, |editor, cx| {
19488                                        editor.unfold_at(buffer_row, window, cx)
19489                                    });
19490                                }
19491                            });
19492                        return Some((render_toggle)(
19493                            buffer_row,
19494                            folded,
19495                            toggle_callback,
19496                            window,
19497                            cx,
19498                        ));
19499                    }
19500                }
19501            }
19502        }
19503
19504        is_foldable |= self.starts_indent(buffer_row);
19505
19506        if folded || (is_foldable && (row_contains_cursor || self.gutter_hovered)) {
19507            Some(
19508                Disclosure::new(("gutter_crease", buffer_row.0), !folded)
19509                    .toggle_state(folded)
19510                    .on_click(window.listener_for(&editor, move |this, _e, window, cx| {
19511                        if folded {
19512                            this.unfold_at(buffer_row, window, cx);
19513                        } else {
19514                            this.fold_at(buffer_row, window, cx);
19515                        }
19516                    }))
19517                    .into_any_element(),
19518            )
19519        } else {
19520            None
19521        }
19522    }
19523
19524    pub fn render_crease_trailer(
19525        &self,
19526        buffer_row: MultiBufferRow,
19527        window: &mut Window,
19528        cx: &mut App,
19529    ) -> Option<AnyElement> {
19530        let folded = self.is_line_folded(buffer_row);
19531        if let Crease::Inline { render_trailer, .. } = self
19532            .crease_snapshot
19533            .query_row(buffer_row, &self.buffer_snapshot)?
19534        {
19535            let render_trailer = render_trailer.as_ref()?;
19536            Some(render_trailer(buffer_row, folded, window, cx))
19537        } else {
19538            None
19539        }
19540    }
19541}
19542
19543impl Deref for EditorSnapshot {
19544    type Target = DisplaySnapshot;
19545
19546    fn deref(&self) -> &Self::Target {
19547        &self.display_snapshot
19548    }
19549}
19550
19551#[derive(Clone, Debug, PartialEq, Eq)]
19552pub enum EditorEvent {
19553    InputIgnored {
19554        text: Arc<str>,
19555    },
19556    InputHandled {
19557        utf16_range_to_replace: Option<Range<isize>>,
19558        text: Arc<str>,
19559    },
19560    ExcerptsAdded {
19561        buffer: Entity<Buffer>,
19562        predecessor: ExcerptId,
19563        excerpts: Vec<(ExcerptId, ExcerptRange<language::Anchor>)>,
19564    },
19565    ExcerptsRemoved {
19566        ids: Vec<ExcerptId>,
19567    },
19568    BufferFoldToggled {
19569        ids: Vec<ExcerptId>,
19570        folded: bool,
19571    },
19572    ExcerptsEdited {
19573        ids: Vec<ExcerptId>,
19574    },
19575    ExcerptsExpanded {
19576        ids: Vec<ExcerptId>,
19577    },
19578    BufferEdited,
19579    Edited {
19580        transaction_id: clock::Lamport,
19581    },
19582    Reparsed(BufferId),
19583    Focused,
19584    FocusedIn,
19585    Blurred,
19586    DirtyChanged,
19587    Saved,
19588    TitleChanged,
19589    DiffBaseChanged,
19590    SelectionsChanged {
19591        local: bool,
19592    },
19593    ScrollPositionChanged {
19594        local: bool,
19595        autoscroll: bool,
19596    },
19597    Closed,
19598    TransactionUndone {
19599        transaction_id: clock::Lamport,
19600    },
19601    TransactionBegun {
19602        transaction_id: clock::Lamport,
19603    },
19604    Reloaded,
19605    CursorShapeChanged,
19606    PushedToNavHistory {
19607        anchor: Anchor,
19608        is_deactivate: bool,
19609    },
19610}
19611
19612impl EventEmitter<EditorEvent> for Editor {}
19613
19614impl Focusable for Editor {
19615    fn focus_handle(&self, _cx: &App) -> FocusHandle {
19616        self.focus_handle.clone()
19617    }
19618}
19619
19620impl Render for Editor {
19621    fn render(&mut self, _: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
19622        let settings = ThemeSettings::get_global(cx);
19623
19624        let mut text_style = match self.mode {
19625            EditorMode::SingleLine { .. } | EditorMode::AutoHeight { .. } => TextStyle {
19626                color: cx.theme().colors().editor_foreground,
19627                font_family: settings.ui_font.family.clone(),
19628                font_features: settings.ui_font.features.clone(),
19629                font_fallbacks: settings.ui_font.fallbacks.clone(),
19630                font_size: rems(0.875).into(),
19631                font_weight: settings.ui_font.weight,
19632                line_height: relative(settings.buffer_line_height.value()),
19633                ..Default::default()
19634            },
19635            EditorMode::Full { .. } => TextStyle {
19636                color: cx.theme().colors().editor_foreground,
19637                font_family: settings.buffer_font.family.clone(),
19638                font_features: settings.buffer_font.features.clone(),
19639                font_fallbacks: settings.buffer_font.fallbacks.clone(),
19640                font_size: settings.buffer_font_size(cx).into(),
19641                font_weight: settings.buffer_font.weight,
19642                line_height: relative(settings.buffer_line_height.value()),
19643                ..Default::default()
19644            },
19645        };
19646        if let Some(text_style_refinement) = &self.text_style_refinement {
19647            text_style.refine(text_style_refinement)
19648        }
19649
19650        let background = match self.mode {
19651            EditorMode::SingleLine { .. } => cx.theme().system().transparent,
19652            EditorMode::AutoHeight { max_lines: _ } => cx.theme().system().transparent,
19653            EditorMode::Full { .. } => cx.theme().colors().editor_background,
19654        };
19655
19656        EditorElement::new(
19657            &cx.entity(),
19658            EditorStyle {
19659                background,
19660                local_player: cx.theme().players().local(),
19661                text: text_style,
19662                scrollbar_width: EditorElement::SCROLLBAR_WIDTH,
19663                syntax: cx.theme().syntax().clone(),
19664                status: cx.theme().status().clone(),
19665                inlay_hints_style: make_inlay_hints_style(cx),
19666                inline_completion_styles: make_suggestion_styles(cx),
19667                unnecessary_code_fade: ThemeSettings::get_global(cx).unnecessary_code_fade,
19668            },
19669        )
19670    }
19671}
19672
19673impl EntityInputHandler for Editor {
19674    fn text_for_range(
19675        &mut self,
19676        range_utf16: Range<usize>,
19677        adjusted_range: &mut Option<Range<usize>>,
19678        _: &mut Window,
19679        cx: &mut Context<Self>,
19680    ) -> Option<String> {
19681        let snapshot = self.buffer.read(cx).read(cx);
19682        let start = snapshot.clip_offset_utf16(OffsetUtf16(range_utf16.start), Bias::Left);
19683        let end = snapshot.clip_offset_utf16(OffsetUtf16(range_utf16.end), Bias::Right);
19684        if (start.0..end.0) != range_utf16 {
19685            adjusted_range.replace(start.0..end.0);
19686        }
19687        Some(snapshot.text_for_range(start..end).collect())
19688    }
19689
19690    fn selected_text_range(
19691        &mut self,
19692        ignore_disabled_input: bool,
19693        _: &mut Window,
19694        cx: &mut Context<Self>,
19695    ) -> Option<UTF16Selection> {
19696        // Prevent the IME menu from appearing when holding down an alphabetic key
19697        // while input is disabled.
19698        if !ignore_disabled_input && !self.input_enabled {
19699            return None;
19700        }
19701
19702        let selection = self.selections.newest::<OffsetUtf16>(cx);
19703        let range = selection.range();
19704
19705        Some(UTF16Selection {
19706            range: range.start.0..range.end.0,
19707            reversed: selection.reversed,
19708        })
19709    }
19710
19711    fn marked_text_range(&self, _: &mut Window, cx: &mut Context<Self>) -> Option<Range<usize>> {
19712        let snapshot = self.buffer.read(cx).read(cx);
19713        let range = self.text_highlights::<InputComposition>(cx)?.1.first()?;
19714        Some(range.start.to_offset_utf16(&snapshot).0..range.end.to_offset_utf16(&snapshot).0)
19715    }
19716
19717    fn unmark_text(&mut self, _: &mut Window, cx: &mut Context<Self>) {
19718        self.clear_highlights::<InputComposition>(cx);
19719        self.ime_transaction.take();
19720    }
19721
19722    fn replace_text_in_range(
19723        &mut self,
19724        range_utf16: Option<Range<usize>>,
19725        text: &str,
19726        window: &mut Window,
19727        cx: &mut Context<Self>,
19728    ) {
19729        if !self.input_enabled {
19730            cx.emit(EditorEvent::InputIgnored { text: text.into() });
19731            return;
19732        }
19733
19734        self.transact(window, cx, |this, window, cx| {
19735            let new_selected_ranges = if let Some(range_utf16) = range_utf16 {
19736                let range_utf16 = OffsetUtf16(range_utf16.start)..OffsetUtf16(range_utf16.end);
19737                Some(this.selection_replacement_ranges(range_utf16, cx))
19738            } else {
19739                this.marked_text_ranges(cx)
19740            };
19741
19742            let range_to_replace = new_selected_ranges.as_ref().and_then(|ranges_to_replace| {
19743                let newest_selection_id = this.selections.newest_anchor().id;
19744                this.selections
19745                    .all::<OffsetUtf16>(cx)
19746                    .iter()
19747                    .zip(ranges_to_replace.iter())
19748                    .find_map(|(selection, range)| {
19749                        if selection.id == newest_selection_id {
19750                            Some(
19751                                (range.start.0 as isize - selection.head().0 as isize)
19752                                    ..(range.end.0 as isize - selection.head().0 as isize),
19753                            )
19754                        } else {
19755                            None
19756                        }
19757                    })
19758            });
19759
19760            cx.emit(EditorEvent::InputHandled {
19761                utf16_range_to_replace: range_to_replace,
19762                text: text.into(),
19763            });
19764
19765            if let Some(new_selected_ranges) = new_selected_ranges {
19766                this.change_selections(None, window, cx, |selections| {
19767                    selections.select_ranges(new_selected_ranges)
19768                });
19769                this.backspace(&Default::default(), window, cx);
19770            }
19771
19772            this.handle_input(text, window, cx);
19773        });
19774
19775        if let Some(transaction) = self.ime_transaction {
19776            self.buffer.update(cx, |buffer, cx| {
19777                buffer.group_until_transaction(transaction, cx);
19778            });
19779        }
19780
19781        self.unmark_text(window, cx);
19782    }
19783
19784    fn replace_and_mark_text_in_range(
19785        &mut self,
19786        range_utf16: Option<Range<usize>>,
19787        text: &str,
19788        new_selected_range_utf16: Option<Range<usize>>,
19789        window: &mut Window,
19790        cx: &mut Context<Self>,
19791    ) {
19792        if !self.input_enabled {
19793            return;
19794        }
19795
19796        let transaction = self.transact(window, cx, |this, window, cx| {
19797            let ranges_to_replace = if let Some(mut marked_ranges) = this.marked_text_ranges(cx) {
19798                let snapshot = this.buffer.read(cx).read(cx);
19799                if let Some(relative_range_utf16) = range_utf16.as_ref() {
19800                    for marked_range in &mut marked_ranges {
19801                        marked_range.end.0 = marked_range.start.0 + relative_range_utf16.end;
19802                        marked_range.start.0 += relative_range_utf16.start;
19803                        marked_range.start =
19804                            snapshot.clip_offset_utf16(marked_range.start, Bias::Left);
19805                        marked_range.end =
19806                            snapshot.clip_offset_utf16(marked_range.end, Bias::Right);
19807                    }
19808                }
19809                Some(marked_ranges)
19810            } else if let Some(range_utf16) = range_utf16 {
19811                let range_utf16 = OffsetUtf16(range_utf16.start)..OffsetUtf16(range_utf16.end);
19812                Some(this.selection_replacement_ranges(range_utf16, cx))
19813            } else {
19814                None
19815            };
19816
19817            let range_to_replace = ranges_to_replace.as_ref().and_then(|ranges_to_replace| {
19818                let newest_selection_id = this.selections.newest_anchor().id;
19819                this.selections
19820                    .all::<OffsetUtf16>(cx)
19821                    .iter()
19822                    .zip(ranges_to_replace.iter())
19823                    .find_map(|(selection, range)| {
19824                        if selection.id == newest_selection_id {
19825                            Some(
19826                                (range.start.0 as isize - selection.head().0 as isize)
19827                                    ..(range.end.0 as isize - selection.head().0 as isize),
19828                            )
19829                        } else {
19830                            None
19831                        }
19832                    })
19833            });
19834
19835            cx.emit(EditorEvent::InputHandled {
19836                utf16_range_to_replace: range_to_replace,
19837                text: text.into(),
19838            });
19839
19840            if let Some(ranges) = ranges_to_replace {
19841                this.change_selections(None, window, cx, |s| s.select_ranges(ranges));
19842            }
19843
19844            let marked_ranges = {
19845                let snapshot = this.buffer.read(cx).read(cx);
19846                this.selections
19847                    .disjoint_anchors()
19848                    .iter()
19849                    .map(|selection| {
19850                        selection.start.bias_left(&snapshot)..selection.end.bias_right(&snapshot)
19851                    })
19852                    .collect::<Vec<_>>()
19853            };
19854
19855            if text.is_empty() {
19856                this.unmark_text(window, cx);
19857            } else {
19858                this.highlight_text::<InputComposition>(
19859                    marked_ranges.clone(),
19860                    HighlightStyle {
19861                        underline: Some(UnderlineStyle {
19862                            thickness: px(1.),
19863                            color: None,
19864                            wavy: false,
19865                        }),
19866                        ..Default::default()
19867                    },
19868                    cx,
19869                );
19870            }
19871
19872            // Disable auto-closing when composing text (i.e. typing a `"` on a Brazilian keyboard)
19873            let use_autoclose = this.use_autoclose;
19874            let use_auto_surround = this.use_auto_surround;
19875            this.set_use_autoclose(false);
19876            this.set_use_auto_surround(false);
19877            this.handle_input(text, window, cx);
19878            this.set_use_autoclose(use_autoclose);
19879            this.set_use_auto_surround(use_auto_surround);
19880
19881            if let Some(new_selected_range) = new_selected_range_utf16 {
19882                let snapshot = this.buffer.read(cx).read(cx);
19883                let new_selected_ranges = marked_ranges
19884                    .into_iter()
19885                    .map(|marked_range| {
19886                        let insertion_start = marked_range.start.to_offset_utf16(&snapshot).0;
19887                        let new_start = OffsetUtf16(new_selected_range.start + insertion_start);
19888                        let new_end = OffsetUtf16(new_selected_range.end + insertion_start);
19889                        snapshot.clip_offset_utf16(new_start, Bias::Left)
19890                            ..snapshot.clip_offset_utf16(new_end, Bias::Right)
19891                    })
19892                    .collect::<Vec<_>>();
19893
19894                drop(snapshot);
19895                this.change_selections(None, window, cx, |selections| {
19896                    selections.select_ranges(new_selected_ranges)
19897                });
19898            }
19899        });
19900
19901        self.ime_transaction = self.ime_transaction.or(transaction);
19902        if let Some(transaction) = self.ime_transaction {
19903            self.buffer.update(cx, |buffer, cx| {
19904                buffer.group_until_transaction(transaction, cx);
19905            });
19906        }
19907
19908        if self.text_highlights::<InputComposition>(cx).is_none() {
19909            self.ime_transaction.take();
19910        }
19911    }
19912
19913    fn bounds_for_range(
19914        &mut self,
19915        range_utf16: Range<usize>,
19916        element_bounds: gpui::Bounds<Pixels>,
19917        window: &mut Window,
19918        cx: &mut Context<Self>,
19919    ) -> Option<gpui::Bounds<Pixels>> {
19920        let text_layout_details = self.text_layout_details(window);
19921        let gpui::Size {
19922            width: em_width,
19923            height: line_height,
19924        } = self.character_size(window);
19925
19926        let snapshot = self.snapshot(window, cx);
19927        let scroll_position = snapshot.scroll_position();
19928        let scroll_left = scroll_position.x * em_width;
19929
19930        let start = OffsetUtf16(range_utf16.start).to_display_point(&snapshot);
19931        let x = snapshot.x_for_display_point(start, &text_layout_details) - scroll_left
19932            + self.gutter_dimensions.width
19933            + self.gutter_dimensions.margin;
19934        let y = line_height * (start.row().as_f32() - scroll_position.y);
19935
19936        Some(Bounds {
19937            origin: element_bounds.origin + point(x, y),
19938            size: size(em_width, line_height),
19939        })
19940    }
19941
19942    fn character_index_for_point(
19943        &mut self,
19944        point: gpui::Point<Pixels>,
19945        _window: &mut Window,
19946        _cx: &mut Context<Self>,
19947    ) -> Option<usize> {
19948        let position_map = self.last_position_map.as_ref()?;
19949        if !position_map.text_hitbox.contains(&point) {
19950            return None;
19951        }
19952        let display_point = position_map.point_for_position(point).previous_valid;
19953        let anchor = position_map
19954            .snapshot
19955            .display_point_to_anchor(display_point, Bias::Left);
19956        let utf16_offset = anchor.to_offset_utf16(&position_map.snapshot.buffer_snapshot);
19957        Some(utf16_offset.0)
19958    }
19959}
19960
19961trait SelectionExt {
19962    fn display_range(&self, map: &DisplaySnapshot) -> Range<DisplayPoint>;
19963    fn spanned_rows(
19964        &self,
19965        include_end_if_at_line_start: bool,
19966        map: &DisplaySnapshot,
19967    ) -> Range<MultiBufferRow>;
19968}
19969
19970impl<T: ToPoint + ToOffset> SelectionExt for Selection<T> {
19971    fn display_range(&self, map: &DisplaySnapshot) -> Range<DisplayPoint> {
19972        let start = self
19973            .start
19974            .to_point(&map.buffer_snapshot)
19975            .to_display_point(map);
19976        let end = self
19977            .end
19978            .to_point(&map.buffer_snapshot)
19979            .to_display_point(map);
19980        if self.reversed {
19981            end..start
19982        } else {
19983            start..end
19984        }
19985    }
19986
19987    fn spanned_rows(
19988        &self,
19989        include_end_if_at_line_start: bool,
19990        map: &DisplaySnapshot,
19991    ) -> Range<MultiBufferRow> {
19992        let start = self.start.to_point(&map.buffer_snapshot);
19993        let mut end = self.end.to_point(&map.buffer_snapshot);
19994        if !include_end_if_at_line_start && start.row != end.row && end.column == 0 {
19995            end.row -= 1;
19996        }
19997
19998        let buffer_start = map.prev_line_boundary(start).0;
19999        let buffer_end = map.next_line_boundary(end).0;
20000        MultiBufferRow(buffer_start.row)..MultiBufferRow(buffer_end.row + 1)
20001    }
20002}
20003
20004impl<T: InvalidationRegion> InvalidationStack<T> {
20005    fn invalidate<S>(&mut self, selections: &[Selection<S>], buffer: &MultiBufferSnapshot)
20006    where
20007        S: Clone + ToOffset,
20008    {
20009        while let Some(region) = self.last() {
20010            let all_selections_inside_invalidation_ranges =
20011                if selections.len() == region.ranges().len() {
20012                    selections
20013                        .iter()
20014                        .zip(region.ranges().iter().map(|r| r.to_offset(buffer)))
20015                        .all(|(selection, invalidation_range)| {
20016                            let head = selection.head().to_offset(buffer);
20017                            invalidation_range.start <= head && invalidation_range.end >= head
20018                        })
20019                } else {
20020                    false
20021                };
20022
20023            if all_selections_inside_invalidation_ranges {
20024                break;
20025            } else {
20026                self.pop();
20027            }
20028        }
20029    }
20030}
20031
20032impl<T> Default for InvalidationStack<T> {
20033    fn default() -> Self {
20034        Self(Default::default())
20035    }
20036}
20037
20038impl<T> Deref for InvalidationStack<T> {
20039    type Target = Vec<T>;
20040
20041    fn deref(&self) -> &Self::Target {
20042        &self.0
20043    }
20044}
20045
20046impl<T> DerefMut for InvalidationStack<T> {
20047    fn deref_mut(&mut self) -> &mut Self::Target {
20048        &mut self.0
20049    }
20050}
20051
20052impl InvalidationRegion for SnippetState {
20053    fn ranges(&self) -> &[Range<Anchor>] {
20054        &self.ranges[self.active_index]
20055    }
20056}
20057
20058fn inline_completion_edit_text(
20059    current_snapshot: &BufferSnapshot,
20060    edits: &[(Range<Anchor>, String)],
20061    edit_preview: &EditPreview,
20062    include_deletions: bool,
20063    cx: &App,
20064) -> HighlightedText {
20065    let edits = edits
20066        .iter()
20067        .map(|(anchor, text)| {
20068            (
20069                anchor.start.text_anchor..anchor.end.text_anchor,
20070                text.clone(),
20071            )
20072        })
20073        .collect::<Vec<_>>();
20074
20075    edit_preview.highlight_edits(current_snapshot, &edits, include_deletions, cx)
20076}
20077
20078pub fn diagnostic_style(severity: DiagnosticSeverity, colors: &StatusColors) -> Hsla {
20079    match severity {
20080        DiagnosticSeverity::ERROR => colors.error,
20081        DiagnosticSeverity::WARNING => colors.warning,
20082        DiagnosticSeverity::INFORMATION => colors.info,
20083        DiagnosticSeverity::HINT => colors.info,
20084        _ => colors.ignored,
20085    }
20086}
20087
20088pub fn styled_runs_for_code_label<'a>(
20089    label: &'a CodeLabel,
20090    syntax_theme: &'a theme::SyntaxTheme,
20091) -> impl 'a + Iterator<Item = (Range<usize>, HighlightStyle)> {
20092    let fade_out = HighlightStyle {
20093        fade_out: Some(0.35),
20094        ..Default::default()
20095    };
20096
20097    let mut prev_end = label.filter_range.end;
20098    label
20099        .runs
20100        .iter()
20101        .enumerate()
20102        .flat_map(move |(ix, (range, highlight_id))| {
20103            let style = if let Some(style) = highlight_id.style(syntax_theme) {
20104                style
20105            } else {
20106                return Default::default();
20107            };
20108            let mut muted_style = style;
20109            muted_style.highlight(fade_out);
20110
20111            let mut runs = SmallVec::<[(Range<usize>, HighlightStyle); 3]>::new();
20112            if range.start >= label.filter_range.end {
20113                if range.start > prev_end {
20114                    runs.push((prev_end..range.start, fade_out));
20115                }
20116                runs.push((range.clone(), muted_style));
20117            } else if range.end <= label.filter_range.end {
20118                runs.push((range.clone(), style));
20119            } else {
20120                runs.push((range.start..label.filter_range.end, style));
20121                runs.push((label.filter_range.end..range.end, muted_style));
20122            }
20123            prev_end = cmp::max(prev_end, range.end);
20124
20125            if ix + 1 == label.runs.len() && label.text.len() > prev_end {
20126                runs.push((prev_end..label.text.len(), fade_out));
20127            }
20128
20129            runs
20130        })
20131}
20132
20133pub(crate) fn split_words(text: &str) -> impl std::iter::Iterator<Item = &str> + '_ {
20134    let mut prev_index = 0;
20135    let mut prev_codepoint: Option<char> = None;
20136    text.char_indices()
20137        .chain([(text.len(), '\0')])
20138        .filter_map(move |(index, codepoint)| {
20139            let prev_codepoint = prev_codepoint.replace(codepoint)?;
20140            let is_boundary = index == text.len()
20141                || !prev_codepoint.is_uppercase() && codepoint.is_uppercase()
20142                || !prev_codepoint.is_alphanumeric() && codepoint.is_alphanumeric();
20143            if is_boundary {
20144                let chunk = &text[prev_index..index];
20145                prev_index = index;
20146                Some(chunk)
20147            } else {
20148                None
20149            }
20150        })
20151}
20152
20153pub trait RangeToAnchorExt: Sized {
20154    fn to_anchors(self, snapshot: &MultiBufferSnapshot) -> Range<Anchor>;
20155
20156    fn to_display_points(self, snapshot: &EditorSnapshot) -> Range<DisplayPoint> {
20157        let anchor_range = self.to_anchors(&snapshot.buffer_snapshot);
20158        anchor_range.start.to_display_point(snapshot)..anchor_range.end.to_display_point(snapshot)
20159    }
20160}
20161
20162impl<T: ToOffset> RangeToAnchorExt for Range<T> {
20163    fn to_anchors(self, snapshot: &MultiBufferSnapshot) -> Range<Anchor> {
20164        let start_offset = self.start.to_offset(snapshot);
20165        let end_offset = self.end.to_offset(snapshot);
20166        if start_offset == end_offset {
20167            snapshot.anchor_before(start_offset)..snapshot.anchor_before(end_offset)
20168        } else {
20169            snapshot.anchor_after(self.start)..snapshot.anchor_before(self.end)
20170        }
20171    }
20172}
20173
20174pub trait RowExt {
20175    fn as_f32(&self) -> f32;
20176
20177    fn next_row(&self) -> Self;
20178
20179    fn previous_row(&self) -> Self;
20180
20181    fn minus(&self, other: Self) -> u32;
20182}
20183
20184impl RowExt for DisplayRow {
20185    fn as_f32(&self) -> f32 {
20186        self.0 as f32
20187    }
20188
20189    fn next_row(&self) -> Self {
20190        Self(self.0 + 1)
20191    }
20192
20193    fn previous_row(&self) -> Self {
20194        Self(self.0.saturating_sub(1))
20195    }
20196
20197    fn minus(&self, other: Self) -> u32 {
20198        self.0 - other.0
20199    }
20200}
20201
20202impl RowExt for MultiBufferRow {
20203    fn as_f32(&self) -> f32 {
20204        self.0 as f32
20205    }
20206
20207    fn next_row(&self) -> Self {
20208        Self(self.0 + 1)
20209    }
20210
20211    fn previous_row(&self) -> Self {
20212        Self(self.0.saturating_sub(1))
20213    }
20214
20215    fn minus(&self, other: Self) -> u32 {
20216        self.0 - other.0
20217    }
20218}
20219
20220trait RowRangeExt {
20221    type Row;
20222
20223    fn len(&self) -> usize;
20224
20225    fn iter_rows(&self) -> impl DoubleEndedIterator<Item = Self::Row>;
20226}
20227
20228impl RowRangeExt for Range<MultiBufferRow> {
20229    type Row = MultiBufferRow;
20230
20231    fn len(&self) -> usize {
20232        (self.end.0 - self.start.0) as usize
20233    }
20234
20235    fn iter_rows(&self) -> impl DoubleEndedIterator<Item = MultiBufferRow> {
20236        (self.start.0..self.end.0).map(MultiBufferRow)
20237    }
20238}
20239
20240impl RowRangeExt for Range<DisplayRow> {
20241    type Row = DisplayRow;
20242
20243    fn len(&self) -> usize {
20244        (self.end.0 - self.start.0) as usize
20245    }
20246
20247    fn iter_rows(&self) -> impl DoubleEndedIterator<Item = DisplayRow> {
20248        (self.start.0..self.end.0).map(DisplayRow)
20249    }
20250}
20251
20252/// If select range has more than one line, we
20253/// just point the cursor to range.start.
20254fn collapse_multiline_range(range: Range<Point>) -> Range<Point> {
20255    if range.start.row == range.end.row {
20256        range
20257    } else {
20258        range.start..range.start
20259    }
20260}
20261pub struct KillRing(ClipboardItem);
20262impl Global for KillRing {}
20263
20264const UPDATE_DEBOUNCE: Duration = Duration::from_millis(50);
20265
20266enum BreakpointPromptEditAction {
20267    Log,
20268    Condition,
20269    HitCondition,
20270}
20271
20272struct BreakpointPromptEditor {
20273    pub(crate) prompt: Entity<Editor>,
20274    editor: WeakEntity<Editor>,
20275    breakpoint_anchor: Anchor,
20276    breakpoint: Breakpoint,
20277    edit_action: BreakpointPromptEditAction,
20278    block_ids: HashSet<CustomBlockId>,
20279    gutter_dimensions: Arc<Mutex<GutterDimensions>>,
20280    _subscriptions: Vec<Subscription>,
20281}
20282
20283impl BreakpointPromptEditor {
20284    const MAX_LINES: u8 = 4;
20285
20286    fn new(
20287        editor: WeakEntity<Editor>,
20288        breakpoint_anchor: Anchor,
20289        breakpoint: Breakpoint,
20290        edit_action: BreakpointPromptEditAction,
20291        window: &mut Window,
20292        cx: &mut Context<Self>,
20293    ) -> Self {
20294        let base_text = match edit_action {
20295            BreakpointPromptEditAction::Log => breakpoint.message.as_ref(),
20296            BreakpointPromptEditAction::Condition => breakpoint.condition.as_ref(),
20297            BreakpointPromptEditAction::HitCondition => breakpoint.hit_condition.as_ref(),
20298        }
20299        .map(|msg| msg.to_string())
20300        .unwrap_or_default();
20301
20302        let buffer = cx.new(|cx| Buffer::local(base_text, cx));
20303        let buffer = cx.new(|cx| MultiBuffer::singleton(buffer, cx));
20304
20305        let prompt = cx.new(|cx| {
20306            let mut prompt = Editor::new(
20307                EditorMode::AutoHeight {
20308                    max_lines: Self::MAX_LINES as usize,
20309                },
20310                buffer,
20311                None,
20312                window,
20313                cx,
20314            );
20315            prompt.set_soft_wrap_mode(language::language_settings::SoftWrap::EditorWidth, cx);
20316            prompt.set_show_cursor_when_unfocused(false, cx);
20317            prompt.set_placeholder_text(
20318                match edit_action {
20319                    BreakpointPromptEditAction::Log => "Message to log when a breakpoint is hit. Expressions within {} are interpolated.",
20320                    BreakpointPromptEditAction::Condition => "Condition when a breakpoint is hit. Expressions within {} are interpolated.",
20321                    BreakpointPromptEditAction::HitCondition => "How many breakpoint hits to ignore",
20322                },
20323                cx,
20324            );
20325
20326            prompt
20327        });
20328
20329        Self {
20330            prompt,
20331            editor,
20332            breakpoint_anchor,
20333            breakpoint,
20334            edit_action,
20335            gutter_dimensions: Arc::new(Mutex::new(GutterDimensions::default())),
20336            block_ids: Default::default(),
20337            _subscriptions: vec![],
20338        }
20339    }
20340
20341    pub(crate) fn add_block_ids(&mut self, block_ids: Vec<CustomBlockId>) {
20342        self.block_ids.extend(block_ids)
20343    }
20344
20345    fn confirm(&mut self, _: &menu::Confirm, window: &mut Window, cx: &mut Context<Self>) {
20346        if let Some(editor) = self.editor.upgrade() {
20347            let message = self
20348                .prompt
20349                .read(cx)
20350                .buffer
20351                .read(cx)
20352                .as_singleton()
20353                .expect("A multi buffer in breakpoint prompt isn't possible")
20354                .read(cx)
20355                .as_rope()
20356                .to_string();
20357
20358            editor.update(cx, |editor, cx| {
20359                editor.edit_breakpoint_at_anchor(
20360                    self.breakpoint_anchor,
20361                    self.breakpoint.clone(),
20362                    match self.edit_action {
20363                        BreakpointPromptEditAction::Log => {
20364                            BreakpointEditAction::EditLogMessage(message.into())
20365                        }
20366                        BreakpointPromptEditAction::Condition => {
20367                            BreakpointEditAction::EditCondition(message.into())
20368                        }
20369                        BreakpointPromptEditAction::HitCondition => {
20370                            BreakpointEditAction::EditHitCondition(message.into())
20371                        }
20372                    },
20373                    cx,
20374                );
20375
20376                editor.remove_blocks(self.block_ids.clone(), None, cx);
20377                cx.focus_self(window);
20378            });
20379        }
20380    }
20381
20382    fn cancel(&mut self, _: &menu::Cancel, window: &mut Window, cx: &mut Context<Self>) {
20383        self.editor
20384            .update(cx, |editor, cx| {
20385                editor.remove_blocks(self.block_ids.clone(), None, cx);
20386                window.focus(&editor.focus_handle);
20387            })
20388            .log_err();
20389    }
20390
20391    fn render_prompt_editor(&self, cx: &mut Context<Self>) -> impl IntoElement {
20392        let settings = ThemeSettings::get_global(cx);
20393        let text_style = TextStyle {
20394            color: if self.prompt.read(cx).read_only(cx) {
20395                cx.theme().colors().text_disabled
20396            } else {
20397                cx.theme().colors().text
20398            },
20399            font_family: settings.buffer_font.family.clone(),
20400            font_fallbacks: settings.buffer_font.fallbacks.clone(),
20401            font_size: settings.buffer_font_size(cx).into(),
20402            font_weight: settings.buffer_font.weight,
20403            line_height: relative(settings.buffer_line_height.value()),
20404            ..Default::default()
20405        };
20406        EditorElement::new(
20407            &self.prompt,
20408            EditorStyle {
20409                background: cx.theme().colors().editor_background,
20410                local_player: cx.theme().players().local(),
20411                text: text_style,
20412                ..Default::default()
20413            },
20414        )
20415    }
20416}
20417
20418impl Render for BreakpointPromptEditor {
20419    fn render(&mut self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
20420        let gutter_dimensions = *self.gutter_dimensions.lock();
20421        h_flex()
20422            .key_context("Editor")
20423            .bg(cx.theme().colors().editor_background)
20424            .border_y_1()
20425            .border_color(cx.theme().status().info_border)
20426            .size_full()
20427            .py(window.line_height() / 2.5)
20428            .on_action(cx.listener(Self::confirm))
20429            .on_action(cx.listener(Self::cancel))
20430            .child(h_flex().w(gutter_dimensions.full_width() + (gutter_dimensions.margin / 2.0)))
20431            .child(div().flex_1().child(self.render_prompt_editor(cx)))
20432    }
20433}
20434
20435impl Focusable for BreakpointPromptEditor {
20436    fn focus_handle(&self, cx: &App) -> FocusHandle {
20437        self.prompt.focus_handle(cx)
20438    }
20439}
20440
20441fn all_edits_insertions_or_deletions(
20442    edits: &Vec<(Range<Anchor>, String)>,
20443    snapshot: &MultiBufferSnapshot,
20444) -> bool {
20445    let mut all_insertions = true;
20446    let mut all_deletions = true;
20447
20448    for (range, new_text) in edits.iter() {
20449        let range_is_empty = range.to_offset(&snapshot).is_empty();
20450        let text_is_empty = new_text.is_empty();
20451
20452        if range_is_empty != text_is_empty {
20453            if range_is_empty {
20454                all_deletions = false;
20455            } else {
20456                all_insertions = false;
20457            }
20458        } else {
20459            return false;
20460        }
20461
20462        if !all_insertions && !all_deletions {
20463            return false;
20464        }
20465    }
20466    all_insertions || all_deletions
20467}
20468
20469struct MissingEditPredictionKeybindingTooltip;
20470
20471impl Render for MissingEditPredictionKeybindingTooltip {
20472    fn render(&mut self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
20473        ui::tooltip_container(window, cx, |container, _, cx| {
20474            container
20475                .flex_shrink_0()
20476                .max_w_80()
20477                .min_h(rems_from_px(124.))
20478                .justify_between()
20479                .child(
20480                    v_flex()
20481                        .flex_1()
20482                        .text_ui_sm(cx)
20483                        .child(Label::new("Conflict with Accept Keybinding"))
20484                        .child("Your keymap currently overrides the default accept keybinding. To continue, assign one keybinding for the `editor::AcceptEditPrediction` action.")
20485                )
20486                .child(
20487                    h_flex()
20488                        .pb_1()
20489                        .gap_1()
20490                        .items_end()
20491                        .w_full()
20492                        .child(Button::new("open-keymap", "Assign Keybinding").size(ButtonSize::Compact).on_click(|_ev, window, cx| {
20493                            window.dispatch_action(zed_actions::OpenKeymap.boxed_clone(), cx)
20494                        }))
20495                        .child(Button::new("see-docs", "See Docs").size(ButtonSize::Compact).on_click(|_ev, _window, cx| {
20496                            cx.open_url("https://zed.dev/docs/completions#edit-predictions-missing-keybinding");
20497                        })),
20498                )
20499        })
20500    }
20501}
20502
20503#[derive(Debug, Clone, Copy, PartialEq)]
20504pub struct LineHighlight {
20505    pub background: Background,
20506    pub border: Option<gpui::Hsla>,
20507}
20508
20509impl From<Hsla> for LineHighlight {
20510    fn from(hsla: Hsla) -> Self {
20511        Self {
20512            background: hsla.into(),
20513            border: None,
20514        }
20515    }
20516}
20517
20518impl From<Background> for LineHighlight {
20519    fn from(background: Background) -> Self {
20520        Self {
20521            background,
20522            border: None,
20523        }
20524    }
20525}
20526
20527fn render_diff_hunk_controls(
20528    row: u32,
20529    status: &DiffHunkStatus,
20530    hunk_range: Range<Anchor>,
20531    is_created_file: bool,
20532    line_height: Pixels,
20533    editor: &Entity<Editor>,
20534    _window: &mut Window,
20535    cx: &mut App,
20536) -> AnyElement {
20537    h_flex()
20538        .h(line_height)
20539        .mr_1()
20540        .gap_1()
20541        .px_0p5()
20542        .pb_1()
20543        .border_x_1()
20544        .border_b_1()
20545        .border_color(cx.theme().colors().border_variant)
20546        .rounded_b_lg()
20547        .bg(cx.theme().colors().editor_background)
20548        .gap_1()
20549        .occlude()
20550        .shadow_md()
20551        .child(if status.has_secondary_hunk() {
20552            Button::new(("stage", row as u64), "Stage")
20553                .alpha(if status.is_pending() { 0.66 } else { 1.0 })
20554                .tooltip({
20555                    let focus_handle = editor.focus_handle(cx);
20556                    move |window, cx| {
20557                        Tooltip::for_action_in(
20558                            "Stage Hunk",
20559                            &::git::ToggleStaged,
20560                            &focus_handle,
20561                            window,
20562                            cx,
20563                        )
20564                    }
20565                })
20566                .on_click({
20567                    let editor = editor.clone();
20568                    move |_event, _window, cx| {
20569                        editor.update(cx, |editor, cx| {
20570                            editor.stage_or_unstage_diff_hunks(
20571                                true,
20572                                vec![hunk_range.start..hunk_range.start],
20573                                cx,
20574                            );
20575                        });
20576                    }
20577                })
20578        } else {
20579            Button::new(("unstage", row as u64), "Unstage")
20580                .alpha(if status.is_pending() { 0.66 } else { 1.0 })
20581                .tooltip({
20582                    let focus_handle = editor.focus_handle(cx);
20583                    move |window, cx| {
20584                        Tooltip::for_action_in(
20585                            "Unstage Hunk",
20586                            &::git::ToggleStaged,
20587                            &focus_handle,
20588                            window,
20589                            cx,
20590                        )
20591                    }
20592                })
20593                .on_click({
20594                    let editor = editor.clone();
20595                    move |_event, _window, cx| {
20596                        editor.update(cx, |editor, cx| {
20597                            editor.stage_or_unstage_diff_hunks(
20598                                false,
20599                                vec![hunk_range.start..hunk_range.start],
20600                                cx,
20601                            );
20602                        });
20603                    }
20604                })
20605        })
20606        .child(
20607            Button::new(("restore", row as u64), "Restore")
20608                .tooltip({
20609                    let focus_handle = editor.focus_handle(cx);
20610                    move |window, cx| {
20611                        Tooltip::for_action_in(
20612                            "Restore Hunk",
20613                            &::git::Restore,
20614                            &focus_handle,
20615                            window,
20616                            cx,
20617                        )
20618                    }
20619                })
20620                .on_click({
20621                    let editor = editor.clone();
20622                    move |_event, window, cx| {
20623                        editor.update(cx, |editor, cx| {
20624                            let snapshot = editor.snapshot(window, cx);
20625                            let point = hunk_range.start.to_point(&snapshot.buffer_snapshot);
20626                            editor.restore_hunks_in_ranges(vec![point..point], window, cx);
20627                        });
20628                    }
20629                })
20630                .disabled(is_created_file),
20631        )
20632        .when(
20633            !editor.read(cx).buffer().read(cx).all_diff_hunks_expanded(),
20634            |el| {
20635                el.child(
20636                    IconButton::new(("next-hunk", row as u64), IconName::ArrowDown)
20637                        .shape(IconButtonShape::Square)
20638                        .icon_size(IconSize::Small)
20639                        // .disabled(!has_multiple_hunks)
20640                        .tooltip({
20641                            let focus_handle = editor.focus_handle(cx);
20642                            move |window, cx| {
20643                                Tooltip::for_action_in(
20644                                    "Next Hunk",
20645                                    &GoToHunk,
20646                                    &focus_handle,
20647                                    window,
20648                                    cx,
20649                                )
20650                            }
20651                        })
20652                        .on_click({
20653                            let editor = editor.clone();
20654                            move |_event, window, cx| {
20655                                editor.update(cx, |editor, cx| {
20656                                    let snapshot = editor.snapshot(window, cx);
20657                                    let position =
20658                                        hunk_range.end.to_point(&snapshot.buffer_snapshot);
20659                                    editor.go_to_hunk_before_or_after_position(
20660                                        &snapshot,
20661                                        position,
20662                                        Direction::Next,
20663                                        window,
20664                                        cx,
20665                                    );
20666                                    editor.expand_selected_diff_hunks(cx);
20667                                });
20668                            }
20669                        }),
20670                )
20671                .child(
20672                    IconButton::new(("prev-hunk", row as u64), IconName::ArrowUp)
20673                        .shape(IconButtonShape::Square)
20674                        .icon_size(IconSize::Small)
20675                        // .disabled(!has_multiple_hunks)
20676                        .tooltip({
20677                            let focus_handle = editor.focus_handle(cx);
20678                            move |window, cx| {
20679                                Tooltip::for_action_in(
20680                                    "Previous Hunk",
20681                                    &GoToPreviousHunk,
20682                                    &focus_handle,
20683                                    window,
20684                                    cx,
20685                                )
20686                            }
20687                        })
20688                        .on_click({
20689                            let editor = editor.clone();
20690                            move |_event, window, cx| {
20691                                editor.update(cx, |editor, cx| {
20692                                    let snapshot = editor.snapshot(window, cx);
20693                                    let point =
20694                                        hunk_range.start.to_point(&snapshot.buffer_snapshot);
20695                                    editor.go_to_hunk_before_or_after_position(
20696                                        &snapshot,
20697                                        point,
20698                                        Direction::Prev,
20699                                        window,
20700                                        cx,
20701                                    );
20702                                    editor.expand_selected_diff_hunks(cx);
20703                                });
20704                            }
20705                        }),
20706                )
20707            },
20708        )
20709        .into_any_element()
20710}