editor.rs

    1#![allow(rustdoc::private_intra_doc_links)]
    2//! This is the place where everything editor-related is stored (data-wise) and displayed (ui-wise).
    3//! The main point of interest in this crate is [`Editor`] type, which is used in every other Zed part as a user input element.
    4//! It comes in different flavors: single line, multiline and a fixed height one.
    5//!
    6//! Editor contains of multiple large submodules:
    7//! * [`element`] — the place where all rendering happens
    8//! * [`display_map`] - chunks up text in the editor into the logical blocks, establishes coordinates and mapping between each of them.
    9//!   Contains all metadata related to text transformations (folds, fake inlay text insertions, soft wraps, tab markup, etc.).
   10//! * [`inlay_hint_cache`] - is a storage of inlay hints out of LSP requests, responsible for querying LSP and updating `display_map`'s state accordingly.
   11//!
   12//! All other submodules and structs are mostly concerned with holding editor data about the way it displays current buffer region(s).
   13//!
   14//! If you're looking to improve Vim mode, you should check out Vim crate that wraps Editor and overrides its behavior.
   15pub mod actions;
   16mod blink_manager;
   17mod clangd_ext;
   18mod code_context_menus;
   19pub mod display_map;
   20mod editor_settings;
   21mod editor_settings_controls;
   22mod element;
   23mod git;
   24mod highlight_matching_bracket;
   25mod hover_links;
   26pub mod hover_popover;
   27mod indent_guides;
   28mod inlay_hint_cache;
   29pub mod items;
   30mod jsx_tag_auto_close;
   31mod linked_editing_ranges;
   32mod lsp_ext;
   33mod mouse_context_menu;
   34pub mod movement;
   35mod persistence;
   36mod proposed_changes_editor;
   37mod rust_analyzer_ext;
   38pub mod scroll;
   39mod selections_collection;
   40pub mod tasks;
   41
   42#[cfg(test)]
   43mod editor_tests;
   44#[cfg(test)]
   45mod inline_completion_tests;
   46mod signature_help;
   47#[cfg(any(test, feature = "test-support"))]
   48pub mod test;
   49
   50pub(crate) use actions::*;
   51pub use actions::{AcceptEditPrediction, OpenExcerpts, OpenExcerptsSplit};
   52use aho_corasick::AhoCorasick;
   53use anyhow::{Context as _, Result, anyhow};
   54use blink_manager::BlinkManager;
   55use buffer_diff::DiffHunkStatus;
   56use client::{Collaborator, ParticipantIndex};
   57use clock::ReplicaId;
   58use collections::{BTreeMap, HashMap, HashSet, VecDeque};
   59use convert_case::{Case, Casing};
   60use display_map::*;
   61pub use display_map::{ChunkRenderer, ChunkRendererContext, DisplayPoint, FoldPlaceholder};
   62use editor_settings::GoToDefinitionFallback;
   63pub use editor_settings::{
   64    CurrentLineHighlight, EditorSettings, HideMouseMode, ScrollBeyondLastLine, SearchSettings,
   65    ShowScrollbar,
   66};
   67pub use editor_settings_controls::*;
   68use element::{AcceptEditPredictionBinding, LineWithInvisibles, PositionMap, layout_line};
   69pub use element::{
   70    CursorLayout, EditorElement, HighlightedRange, HighlightedRangeLine, PointForPosition,
   71};
   72use feature_flags::{Debugger, FeatureFlagAppExt};
   73use futures::{
   74    FutureExt,
   75    future::{self, Shared, join},
   76};
   77use fuzzy::StringMatchCandidate;
   78
   79use ::git::Restore;
   80use code_context_menus::{
   81    AvailableCodeAction, CodeActionContents, CodeActionsItem, CodeActionsMenu, CodeContextMenu,
   82    CompletionsMenu, ContextMenuOrigin,
   83};
   84use git::blame::{GitBlame, GlobalBlameRenderer};
   85use gpui::{
   86    Action, Animation, AnimationExt, AnyElement, AnyWeakEntity, App, AppContext,
   87    AsyncWindowContext, AvailableSpace, Background, Bounds, ClickEvent, ClipboardEntry,
   88    ClipboardItem, Context, DispatchPhase, Edges, Entity, EntityInputHandler, EventEmitter,
   89    FocusHandle, FocusOutEvent, Focusable, FontId, FontWeight, Global, HighlightStyle, Hsla,
   90    KeyContext, Modifiers, MouseButton, MouseDownEvent, PaintQuad, ParentElement, Pixels, Render,
   91    SharedString, Size, Stateful, Styled, Subscription, Task, TextStyle, TextStyleRefinement,
   92    UTF16Selection, UnderlineStyle, UniformListScrollHandle, WeakEntity, WeakFocusHandle, Window,
   93    div, impl_actions, point, prelude::*, pulsating_between, px, relative, size,
   94};
   95use highlight_matching_bracket::refresh_matching_bracket_highlights;
   96use hover_links::{HoverLink, HoveredLinkState, InlayHighlight, find_file};
   97pub use hover_popover::hover_markdown_style;
   98use hover_popover::{HoverState, hide_hover};
   99use indent_guides::ActiveIndentGuidesState;
  100use inlay_hint_cache::{InlayHintCache, InlaySplice, InvalidationStrategy};
  101pub use inline_completion::Direction;
  102use inline_completion::{EditPredictionProvider, InlineCompletionProviderHandle};
  103pub use items::MAX_TAB_TITLE_LEN;
  104use itertools::Itertools;
  105use language::{
  106    AutoindentMode, BracketMatch, BracketPair, Buffer, Capability, CharKind, CodeLabel,
  107    CursorShape, DiagnosticEntry, DiffOptions, EditPredictionsMode, EditPreview, HighlightedText,
  108    IndentKind, IndentSize, Language, OffsetRangeExt, Point, Selection, SelectionGoal, TextObject,
  109    TransactionId, TreeSitterOptions, WordsQuery,
  110    language_settings::{
  111        self, InlayHintSettings, LspInsertMode, RewrapBehavior, WordsCompletionMode,
  112        all_language_settings, language_settings,
  113    },
  114    point_from_lsp, text_diff_with_options,
  115};
  116use language::{BufferRow, CharClassifier, Runnable, RunnableRange, point_to_lsp};
  117use linked_editing_ranges::refresh_linked_ranges;
  118use mouse_context_menu::MouseContextMenu;
  119use persistence::DB;
  120use project::{
  121    ProjectPath,
  122    debugger::breakpoint_store::{
  123        BreakpointEditAction, BreakpointState, BreakpointStore, BreakpointStoreEvent,
  124    },
  125};
  126
  127pub use git::blame::BlameRenderer;
  128pub use proposed_changes_editor::{
  129    ProposedChangeLocation, ProposedChangesEditor, ProposedChangesEditorToolbar,
  130};
  131use smallvec::smallvec;
  132use std::{cell::OnceCell, iter::Peekable};
  133use task::{ResolvedTask, RunnableTag, TaskTemplate, TaskVariables};
  134
  135pub use lsp::CompletionContext;
  136use lsp::{
  137    CodeActionKind, CompletionItemKind, CompletionTriggerKind, DiagnosticSeverity,
  138    InsertTextFormat, InsertTextMode, LanguageServerId, LanguageServerName,
  139};
  140
  141use language::BufferSnapshot;
  142pub use lsp_ext::lsp_tasks;
  143use movement::TextLayoutDetails;
  144pub use multi_buffer::{
  145    Anchor, AnchorRangeExt, ExcerptId, ExcerptRange, MultiBuffer, MultiBufferSnapshot, PathKey,
  146    RowInfo, ToOffset, ToPoint,
  147};
  148use multi_buffer::{
  149    ExcerptInfo, ExpandExcerptDirection, MultiBufferDiffHunk, MultiBufferPoint, MultiBufferRow,
  150    MultiOrSingleBufferOffsetRange, ToOffsetUtf16,
  151};
  152use parking_lot::Mutex;
  153use project::{
  154    CodeAction, Completion, CompletionIntent, CompletionSource, DocumentHighlight, InlayHint,
  155    Location, LocationLink, PrepareRenameResponse, Project, ProjectItem, ProjectTransaction,
  156    TaskSourceKind,
  157    debugger::breakpoint_store::Breakpoint,
  158    lsp_store::{CompletionDocumentation, FormatTrigger, LspFormatTarget, OpenLspBufferHandle},
  159    project_settings::{GitGutterSetting, ProjectSettings},
  160};
  161use rand::prelude::*;
  162use rpc::{ErrorExt, proto::*};
  163use scroll::{Autoscroll, OngoingScroll, ScrollAnchor, ScrollManager, ScrollbarAutoHide};
  164use selections_collection::{
  165    MutableSelectionsCollection, SelectionsCollection, resolve_selections,
  166};
  167use serde::{Deserialize, Serialize};
  168use settings::{Settings, SettingsLocation, SettingsStore, update_settings_file};
  169use smallvec::SmallVec;
  170use snippet::Snippet;
  171use std::sync::Arc;
  172use std::{
  173    any::TypeId,
  174    borrow::Cow,
  175    cell::RefCell,
  176    cmp::{self, Ordering, Reverse},
  177    mem,
  178    num::NonZeroU32,
  179    ops::{ControlFlow, Deref, DerefMut, Not as _, Range, RangeInclusive},
  180    path::{Path, PathBuf},
  181    rc::Rc,
  182    time::{Duration, Instant},
  183};
  184pub use sum_tree::Bias;
  185use sum_tree::TreeMap;
  186use text::{BufferId, FromAnchor, OffsetUtf16, Rope};
  187use theme::{
  188    ActiveTheme, PlayerColor, StatusColors, SyntaxTheme, ThemeColors, ThemeSettings,
  189    observe_buffer_font_size_adjustment,
  190};
  191use ui::{
  192    ButtonSize, ButtonStyle, ContextMenu, Disclosure, IconButton, IconButtonShape, IconName,
  193    IconSize, Key, Tooltip, h_flex, prelude::*,
  194};
  195use util::{RangeExt, ResultExt, TryFutureExt, maybe, post_inc};
  196use workspace::{
  197    Item as WorkspaceItem, ItemId, ItemNavHistory, OpenInTerminal, OpenTerminal,
  198    RestoreOnStartupBehavior, SERIALIZATION_THROTTLE_TIME, SplitDirection, TabBarSettings, Toast,
  199    ViewId, Workspace, WorkspaceId, WorkspaceSettings,
  200    item::{ItemHandle, PreviewTabsSettings},
  201    notifications::{DetachAndPromptErr, NotificationId, NotifyTaskExt},
  202    searchable::SearchEvent,
  203};
  204
  205use crate::hover_links::{find_url, find_url_from_range};
  206use crate::signature_help::{SignatureHelpHiddenBy, SignatureHelpState};
  207
  208pub const FILE_HEADER_HEIGHT: u32 = 2;
  209pub const MULTI_BUFFER_EXCERPT_HEADER_HEIGHT: u32 = 1;
  210pub const DEFAULT_MULTIBUFFER_CONTEXT: u32 = 2;
  211const CURSOR_BLINK_INTERVAL: Duration = Duration::from_millis(500);
  212const MAX_LINE_LEN: usize = 1024;
  213const MIN_NAVIGATION_HISTORY_ROW_DELTA: i64 = 10;
  214const MAX_SELECTION_HISTORY_LEN: usize = 1024;
  215pub(crate) const CURSORS_VISIBLE_FOR: Duration = Duration::from_millis(2000);
  216#[doc(hidden)]
  217pub const CODE_ACTIONS_DEBOUNCE_TIMEOUT: Duration = Duration::from_millis(250);
  218
  219pub(crate) const CODE_ACTION_TIMEOUT: Duration = Duration::from_secs(5);
  220pub(crate) const FORMAT_TIMEOUT: Duration = Duration::from_secs(5);
  221pub(crate) const SCROLL_CENTER_TOP_BOTTOM_DEBOUNCE_TIMEOUT: Duration = Duration::from_secs(1);
  222
  223pub(crate) const EDIT_PREDICTION_KEY_CONTEXT: &str = "edit_prediction";
  224pub(crate) const EDIT_PREDICTION_CONFLICT_KEY_CONTEXT: &str = "edit_prediction_conflict";
  225pub(crate) const MIN_LINE_NUMBER_DIGITS: u32 = 4;
  226
  227pub type RenderDiffHunkControlsFn = Arc<
  228    dyn Fn(
  229        u32,
  230        &DiffHunkStatus,
  231        Range<Anchor>,
  232        bool,
  233        Pixels,
  234        &Entity<Editor>,
  235        &mut Window,
  236        &mut App,
  237    ) -> AnyElement,
  238>;
  239
  240const COLUMNAR_SELECTION_MODIFIERS: Modifiers = Modifiers {
  241    alt: true,
  242    shift: true,
  243    control: false,
  244    platform: false,
  245    function: false,
  246};
  247
  248#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
  249pub enum InlayId {
  250    InlineCompletion(usize),
  251    Hint(usize),
  252}
  253
  254impl InlayId {
  255    fn id(&self) -> usize {
  256        match self {
  257            Self::InlineCompletion(id) => *id,
  258            Self::Hint(id) => *id,
  259        }
  260    }
  261}
  262
  263pub enum DebugCurrentRowHighlight {}
  264enum DocumentHighlightRead {}
  265enum DocumentHighlightWrite {}
  266enum InputComposition {}
  267enum SelectedTextHighlight {}
  268
  269#[derive(Debug, Copy, Clone, PartialEq, Eq)]
  270pub enum Navigated {
  271    Yes,
  272    No,
  273}
  274
  275impl Navigated {
  276    pub fn from_bool(yes: bool) -> Navigated {
  277        if yes { Navigated::Yes } else { Navigated::No }
  278    }
  279}
  280
  281#[derive(Debug, Clone, PartialEq, Eq)]
  282enum DisplayDiffHunk {
  283    Folded {
  284        display_row: DisplayRow,
  285    },
  286    Unfolded {
  287        is_created_file: bool,
  288        diff_base_byte_range: Range<usize>,
  289        display_row_range: Range<DisplayRow>,
  290        multi_buffer_range: Range<Anchor>,
  291        status: DiffHunkStatus,
  292    },
  293}
  294
  295pub enum HideMouseCursorOrigin {
  296    TypingAction,
  297    MovementAction,
  298}
  299
  300pub fn init_settings(cx: &mut App) {
  301    EditorSettings::register(cx);
  302}
  303
  304pub fn init(cx: &mut App) {
  305    init_settings(cx);
  306
  307    cx.set_global(GlobalBlameRenderer(Arc::new(())));
  308
  309    workspace::register_project_item::<Editor>(cx);
  310    workspace::FollowableViewRegistry::register::<Editor>(cx);
  311    workspace::register_serializable_item::<Editor>(cx);
  312
  313    cx.observe_new(
  314        |workspace: &mut Workspace, _: Option<&mut Window>, _cx: &mut Context<Workspace>| {
  315            workspace.register_action(Editor::new_file);
  316            workspace.register_action(Editor::new_file_vertical);
  317            workspace.register_action(Editor::new_file_horizontal);
  318            workspace.register_action(Editor::cancel_language_server_work);
  319        },
  320    )
  321    .detach();
  322
  323    cx.on_action(move |_: &workspace::NewFile, cx| {
  324        let app_state = workspace::AppState::global(cx);
  325        if let Some(app_state) = app_state.upgrade() {
  326            workspace::open_new(
  327                Default::default(),
  328                app_state,
  329                cx,
  330                |workspace, window, cx| {
  331                    Editor::new_file(workspace, &Default::default(), window, cx)
  332                },
  333            )
  334            .detach();
  335        }
  336    });
  337    cx.on_action(move |_: &workspace::NewWindow, cx| {
  338        let app_state = workspace::AppState::global(cx);
  339        if let Some(app_state) = app_state.upgrade() {
  340            workspace::open_new(
  341                Default::default(),
  342                app_state,
  343                cx,
  344                |workspace, window, cx| {
  345                    cx.activate(true);
  346                    Editor::new_file(workspace, &Default::default(), window, cx)
  347                },
  348            )
  349            .detach();
  350        }
  351    });
  352}
  353
  354pub fn set_blame_renderer(renderer: impl BlameRenderer + 'static, cx: &mut App) {
  355    cx.set_global(GlobalBlameRenderer(Arc::new(renderer)));
  356}
  357
  358pub trait DiagnosticRenderer {
  359    fn render_group(
  360        &self,
  361        diagnostic_group: Vec<DiagnosticEntry<Point>>,
  362        buffer_id: BufferId,
  363        snapshot: EditorSnapshot,
  364        editor: WeakEntity<Editor>,
  365        cx: &mut App,
  366    ) -> Vec<BlockProperties<Anchor>>;
  367}
  368
  369pub(crate) struct GlobalDiagnosticRenderer(pub Arc<dyn DiagnosticRenderer>);
  370
  371impl gpui::Global for GlobalDiagnosticRenderer {}
  372pub fn set_diagnostic_renderer(renderer: impl DiagnosticRenderer + 'static, cx: &mut App) {
  373    cx.set_global(GlobalDiagnosticRenderer(Arc::new(renderer)));
  374}
  375
  376pub struct SearchWithinRange;
  377
  378trait InvalidationRegion {
  379    fn ranges(&self) -> &[Range<Anchor>];
  380}
  381
  382#[derive(Clone, Debug, PartialEq)]
  383pub enum SelectPhase {
  384    Begin {
  385        position: DisplayPoint,
  386        add: bool,
  387        click_count: usize,
  388    },
  389    BeginColumnar {
  390        position: DisplayPoint,
  391        reset: bool,
  392        goal_column: u32,
  393    },
  394    Extend {
  395        position: DisplayPoint,
  396        click_count: usize,
  397    },
  398    Update {
  399        position: DisplayPoint,
  400        goal_column: u32,
  401        scroll_delta: gpui::Point<f32>,
  402    },
  403    End,
  404}
  405
  406#[derive(Clone, Debug)]
  407pub enum SelectMode {
  408    Character,
  409    Word(Range<Anchor>),
  410    Line(Range<Anchor>),
  411    All,
  412}
  413
  414#[derive(Copy, Clone, PartialEq, Eq, Debug)]
  415pub enum EditorMode {
  416    SingleLine {
  417        auto_width: bool,
  418    },
  419    AutoHeight {
  420        max_lines: usize,
  421    },
  422    Full {
  423        /// When set to `true`, the editor will scale its UI elements with the buffer font size.
  424        scale_ui_elements_with_buffer_font_size: bool,
  425        /// When set to `true`, the editor will render a background for the active line.
  426        show_active_line_background: bool,
  427    },
  428}
  429
  430impl EditorMode {
  431    pub fn full() -> Self {
  432        Self::Full {
  433            scale_ui_elements_with_buffer_font_size: true,
  434            show_active_line_background: true,
  435        }
  436    }
  437
  438    pub fn is_full(&self) -> bool {
  439        matches!(self, Self::Full { .. })
  440    }
  441}
  442
  443#[derive(Copy, Clone, Debug)]
  444pub enum SoftWrap {
  445    /// Prefer not to wrap at all.
  446    ///
  447    /// Note: this is currently internal, as actually limited by [`crate::MAX_LINE_LEN`] until it wraps.
  448    /// The mode is used inside git diff hunks, where it's seems currently more useful to not wrap as much as possible.
  449    GitDiff,
  450    /// Prefer a single line generally, unless an overly long line is encountered.
  451    None,
  452    /// Soft wrap lines that exceed the editor width.
  453    EditorWidth,
  454    /// Soft wrap lines at the preferred line length.
  455    Column(u32),
  456    /// Soft wrap line at the preferred line length or the editor width (whichever is smaller).
  457    Bounded(u32),
  458}
  459
  460#[derive(Clone)]
  461pub struct EditorStyle {
  462    pub background: Hsla,
  463    pub local_player: PlayerColor,
  464    pub text: TextStyle,
  465    pub scrollbar_width: Pixels,
  466    pub syntax: Arc<SyntaxTheme>,
  467    pub status: StatusColors,
  468    pub inlay_hints_style: HighlightStyle,
  469    pub inline_completion_styles: InlineCompletionStyles,
  470    pub unnecessary_code_fade: f32,
  471}
  472
  473impl Default for EditorStyle {
  474    fn default() -> Self {
  475        Self {
  476            background: Hsla::default(),
  477            local_player: PlayerColor::default(),
  478            text: TextStyle::default(),
  479            scrollbar_width: Pixels::default(),
  480            syntax: Default::default(),
  481            // HACK: Status colors don't have a real default.
  482            // We should look into removing the status colors from the editor
  483            // style and retrieve them directly from the theme.
  484            status: StatusColors::dark(),
  485            inlay_hints_style: HighlightStyle::default(),
  486            inline_completion_styles: InlineCompletionStyles {
  487                insertion: HighlightStyle::default(),
  488                whitespace: HighlightStyle::default(),
  489            },
  490            unnecessary_code_fade: Default::default(),
  491        }
  492    }
  493}
  494
  495pub fn make_inlay_hints_style(cx: &mut App) -> HighlightStyle {
  496    let show_background = language_settings::language_settings(None, None, cx)
  497        .inlay_hints
  498        .show_background;
  499
  500    HighlightStyle {
  501        color: Some(cx.theme().status().hint),
  502        background_color: show_background.then(|| cx.theme().status().hint_background),
  503        ..HighlightStyle::default()
  504    }
  505}
  506
  507pub fn make_suggestion_styles(cx: &mut App) -> InlineCompletionStyles {
  508    InlineCompletionStyles {
  509        insertion: HighlightStyle {
  510            color: Some(cx.theme().status().predictive),
  511            ..HighlightStyle::default()
  512        },
  513        whitespace: HighlightStyle {
  514            background_color: Some(cx.theme().status().created_background),
  515            ..HighlightStyle::default()
  516        },
  517    }
  518}
  519
  520type CompletionId = usize;
  521
  522pub(crate) enum EditDisplayMode {
  523    TabAccept,
  524    DiffPopover,
  525    Inline,
  526}
  527
  528enum InlineCompletion {
  529    Edit {
  530        edits: Vec<(Range<Anchor>, String)>,
  531        edit_preview: Option<EditPreview>,
  532        display_mode: EditDisplayMode,
  533        snapshot: BufferSnapshot,
  534    },
  535    Move {
  536        target: Anchor,
  537        snapshot: BufferSnapshot,
  538    },
  539}
  540
  541struct InlineCompletionState {
  542    inlay_ids: Vec<InlayId>,
  543    completion: InlineCompletion,
  544    completion_id: Option<SharedString>,
  545    invalidation_range: Range<Anchor>,
  546}
  547
  548enum EditPredictionSettings {
  549    Disabled,
  550    Enabled {
  551        show_in_menu: bool,
  552        preview_requires_modifier: bool,
  553    },
  554}
  555
  556enum InlineCompletionHighlight {}
  557
  558#[derive(Debug, Clone)]
  559struct InlineDiagnostic {
  560    message: SharedString,
  561    group_id: usize,
  562    is_primary: bool,
  563    start: Point,
  564    severity: DiagnosticSeverity,
  565}
  566
  567pub enum MenuInlineCompletionsPolicy {
  568    Never,
  569    ByProvider,
  570}
  571
  572pub enum EditPredictionPreview {
  573    /// Modifier is not pressed
  574    Inactive { released_too_fast: bool },
  575    /// Modifier pressed
  576    Active {
  577        since: Instant,
  578        previous_scroll_position: Option<ScrollAnchor>,
  579    },
  580}
  581
  582impl EditPredictionPreview {
  583    pub fn released_too_fast(&self) -> bool {
  584        match self {
  585            EditPredictionPreview::Inactive { released_too_fast } => *released_too_fast,
  586            EditPredictionPreview::Active { .. } => false,
  587        }
  588    }
  589
  590    pub fn set_previous_scroll_position(&mut self, scroll_position: Option<ScrollAnchor>) {
  591        if let EditPredictionPreview::Active {
  592            previous_scroll_position,
  593            ..
  594        } = self
  595        {
  596            *previous_scroll_position = scroll_position;
  597        }
  598    }
  599}
  600
  601pub struct ContextMenuOptions {
  602    pub min_entries_visible: usize,
  603    pub max_entries_visible: usize,
  604    pub placement: Option<ContextMenuPlacement>,
  605}
  606
  607#[derive(Debug, Clone, PartialEq, Eq)]
  608pub enum ContextMenuPlacement {
  609    Above,
  610    Below,
  611}
  612
  613#[derive(Copy, Clone, Eq, PartialEq, PartialOrd, Ord, Debug, Default)]
  614struct EditorActionId(usize);
  615
  616impl EditorActionId {
  617    pub fn post_inc(&mut self) -> Self {
  618        let answer = self.0;
  619
  620        *self = Self(answer + 1);
  621
  622        Self(answer)
  623    }
  624}
  625
  626// type GetFieldEditorTheme = dyn Fn(&theme::Theme) -> theme::FieldEditor;
  627// type OverrideTextStyle = dyn Fn(&EditorStyle) -> Option<HighlightStyle>;
  628
  629type BackgroundHighlight = (fn(&ThemeColors) -> Hsla, Arc<[Range<Anchor>]>);
  630type GutterHighlight = (fn(&App) -> Hsla, Arc<[Range<Anchor>]>);
  631
  632#[derive(Default)]
  633struct ScrollbarMarkerState {
  634    scrollbar_size: Size<Pixels>,
  635    dirty: bool,
  636    markers: Arc<[PaintQuad]>,
  637    pending_refresh: Option<Task<Result<()>>>,
  638}
  639
  640impl ScrollbarMarkerState {
  641    fn should_refresh(&self, scrollbar_size: Size<Pixels>) -> bool {
  642        self.pending_refresh.is_none() && (self.scrollbar_size != scrollbar_size || self.dirty)
  643    }
  644}
  645
  646#[derive(Clone, Debug)]
  647struct RunnableTasks {
  648    templates: Vec<(TaskSourceKind, TaskTemplate)>,
  649    offset: multi_buffer::Anchor,
  650    // We need the column at which the task context evaluation should take place (when we're spawning it via gutter).
  651    column: u32,
  652    // Values of all named captures, including those starting with '_'
  653    extra_variables: HashMap<String, String>,
  654    // Full range of the tagged region. We use it to determine which `extra_variables` to grab for context resolution in e.g. a modal.
  655    context_range: Range<BufferOffset>,
  656}
  657
  658impl RunnableTasks {
  659    fn resolve<'a>(
  660        &'a self,
  661        cx: &'a task::TaskContext,
  662    ) -> impl Iterator<Item = (TaskSourceKind, ResolvedTask)> + 'a {
  663        self.templates.iter().filter_map(|(kind, template)| {
  664            template
  665                .resolve_task(&kind.to_id_base(), cx)
  666                .map(|task| (kind.clone(), task))
  667        })
  668    }
  669}
  670
  671#[derive(Clone)]
  672struct ResolvedTasks {
  673    templates: SmallVec<[(TaskSourceKind, ResolvedTask); 1]>,
  674    position: Anchor,
  675}
  676
  677#[derive(Copy, Clone, Debug, PartialEq, PartialOrd)]
  678struct BufferOffset(usize);
  679
  680// Addons allow storing per-editor state in other crates (e.g. Vim)
  681pub trait Addon: 'static {
  682    fn extend_key_context(&self, _: &mut KeyContext, _: &App) {}
  683
  684    fn render_buffer_header_controls(
  685        &self,
  686        _: &ExcerptInfo,
  687        _: &Window,
  688        _: &App,
  689    ) -> Option<AnyElement> {
  690        None
  691    }
  692
  693    fn to_any(&self) -> &dyn std::any::Any;
  694}
  695
  696/// Zed's primary implementation of text input, allowing users to edit a [`MultiBuffer`].
  697///
  698/// See the [module level documentation](self) for more information.
  699pub struct Editor {
  700    focus_handle: FocusHandle,
  701    last_focused_descendant: Option<WeakFocusHandle>,
  702    /// The text buffer being edited
  703    buffer: Entity<MultiBuffer>,
  704    /// Map of how text in the buffer should be displayed.
  705    /// Handles soft wraps, folds, fake inlay text insertions, etc.
  706    pub display_map: Entity<DisplayMap>,
  707    pub selections: SelectionsCollection,
  708    pub scroll_manager: ScrollManager,
  709    /// When inline assist editors are linked, they all render cursors because
  710    /// typing enters text into each of them, even the ones that aren't focused.
  711    pub(crate) show_cursor_when_unfocused: bool,
  712    columnar_selection_tail: Option<Anchor>,
  713    add_selections_state: Option<AddSelectionsState>,
  714    select_next_state: Option<SelectNextState>,
  715    select_prev_state: Option<SelectNextState>,
  716    selection_history: SelectionHistory,
  717    autoclose_regions: Vec<AutocloseRegion>,
  718    snippet_stack: InvalidationStack<SnippetState>,
  719    select_syntax_node_history: SelectSyntaxNodeHistory,
  720    ime_transaction: Option<TransactionId>,
  721    active_diagnostics: ActiveDiagnostic,
  722    show_inline_diagnostics: bool,
  723    inline_diagnostics_update: Task<()>,
  724    inline_diagnostics_enabled: bool,
  725    inline_diagnostics: Vec<(Anchor, InlineDiagnostic)>,
  726    soft_wrap_mode_override: Option<language_settings::SoftWrap>,
  727    hard_wrap: Option<usize>,
  728
  729    // TODO: make this a access method
  730    pub project: Option<Entity<Project>>,
  731    semantics_provider: Option<Rc<dyn SemanticsProvider>>,
  732    completion_provider: Option<Box<dyn CompletionProvider>>,
  733    collaboration_hub: Option<Box<dyn CollaborationHub>>,
  734    blink_manager: Entity<BlinkManager>,
  735    show_cursor_names: bool,
  736    hovered_cursors: HashMap<HoveredCursor, Task<()>>,
  737    pub show_local_selections: bool,
  738    mode: EditorMode,
  739    show_breadcrumbs: bool,
  740    show_gutter: bool,
  741    show_scrollbars: bool,
  742    show_line_numbers: Option<bool>,
  743    use_relative_line_numbers: Option<bool>,
  744    show_git_diff_gutter: Option<bool>,
  745    show_code_actions: Option<bool>,
  746    show_runnables: Option<bool>,
  747    show_breakpoints: Option<bool>,
  748    show_wrap_guides: Option<bool>,
  749    show_indent_guides: Option<bool>,
  750    placeholder_text: Option<Arc<str>>,
  751    highlight_order: usize,
  752    highlighted_rows: HashMap<TypeId, Vec<RowHighlight>>,
  753    background_highlights: TreeMap<TypeId, BackgroundHighlight>,
  754    gutter_highlights: TreeMap<TypeId, GutterHighlight>,
  755    scrollbar_marker_state: ScrollbarMarkerState,
  756    active_indent_guides_state: ActiveIndentGuidesState,
  757    nav_history: Option<ItemNavHistory>,
  758    context_menu: RefCell<Option<CodeContextMenu>>,
  759    context_menu_options: Option<ContextMenuOptions>,
  760    mouse_context_menu: Option<MouseContextMenu>,
  761    completion_tasks: Vec<(CompletionId, Task<Option<()>>)>,
  762    signature_help_state: SignatureHelpState,
  763    auto_signature_help: Option<bool>,
  764    find_all_references_task_sources: Vec<Anchor>,
  765    next_completion_id: CompletionId,
  766    available_code_actions: Option<(Location, Rc<[AvailableCodeAction]>)>,
  767    code_actions_task: Option<Task<Result<()>>>,
  768    selection_highlight_task: Option<Task<()>>,
  769    document_highlights_task: Option<Task<()>>,
  770    linked_editing_range_task: Option<Task<Option<()>>>,
  771    linked_edit_ranges: linked_editing_ranges::LinkedEditingRanges,
  772    pending_rename: Option<RenameState>,
  773    searchable: bool,
  774    cursor_shape: CursorShape,
  775    current_line_highlight: Option<CurrentLineHighlight>,
  776    collapse_matches: bool,
  777    autoindent_mode: Option<AutoindentMode>,
  778    workspace: Option<(WeakEntity<Workspace>, Option<WorkspaceId>)>,
  779    input_enabled: bool,
  780    use_modal_editing: bool,
  781    read_only: bool,
  782    leader_peer_id: Option<PeerId>,
  783    remote_id: Option<ViewId>,
  784    hover_state: HoverState,
  785    pending_mouse_down: Option<Rc<RefCell<Option<MouseDownEvent>>>>,
  786    gutter_hovered: bool,
  787    hovered_link_state: Option<HoveredLinkState>,
  788    edit_prediction_provider: Option<RegisteredInlineCompletionProvider>,
  789    code_action_providers: Vec<Rc<dyn CodeActionProvider>>,
  790    active_inline_completion: Option<InlineCompletionState>,
  791    /// Used to prevent flickering as the user types while the menu is open
  792    stale_inline_completion_in_menu: Option<InlineCompletionState>,
  793    edit_prediction_settings: EditPredictionSettings,
  794    inline_completions_hidden_for_vim_mode: bool,
  795    show_inline_completions_override: Option<bool>,
  796    menu_inline_completions_policy: MenuInlineCompletionsPolicy,
  797    edit_prediction_preview: EditPredictionPreview,
  798    edit_prediction_indent_conflict: bool,
  799    edit_prediction_requires_modifier_in_indent_conflict: bool,
  800    inlay_hint_cache: InlayHintCache,
  801    next_inlay_id: usize,
  802    _subscriptions: Vec<Subscription>,
  803    pixel_position_of_newest_cursor: Option<gpui::Point<Pixels>>,
  804    gutter_dimensions: GutterDimensions,
  805    style: Option<EditorStyle>,
  806    text_style_refinement: Option<TextStyleRefinement>,
  807    next_editor_action_id: EditorActionId,
  808    editor_actions:
  809        Rc<RefCell<BTreeMap<EditorActionId, Box<dyn Fn(&mut Window, &mut Context<Self>)>>>>,
  810    use_autoclose: bool,
  811    use_auto_surround: bool,
  812    auto_replace_emoji_shortcode: bool,
  813    jsx_tag_auto_close_enabled_in_any_buffer: bool,
  814    show_git_blame_gutter: bool,
  815    show_git_blame_inline: bool,
  816    show_git_blame_inline_delay_task: Option<Task<()>>,
  817    pub git_blame_inline_tooltip: Option<AnyWeakEntity>,
  818    git_blame_inline_enabled: bool,
  819    render_diff_hunk_controls: RenderDiffHunkControlsFn,
  820    serialize_dirty_buffers: bool,
  821    show_selection_menu: Option<bool>,
  822    blame: Option<Entity<GitBlame>>,
  823    blame_subscription: Option<Subscription>,
  824    custom_context_menu: Option<
  825        Box<
  826            dyn 'static
  827                + Fn(
  828                    &mut Self,
  829                    DisplayPoint,
  830                    &mut Window,
  831                    &mut Context<Self>,
  832                ) -> Option<Entity<ui::ContextMenu>>,
  833        >,
  834    >,
  835    last_bounds: Option<Bounds<Pixels>>,
  836    last_position_map: Option<Rc<PositionMap>>,
  837    expect_bounds_change: Option<Bounds<Pixels>>,
  838    tasks: BTreeMap<(BufferId, BufferRow), RunnableTasks>,
  839    tasks_update_task: Option<Task<()>>,
  840    breakpoint_store: Option<Entity<BreakpointStore>>,
  841    /// Allow's a user to create a breakpoint by selecting this indicator
  842    /// It should be None while a user is not hovering over the gutter
  843    /// Otherwise it represents the point that the breakpoint will be shown
  844    gutter_breakpoint_indicator: (Option<(DisplayPoint, bool)>, Option<Task<()>>),
  845    in_project_search: bool,
  846    previous_search_ranges: Option<Arc<[Range<Anchor>]>>,
  847    breadcrumb_header: Option<String>,
  848    focused_block: Option<FocusedBlock>,
  849    next_scroll_position: NextScrollCursorCenterTopBottom,
  850    addons: HashMap<TypeId, Box<dyn Addon>>,
  851    registered_buffers: HashMap<BufferId, OpenLspBufferHandle>,
  852    load_diff_task: Option<Shared<Task<()>>>,
  853    selection_mark_mode: bool,
  854    toggle_fold_multiple_buffers: Task<()>,
  855    _scroll_cursor_center_top_bottom_task: Task<()>,
  856    serialize_selections: Task<()>,
  857    serialize_folds: Task<()>,
  858    mouse_cursor_hidden: bool,
  859    hide_mouse_mode: HideMouseMode,
  860}
  861
  862#[derive(Copy, Clone, Debug, PartialEq, Eq, Default)]
  863enum NextScrollCursorCenterTopBottom {
  864    #[default]
  865    Center,
  866    Top,
  867    Bottom,
  868}
  869
  870impl NextScrollCursorCenterTopBottom {
  871    fn next(&self) -> Self {
  872        match self {
  873            Self::Center => Self::Top,
  874            Self::Top => Self::Bottom,
  875            Self::Bottom => Self::Center,
  876        }
  877    }
  878}
  879
  880#[derive(Clone)]
  881pub struct EditorSnapshot {
  882    pub mode: EditorMode,
  883    show_gutter: bool,
  884    show_line_numbers: Option<bool>,
  885    show_git_diff_gutter: Option<bool>,
  886    show_code_actions: Option<bool>,
  887    show_runnables: Option<bool>,
  888    show_breakpoints: Option<bool>,
  889    git_blame_gutter_max_author_length: Option<usize>,
  890    pub display_snapshot: DisplaySnapshot,
  891    pub placeholder_text: Option<Arc<str>>,
  892    is_focused: bool,
  893    scroll_anchor: ScrollAnchor,
  894    ongoing_scroll: OngoingScroll,
  895    current_line_highlight: CurrentLineHighlight,
  896    gutter_hovered: bool,
  897}
  898
  899#[derive(Default, Debug, Clone, Copy)]
  900pub struct GutterDimensions {
  901    pub left_padding: Pixels,
  902    pub right_padding: Pixels,
  903    pub width: Pixels,
  904    pub margin: Pixels,
  905    pub git_blame_entries_width: Option<Pixels>,
  906}
  907
  908impl GutterDimensions {
  909    /// The full width of the space taken up by the gutter.
  910    pub fn full_width(&self) -> Pixels {
  911        self.margin + self.width
  912    }
  913
  914    /// The width of the space reserved for the fold indicators,
  915    /// use alongside 'justify_end' and `gutter_width` to
  916    /// right align content with the line numbers
  917    pub fn fold_area_width(&self) -> Pixels {
  918        self.margin + self.right_padding
  919    }
  920}
  921
  922#[derive(Debug)]
  923pub struct RemoteSelection {
  924    pub replica_id: ReplicaId,
  925    pub selection: Selection<Anchor>,
  926    pub cursor_shape: CursorShape,
  927    pub peer_id: PeerId,
  928    pub line_mode: bool,
  929    pub participant_index: Option<ParticipantIndex>,
  930    pub user_name: Option<SharedString>,
  931}
  932
  933#[derive(Clone, Debug)]
  934struct SelectionHistoryEntry {
  935    selections: Arc<[Selection<Anchor>]>,
  936    select_next_state: Option<SelectNextState>,
  937    select_prev_state: Option<SelectNextState>,
  938    add_selections_state: Option<AddSelectionsState>,
  939}
  940
  941enum SelectionHistoryMode {
  942    Normal,
  943    Undoing,
  944    Redoing,
  945}
  946
  947#[derive(Clone, PartialEq, Eq, Hash)]
  948struct HoveredCursor {
  949    replica_id: u16,
  950    selection_id: usize,
  951}
  952
  953impl Default for SelectionHistoryMode {
  954    fn default() -> Self {
  955        Self::Normal
  956    }
  957}
  958
  959#[derive(Default)]
  960struct SelectionHistory {
  961    #[allow(clippy::type_complexity)]
  962    selections_by_transaction:
  963        HashMap<TransactionId, (Arc<[Selection<Anchor>]>, Option<Arc<[Selection<Anchor>]>>)>,
  964    mode: SelectionHistoryMode,
  965    undo_stack: VecDeque<SelectionHistoryEntry>,
  966    redo_stack: VecDeque<SelectionHistoryEntry>,
  967}
  968
  969impl SelectionHistory {
  970    fn insert_transaction(
  971        &mut self,
  972        transaction_id: TransactionId,
  973        selections: Arc<[Selection<Anchor>]>,
  974    ) {
  975        self.selections_by_transaction
  976            .insert(transaction_id, (selections, None));
  977    }
  978
  979    #[allow(clippy::type_complexity)]
  980    fn transaction(
  981        &self,
  982        transaction_id: TransactionId,
  983    ) -> Option<&(Arc<[Selection<Anchor>]>, Option<Arc<[Selection<Anchor>]>>)> {
  984        self.selections_by_transaction.get(&transaction_id)
  985    }
  986
  987    #[allow(clippy::type_complexity)]
  988    fn transaction_mut(
  989        &mut self,
  990        transaction_id: TransactionId,
  991    ) -> Option<&mut (Arc<[Selection<Anchor>]>, Option<Arc<[Selection<Anchor>]>>)> {
  992        self.selections_by_transaction.get_mut(&transaction_id)
  993    }
  994
  995    fn push(&mut self, entry: SelectionHistoryEntry) {
  996        if !entry.selections.is_empty() {
  997            match self.mode {
  998                SelectionHistoryMode::Normal => {
  999                    self.push_undo(entry);
 1000                    self.redo_stack.clear();
 1001                }
 1002                SelectionHistoryMode::Undoing => self.push_redo(entry),
 1003                SelectionHistoryMode::Redoing => self.push_undo(entry),
 1004            }
 1005        }
 1006    }
 1007
 1008    fn push_undo(&mut self, entry: SelectionHistoryEntry) {
 1009        if self
 1010            .undo_stack
 1011            .back()
 1012            .map_or(true, |e| e.selections != entry.selections)
 1013        {
 1014            self.undo_stack.push_back(entry);
 1015            if self.undo_stack.len() > MAX_SELECTION_HISTORY_LEN {
 1016                self.undo_stack.pop_front();
 1017            }
 1018        }
 1019    }
 1020
 1021    fn push_redo(&mut self, entry: SelectionHistoryEntry) {
 1022        if self
 1023            .redo_stack
 1024            .back()
 1025            .map_or(true, |e| e.selections != entry.selections)
 1026        {
 1027            self.redo_stack.push_back(entry);
 1028            if self.redo_stack.len() > MAX_SELECTION_HISTORY_LEN {
 1029                self.redo_stack.pop_front();
 1030            }
 1031        }
 1032    }
 1033}
 1034
 1035struct RowHighlight {
 1036    index: usize,
 1037    range: Range<Anchor>,
 1038    color: Hsla,
 1039    should_autoscroll: bool,
 1040}
 1041
 1042#[derive(Clone, Debug)]
 1043struct AddSelectionsState {
 1044    above: bool,
 1045    stack: Vec<usize>,
 1046}
 1047
 1048#[derive(Clone)]
 1049struct SelectNextState {
 1050    query: AhoCorasick,
 1051    wordwise: bool,
 1052    done: bool,
 1053}
 1054
 1055impl std::fmt::Debug for SelectNextState {
 1056    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
 1057        f.debug_struct(std::any::type_name::<Self>())
 1058            .field("wordwise", &self.wordwise)
 1059            .field("done", &self.done)
 1060            .finish()
 1061    }
 1062}
 1063
 1064#[derive(Debug)]
 1065struct AutocloseRegion {
 1066    selection_id: usize,
 1067    range: Range<Anchor>,
 1068    pair: BracketPair,
 1069}
 1070
 1071#[derive(Debug)]
 1072struct SnippetState {
 1073    ranges: Vec<Vec<Range<Anchor>>>,
 1074    active_index: usize,
 1075    choices: Vec<Option<Vec<String>>>,
 1076}
 1077
 1078#[doc(hidden)]
 1079pub struct RenameState {
 1080    pub range: Range<Anchor>,
 1081    pub old_name: Arc<str>,
 1082    pub editor: Entity<Editor>,
 1083    block_id: CustomBlockId,
 1084}
 1085
 1086struct InvalidationStack<T>(Vec<T>);
 1087
 1088struct RegisteredInlineCompletionProvider {
 1089    provider: Arc<dyn InlineCompletionProviderHandle>,
 1090    _subscription: Subscription,
 1091}
 1092
 1093#[derive(Debug, PartialEq, Eq)]
 1094pub struct ActiveDiagnosticGroup {
 1095    pub active_range: Range<Anchor>,
 1096    pub active_message: String,
 1097    pub group_id: usize,
 1098    pub blocks: HashSet<CustomBlockId>,
 1099}
 1100
 1101#[derive(Debug, PartialEq, Eq)]
 1102#[allow(clippy::large_enum_variant)]
 1103pub(crate) enum ActiveDiagnostic {
 1104    None,
 1105    All,
 1106    Group(ActiveDiagnosticGroup),
 1107}
 1108
 1109#[derive(Serialize, Deserialize, Clone, Debug)]
 1110pub struct ClipboardSelection {
 1111    /// The number of bytes in this selection.
 1112    pub len: usize,
 1113    /// Whether this was a full-line selection.
 1114    pub is_entire_line: bool,
 1115    /// The indentation of the first line when this content was originally copied.
 1116    pub first_line_indent: u32,
 1117}
 1118
 1119// selections, scroll behavior, was newest selection reversed
 1120type SelectSyntaxNodeHistoryState = (
 1121    Box<[Selection<usize>]>,
 1122    SelectSyntaxNodeScrollBehavior,
 1123    bool,
 1124);
 1125
 1126#[derive(Default)]
 1127struct SelectSyntaxNodeHistory {
 1128    stack: Vec<SelectSyntaxNodeHistoryState>,
 1129    // disable temporarily to allow changing selections without losing the stack
 1130    pub disable_clearing: bool,
 1131}
 1132
 1133impl SelectSyntaxNodeHistory {
 1134    pub fn try_clear(&mut self) {
 1135        if !self.disable_clearing {
 1136            self.stack.clear();
 1137        }
 1138    }
 1139
 1140    pub fn push(&mut self, selection: SelectSyntaxNodeHistoryState) {
 1141        self.stack.push(selection);
 1142    }
 1143
 1144    pub fn pop(&mut self) -> Option<SelectSyntaxNodeHistoryState> {
 1145        self.stack.pop()
 1146    }
 1147}
 1148
 1149enum SelectSyntaxNodeScrollBehavior {
 1150    CursorTop,
 1151    FitSelection,
 1152    CursorBottom,
 1153}
 1154
 1155#[derive(Debug)]
 1156pub(crate) struct NavigationData {
 1157    cursor_anchor: Anchor,
 1158    cursor_position: Point,
 1159    scroll_anchor: ScrollAnchor,
 1160    scroll_top_row: u32,
 1161}
 1162
 1163#[derive(Debug, Clone, Copy, PartialEq, Eq)]
 1164pub enum GotoDefinitionKind {
 1165    Symbol,
 1166    Declaration,
 1167    Type,
 1168    Implementation,
 1169}
 1170
 1171#[derive(Debug, Clone)]
 1172enum InlayHintRefreshReason {
 1173    ModifiersChanged(bool),
 1174    Toggle(bool),
 1175    SettingsChange(InlayHintSettings),
 1176    NewLinesShown,
 1177    BufferEdited(HashSet<Arc<Language>>),
 1178    RefreshRequested,
 1179    ExcerptsRemoved(Vec<ExcerptId>),
 1180}
 1181
 1182impl InlayHintRefreshReason {
 1183    fn description(&self) -> &'static str {
 1184        match self {
 1185            Self::ModifiersChanged(_) => "modifiers changed",
 1186            Self::Toggle(_) => "toggle",
 1187            Self::SettingsChange(_) => "settings change",
 1188            Self::NewLinesShown => "new lines shown",
 1189            Self::BufferEdited(_) => "buffer edited",
 1190            Self::RefreshRequested => "refresh requested",
 1191            Self::ExcerptsRemoved(_) => "excerpts removed",
 1192        }
 1193    }
 1194}
 1195
 1196pub enum FormatTarget {
 1197    Buffers,
 1198    Ranges(Vec<Range<MultiBufferPoint>>),
 1199}
 1200
 1201pub(crate) struct FocusedBlock {
 1202    id: BlockId,
 1203    focus_handle: WeakFocusHandle,
 1204}
 1205
 1206#[derive(Clone)]
 1207enum JumpData {
 1208    MultiBufferRow {
 1209        row: MultiBufferRow,
 1210        line_offset_from_top: u32,
 1211    },
 1212    MultiBufferPoint {
 1213        excerpt_id: ExcerptId,
 1214        position: Point,
 1215        anchor: text::Anchor,
 1216        line_offset_from_top: u32,
 1217    },
 1218}
 1219
 1220pub enum MultibufferSelectionMode {
 1221    First,
 1222    All,
 1223}
 1224
 1225#[derive(Clone, Copy, Debug, Default)]
 1226pub struct RewrapOptions {
 1227    pub override_language_settings: bool,
 1228    pub preserve_existing_whitespace: bool,
 1229}
 1230
 1231impl Editor {
 1232    pub fn single_line(window: &mut Window, cx: &mut Context<Self>) -> Self {
 1233        let buffer = cx.new(|cx| Buffer::local("", cx));
 1234        let buffer = cx.new(|cx| MultiBuffer::singleton(buffer, cx));
 1235        Self::new(
 1236            EditorMode::SingleLine { auto_width: false },
 1237            buffer,
 1238            None,
 1239            window,
 1240            cx,
 1241        )
 1242    }
 1243
 1244    pub fn multi_line(window: &mut Window, cx: &mut Context<Self>) -> Self {
 1245        let buffer = cx.new(|cx| Buffer::local("", cx));
 1246        let buffer = cx.new(|cx| MultiBuffer::singleton(buffer, cx));
 1247        Self::new(EditorMode::full(), buffer, None, window, cx)
 1248    }
 1249
 1250    pub fn auto_width(window: &mut Window, cx: &mut Context<Self>) -> Self {
 1251        let buffer = cx.new(|cx| Buffer::local("", cx));
 1252        let buffer = cx.new(|cx| MultiBuffer::singleton(buffer, cx));
 1253        Self::new(
 1254            EditorMode::SingleLine { auto_width: true },
 1255            buffer,
 1256            None,
 1257            window,
 1258            cx,
 1259        )
 1260    }
 1261
 1262    pub fn auto_height(max_lines: usize, window: &mut Window, cx: &mut Context<Self>) -> Self {
 1263        let buffer = cx.new(|cx| Buffer::local("", cx));
 1264        let buffer = cx.new(|cx| MultiBuffer::singleton(buffer, cx));
 1265        Self::new(
 1266            EditorMode::AutoHeight { max_lines },
 1267            buffer,
 1268            None,
 1269            window,
 1270            cx,
 1271        )
 1272    }
 1273
 1274    pub fn for_buffer(
 1275        buffer: Entity<Buffer>,
 1276        project: Option<Entity<Project>>,
 1277        window: &mut Window,
 1278        cx: &mut Context<Self>,
 1279    ) -> Self {
 1280        let buffer = cx.new(|cx| MultiBuffer::singleton(buffer, cx));
 1281        Self::new(EditorMode::full(), buffer, project, window, cx)
 1282    }
 1283
 1284    pub fn for_multibuffer(
 1285        buffer: Entity<MultiBuffer>,
 1286        project: Option<Entity<Project>>,
 1287        window: &mut Window,
 1288        cx: &mut Context<Self>,
 1289    ) -> Self {
 1290        Self::new(EditorMode::full(), buffer, project, window, cx)
 1291    }
 1292
 1293    pub fn clone(&self, window: &mut Window, cx: &mut Context<Self>) -> Self {
 1294        let mut clone = Self::new(
 1295            self.mode,
 1296            self.buffer.clone(),
 1297            self.project.clone(),
 1298            window,
 1299            cx,
 1300        );
 1301        self.display_map.update(cx, |display_map, cx| {
 1302            let snapshot = display_map.snapshot(cx);
 1303            clone.display_map.update(cx, |display_map, cx| {
 1304                display_map.set_state(&snapshot, cx);
 1305            });
 1306        });
 1307        clone.folds_did_change(cx);
 1308        clone.selections.clone_state(&self.selections);
 1309        clone.scroll_manager.clone_state(&self.scroll_manager);
 1310        clone.searchable = self.searchable;
 1311        clone.read_only = self.read_only;
 1312        clone
 1313    }
 1314
 1315    pub fn new(
 1316        mode: EditorMode,
 1317        buffer: Entity<MultiBuffer>,
 1318        project: Option<Entity<Project>>,
 1319        window: &mut Window,
 1320        cx: &mut Context<Self>,
 1321    ) -> Self {
 1322        let style = window.text_style();
 1323        let font_size = style.font_size.to_pixels(window.rem_size());
 1324        let editor = cx.entity().downgrade();
 1325        let fold_placeholder = FoldPlaceholder {
 1326            constrain_width: true,
 1327            render: Arc::new(move |fold_id, fold_range, cx| {
 1328                let editor = editor.clone();
 1329                div()
 1330                    .id(fold_id)
 1331                    .bg(cx.theme().colors().ghost_element_background)
 1332                    .hover(|style| style.bg(cx.theme().colors().ghost_element_hover))
 1333                    .active(|style| style.bg(cx.theme().colors().ghost_element_active))
 1334                    .rounded_xs()
 1335                    .size_full()
 1336                    .cursor_pointer()
 1337                    .child("")
 1338                    .on_mouse_down(MouseButton::Left, |_, _, cx| cx.stop_propagation())
 1339                    .on_click(move |_, _window, cx| {
 1340                        editor
 1341                            .update(cx, |editor, cx| {
 1342                                editor.unfold_ranges(
 1343                                    &[fold_range.start..fold_range.end],
 1344                                    true,
 1345                                    false,
 1346                                    cx,
 1347                                );
 1348                                cx.stop_propagation();
 1349                            })
 1350                            .ok();
 1351                    })
 1352                    .into_any()
 1353            }),
 1354            merge_adjacent: true,
 1355            ..Default::default()
 1356        };
 1357        let display_map = cx.new(|cx| {
 1358            DisplayMap::new(
 1359                buffer.clone(),
 1360                style.font(),
 1361                font_size,
 1362                None,
 1363                FILE_HEADER_HEIGHT,
 1364                MULTI_BUFFER_EXCERPT_HEADER_HEIGHT,
 1365                fold_placeholder,
 1366                cx,
 1367            )
 1368        });
 1369
 1370        let selections = SelectionsCollection::new(display_map.clone(), buffer.clone());
 1371
 1372        let blink_manager = cx.new(|cx| BlinkManager::new(CURSOR_BLINK_INTERVAL, cx));
 1373
 1374        let soft_wrap_mode_override = matches!(mode, EditorMode::SingleLine { .. })
 1375            .then(|| language_settings::SoftWrap::None);
 1376
 1377        let mut project_subscriptions = Vec::new();
 1378        if mode.is_full() {
 1379            if let Some(project) = project.as_ref() {
 1380                project_subscriptions.push(cx.subscribe_in(
 1381                    project,
 1382                    window,
 1383                    |editor, _, event, window, cx| match event {
 1384                        project::Event::RefreshCodeLens => {
 1385                            // we always query lens with actions, without storing them, always refreshing them
 1386                        }
 1387                        project::Event::RefreshInlayHints => {
 1388                            editor
 1389                                .refresh_inlay_hints(InlayHintRefreshReason::RefreshRequested, cx);
 1390                        }
 1391                        project::Event::SnippetEdit(id, snippet_edits) => {
 1392                            if let Some(buffer) = editor.buffer.read(cx).buffer(*id) {
 1393                                let focus_handle = editor.focus_handle(cx);
 1394                                if focus_handle.is_focused(window) {
 1395                                    let snapshot = buffer.read(cx).snapshot();
 1396                                    for (range, snippet) in snippet_edits {
 1397                                        let editor_range =
 1398                                            language::range_from_lsp(*range).to_offset(&snapshot);
 1399                                        editor
 1400                                            .insert_snippet(
 1401                                                &[editor_range],
 1402                                                snippet.clone(),
 1403                                                window,
 1404                                                cx,
 1405                                            )
 1406                                            .ok();
 1407                                    }
 1408                                }
 1409                            }
 1410                        }
 1411                        _ => {}
 1412                    },
 1413                ));
 1414                if let Some(task_inventory) = project
 1415                    .read(cx)
 1416                    .task_store()
 1417                    .read(cx)
 1418                    .task_inventory()
 1419                    .cloned()
 1420                {
 1421                    project_subscriptions.push(cx.observe_in(
 1422                        &task_inventory,
 1423                        window,
 1424                        |editor, _, window, cx| {
 1425                            editor.tasks_update_task = Some(editor.refresh_runnables(window, cx));
 1426                        },
 1427                    ));
 1428                };
 1429
 1430                project_subscriptions.push(cx.subscribe_in(
 1431                    &project.read(cx).breakpoint_store(),
 1432                    window,
 1433                    |editor, _, event, window, cx| match event {
 1434                        BreakpointStoreEvent::ActiveDebugLineChanged => {
 1435                            if editor.go_to_active_debug_line(window, cx) {
 1436                                cx.stop_propagation();
 1437                            }
 1438                        }
 1439                        _ => {}
 1440                    },
 1441                ));
 1442            }
 1443        }
 1444
 1445        let buffer_snapshot = buffer.read(cx).snapshot(cx);
 1446
 1447        let inlay_hint_settings =
 1448            inlay_hint_settings(selections.newest_anchor().head(), &buffer_snapshot, cx);
 1449        let focus_handle = cx.focus_handle();
 1450        cx.on_focus(&focus_handle, window, Self::handle_focus)
 1451            .detach();
 1452        cx.on_focus_in(&focus_handle, window, Self::handle_focus_in)
 1453            .detach();
 1454        cx.on_focus_out(&focus_handle, window, Self::handle_focus_out)
 1455            .detach();
 1456        cx.on_blur(&focus_handle, window, Self::handle_blur)
 1457            .detach();
 1458
 1459        let show_indent_guides = if matches!(mode, EditorMode::SingleLine { .. }) {
 1460            Some(false)
 1461        } else {
 1462            None
 1463        };
 1464
 1465        let breakpoint_store = match (mode, project.as_ref()) {
 1466            (EditorMode::Full { .. }, Some(project)) => Some(project.read(cx).breakpoint_store()),
 1467            _ => None,
 1468        };
 1469
 1470        let mut code_action_providers = Vec::new();
 1471        let mut load_uncommitted_diff = None;
 1472        if let Some(project) = project.clone() {
 1473            load_uncommitted_diff = Some(
 1474                get_uncommitted_diff_for_buffer(
 1475                    &project,
 1476                    buffer.read(cx).all_buffers(),
 1477                    buffer.clone(),
 1478                    cx,
 1479                )
 1480                .shared(),
 1481            );
 1482            code_action_providers.push(Rc::new(project) as Rc<_>);
 1483        }
 1484
 1485        let mut this = Self {
 1486            focus_handle,
 1487            show_cursor_when_unfocused: false,
 1488            last_focused_descendant: None,
 1489            buffer: buffer.clone(),
 1490            display_map: display_map.clone(),
 1491            selections,
 1492            scroll_manager: ScrollManager::new(cx),
 1493            columnar_selection_tail: None,
 1494            add_selections_state: None,
 1495            select_next_state: None,
 1496            select_prev_state: None,
 1497            selection_history: Default::default(),
 1498            autoclose_regions: Default::default(),
 1499            snippet_stack: Default::default(),
 1500            select_syntax_node_history: SelectSyntaxNodeHistory::default(),
 1501            ime_transaction: Default::default(),
 1502            active_diagnostics: ActiveDiagnostic::None,
 1503            show_inline_diagnostics: ProjectSettings::get_global(cx).diagnostics.inline.enabled,
 1504            inline_diagnostics_update: Task::ready(()),
 1505            inline_diagnostics: Vec::new(),
 1506            soft_wrap_mode_override,
 1507            hard_wrap: None,
 1508            completion_provider: project.clone().map(|project| Box::new(project) as _),
 1509            semantics_provider: project.clone().map(|project| Rc::new(project) as _),
 1510            collaboration_hub: project.clone().map(|project| Box::new(project) as _),
 1511            project,
 1512            blink_manager: blink_manager.clone(),
 1513            show_local_selections: true,
 1514            show_scrollbars: true,
 1515            mode,
 1516            show_breadcrumbs: EditorSettings::get_global(cx).toolbar.breadcrumbs,
 1517            show_gutter: mode.is_full(),
 1518            show_line_numbers: None,
 1519            use_relative_line_numbers: None,
 1520            show_git_diff_gutter: None,
 1521            show_code_actions: None,
 1522            show_runnables: None,
 1523            show_breakpoints: None,
 1524            show_wrap_guides: None,
 1525            show_indent_guides,
 1526            placeholder_text: None,
 1527            highlight_order: 0,
 1528            highlighted_rows: HashMap::default(),
 1529            background_highlights: Default::default(),
 1530            gutter_highlights: TreeMap::default(),
 1531            scrollbar_marker_state: ScrollbarMarkerState::default(),
 1532            active_indent_guides_state: ActiveIndentGuidesState::default(),
 1533            nav_history: None,
 1534            context_menu: RefCell::new(None),
 1535            context_menu_options: None,
 1536            mouse_context_menu: None,
 1537            completion_tasks: Default::default(),
 1538            signature_help_state: SignatureHelpState::default(),
 1539            auto_signature_help: None,
 1540            find_all_references_task_sources: Vec::new(),
 1541            next_completion_id: 0,
 1542            next_inlay_id: 0,
 1543            code_action_providers,
 1544            available_code_actions: Default::default(),
 1545            code_actions_task: Default::default(),
 1546            selection_highlight_task: Default::default(),
 1547            document_highlights_task: Default::default(),
 1548            linked_editing_range_task: Default::default(),
 1549            pending_rename: Default::default(),
 1550            searchable: true,
 1551            cursor_shape: EditorSettings::get_global(cx)
 1552                .cursor_shape
 1553                .unwrap_or_default(),
 1554            current_line_highlight: None,
 1555            autoindent_mode: Some(AutoindentMode::EachLine),
 1556            collapse_matches: false,
 1557            workspace: None,
 1558            input_enabled: true,
 1559            use_modal_editing: mode.is_full(),
 1560            read_only: false,
 1561            use_autoclose: true,
 1562            use_auto_surround: true,
 1563            auto_replace_emoji_shortcode: false,
 1564            jsx_tag_auto_close_enabled_in_any_buffer: false,
 1565            leader_peer_id: None,
 1566            remote_id: None,
 1567            hover_state: Default::default(),
 1568            pending_mouse_down: None,
 1569            hovered_link_state: Default::default(),
 1570            edit_prediction_provider: None,
 1571            active_inline_completion: None,
 1572            stale_inline_completion_in_menu: None,
 1573            edit_prediction_preview: EditPredictionPreview::Inactive {
 1574                released_too_fast: false,
 1575            },
 1576            inline_diagnostics_enabled: mode.is_full(),
 1577            inlay_hint_cache: InlayHintCache::new(inlay_hint_settings),
 1578
 1579            gutter_hovered: false,
 1580            pixel_position_of_newest_cursor: None,
 1581            last_bounds: None,
 1582            last_position_map: None,
 1583            expect_bounds_change: None,
 1584            gutter_dimensions: GutterDimensions::default(),
 1585            style: None,
 1586            show_cursor_names: false,
 1587            hovered_cursors: Default::default(),
 1588            next_editor_action_id: EditorActionId::default(),
 1589            editor_actions: Rc::default(),
 1590            inline_completions_hidden_for_vim_mode: false,
 1591            show_inline_completions_override: None,
 1592            menu_inline_completions_policy: MenuInlineCompletionsPolicy::ByProvider,
 1593            edit_prediction_settings: EditPredictionSettings::Disabled,
 1594            edit_prediction_indent_conflict: false,
 1595            edit_prediction_requires_modifier_in_indent_conflict: true,
 1596            custom_context_menu: None,
 1597            show_git_blame_gutter: false,
 1598            show_git_blame_inline: false,
 1599            show_selection_menu: None,
 1600            show_git_blame_inline_delay_task: None,
 1601            git_blame_inline_tooltip: None,
 1602            git_blame_inline_enabled: ProjectSettings::get_global(cx).git.inline_blame_enabled(),
 1603            render_diff_hunk_controls: Arc::new(render_diff_hunk_controls),
 1604            serialize_dirty_buffers: ProjectSettings::get_global(cx)
 1605                .session
 1606                .restore_unsaved_buffers,
 1607            blame: None,
 1608            blame_subscription: None,
 1609            tasks: Default::default(),
 1610
 1611            breakpoint_store,
 1612            gutter_breakpoint_indicator: (None, None),
 1613            _subscriptions: vec![
 1614                cx.observe(&buffer, Self::on_buffer_changed),
 1615                cx.subscribe_in(&buffer, window, Self::on_buffer_event),
 1616                cx.observe_in(&display_map, window, Self::on_display_map_changed),
 1617                cx.observe(&blink_manager, |_, _, cx| cx.notify()),
 1618                cx.observe_global_in::<SettingsStore>(window, Self::settings_changed),
 1619                observe_buffer_font_size_adjustment(cx, |_, cx| cx.notify()),
 1620                cx.observe_window_activation(window, |editor, window, cx| {
 1621                    let active = window.is_window_active();
 1622                    editor.blink_manager.update(cx, |blink_manager, cx| {
 1623                        if active {
 1624                            blink_manager.enable(cx);
 1625                        } else {
 1626                            blink_manager.disable(cx);
 1627                        }
 1628                    });
 1629                }),
 1630            ],
 1631            tasks_update_task: None,
 1632            linked_edit_ranges: Default::default(),
 1633            in_project_search: false,
 1634            previous_search_ranges: None,
 1635            breadcrumb_header: None,
 1636            focused_block: None,
 1637            next_scroll_position: NextScrollCursorCenterTopBottom::default(),
 1638            addons: HashMap::default(),
 1639            registered_buffers: HashMap::default(),
 1640            _scroll_cursor_center_top_bottom_task: Task::ready(()),
 1641            selection_mark_mode: false,
 1642            toggle_fold_multiple_buffers: Task::ready(()),
 1643            serialize_selections: Task::ready(()),
 1644            serialize_folds: Task::ready(()),
 1645            text_style_refinement: None,
 1646            load_diff_task: load_uncommitted_diff,
 1647            mouse_cursor_hidden: false,
 1648            hide_mouse_mode: EditorSettings::get_global(cx)
 1649                .hide_mouse
 1650                .unwrap_or_default(),
 1651        };
 1652        if let Some(breakpoints) = this.breakpoint_store.as_ref() {
 1653            this._subscriptions
 1654                .push(cx.observe(breakpoints, |_, _, cx| {
 1655                    cx.notify();
 1656                }));
 1657        }
 1658        this.tasks_update_task = Some(this.refresh_runnables(window, cx));
 1659        this._subscriptions.extend(project_subscriptions);
 1660
 1661        this._subscriptions.push(cx.subscribe_in(
 1662            &cx.entity(),
 1663            window,
 1664            |editor, _, e: &EditorEvent, window, cx| {
 1665                if let EditorEvent::SelectionsChanged { local } = e {
 1666                    if *local {
 1667                        let new_anchor = editor.scroll_manager.anchor();
 1668                        let snapshot = editor.snapshot(window, cx);
 1669                        editor.update_restoration_data(cx, move |data| {
 1670                            data.scroll_position = (
 1671                                new_anchor.top_row(&snapshot.buffer_snapshot),
 1672                                new_anchor.offset,
 1673                            );
 1674                        });
 1675                    }
 1676                }
 1677            },
 1678        ));
 1679
 1680        this.end_selection(window, cx);
 1681        this.scroll_manager.show_scrollbars(window, cx);
 1682        jsx_tag_auto_close::refresh_enabled_in_any_buffer(&mut this, &buffer, cx);
 1683
 1684        if mode.is_full() {
 1685            let should_auto_hide_scrollbars = cx.should_auto_hide_scrollbars();
 1686            cx.set_global(ScrollbarAutoHide(should_auto_hide_scrollbars));
 1687
 1688            if this.git_blame_inline_enabled {
 1689                this.git_blame_inline_enabled = true;
 1690                this.start_git_blame_inline(false, window, cx);
 1691            }
 1692
 1693            this.go_to_active_debug_line(window, cx);
 1694
 1695            if let Some(buffer) = buffer.read(cx).as_singleton() {
 1696                if let Some(project) = this.project.as_ref() {
 1697                    let handle = project.update(cx, |project, cx| {
 1698                        project.register_buffer_with_language_servers(&buffer, cx)
 1699                    });
 1700                    this.registered_buffers
 1701                        .insert(buffer.read(cx).remote_id(), handle);
 1702                }
 1703            }
 1704        }
 1705
 1706        this.report_editor_event("Editor Opened", None, cx);
 1707        this
 1708    }
 1709
 1710    pub fn deploy_mouse_context_menu(
 1711        &mut self,
 1712        position: gpui::Point<Pixels>,
 1713        context_menu: Entity<ContextMenu>,
 1714        window: &mut Window,
 1715        cx: &mut Context<Self>,
 1716    ) {
 1717        self.mouse_context_menu = Some(MouseContextMenu::new(
 1718            crate::mouse_context_menu::MenuPosition::PinnedToScreen(position),
 1719            context_menu,
 1720            None,
 1721            window,
 1722            cx,
 1723        ));
 1724    }
 1725
 1726    pub fn mouse_menu_is_focused(&self, window: &Window, cx: &App) -> bool {
 1727        self.mouse_context_menu
 1728            .as_ref()
 1729            .is_some_and(|menu| menu.context_menu.focus_handle(cx).is_focused(window))
 1730    }
 1731
 1732    fn key_context(&self, window: &Window, cx: &App) -> KeyContext {
 1733        self.key_context_internal(self.has_active_inline_completion(), window, cx)
 1734    }
 1735
 1736    fn key_context_internal(
 1737        &self,
 1738        has_active_edit_prediction: bool,
 1739        window: &Window,
 1740        cx: &App,
 1741    ) -> KeyContext {
 1742        let mut key_context = KeyContext::new_with_defaults();
 1743        key_context.add("Editor");
 1744        let mode = match self.mode {
 1745            EditorMode::SingleLine { .. } => "single_line",
 1746            EditorMode::AutoHeight { .. } => "auto_height",
 1747            EditorMode::Full { .. } => "full",
 1748        };
 1749
 1750        if EditorSettings::jupyter_enabled(cx) {
 1751            key_context.add("jupyter");
 1752        }
 1753
 1754        key_context.set("mode", mode);
 1755        if self.pending_rename.is_some() {
 1756            key_context.add("renaming");
 1757        }
 1758
 1759        match self.context_menu.borrow().as_ref() {
 1760            Some(CodeContextMenu::Completions(_)) => {
 1761                key_context.add("menu");
 1762                key_context.add("showing_completions");
 1763            }
 1764            Some(CodeContextMenu::CodeActions(_)) => {
 1765                key_context.add("menu");
 1766                key_context.add("showing_code_actions")
 1767            }
 1768            None => {}
 1769        }
 1770
 1771        // Disable vim contexts when a sub-editor (e.g. rename/inline assistant) is focused.
 1772        if !self.focus_handle(cx).contains_focused(window, cx)
 1773            || (self.is_focused(window) || self.mouse_menu_is_focused(window, cx))
 1774        {
 1775            for addon in self.addons.values() {
 1776                addon.extend_key_context(&mut key_context, cx)
 1777            }
 1778        }
 1779
 1780        if let Some(singleton_buffer) = self.buffer.read(cx).as_singleton() {
 1781            if let Some(extension) = singleton_buffer
 1782                .read(cx)
 1783                .file()
 1784                .and_then(|file| file.path().extension()?.to_str())
 1785            {
 1786                key_context.set("extension", extension.to_string());
 1787            }
 1788        } else {
 1789            key_context.add("multibuffer");
 1790        }
 1791
 1792        if has_active_edit_prediction {
 1793            if self.edit_prediction_in_conflict() {
 1794                key_context.add(EDIT_PREDICTION_CONFLICT_KEY_CONTEXT);
 1795            } else {
 1796                key_context.add(EDIT_PREDICTION_KEY_CONTEXT);
 1797                key_context.add("copilot_suggestion");
 1798            }
 1799        }
 1800
 1801        if self.selection_mark_mode {
 1802            key_context.add("selection_mode");
 1803        }
 1804
 1805        key_context
 1806    }
 1807
 1808    pub fn hide_mouse_cursor(&mut self, origin: &HideMouseCursorOrigin) {
 1809        self.mouse_cursor_hidden = match origin {
 1810            HideMouseCursorOrigin::TypingAction => {
 1811                matches!(
 1812                    self.hide_mouse_mode,
 1813                    HideMouseMode::OnTyping | HideMouseMode::OnTypingAndMovement
 1814                )
 1815            }
 1816            HideMouseCursorOrigin::MovementAction => {
 1817                matches!(self.hide_mouse_mode, HideMouseMode::OnTypingAndMovement)
 1818            }
 1819        };
 1820    }
 1821
 1822    pub fn edit_prediction_in_conflict(&self) -> bool {
 1823        if !self.show_edit_predictions_in_menu() {
 1824            return false;
 1825        }
 1826
 1827        let showing_completions = self
 1828            .context_menu
 1829            .borrow()
 1830            .as_ref()
 1831            .map_or(false, |context| {
 1832                matches!(context, CodeContextMenu::Completions(_))
 1833            });
 1834
 1835        showing_completions
 1836            || self.edit_prediction_requires_modifier()
 1837            // Require modifier key when the cursor is on leading whitespace, to allow `tab`
 1838            // bindings to insert tab characters.
 1839            || (self.edit_prediction_requires_modifier_in_indent_conflict && self.edit_prediction_indent_conflict)
 1840    }
 1841
 1842    pub fn accept_edit_prediction_keybind(
 1843        &self,
 1844        window: &Window,
 1845        cx: &App,
 1846    ) -> AcceptEditPredictionBinding {
 1847        let key_context = self.key_context_internal(true, window, cx);
 1848        let in_conflict = self.edit_prediction_in_conflict();
 1849
 1850        AcceptEditPredictionBinding(
 1851            window
 1852                .bindings_for_action_in_context(&AcceptEditPrediction, key_context)
 1853                .into_iter()
 1854                .filter(|binding| {
 1855                    !in_conflict
 1856                        || binding
 1857                            .keystrokes()
 1858                            .first()
 1859                            .map_or(false, |keystroke| keystroke.modifiers.modified())
 1860                })
 1861                .rev()
 1862                .min_by_key(|binding| {
 1863                    binding
 1864                        .keystrokes()
 1865                        .first()
 1866                        .map_or(u8::MAX, |k| k.modifiers.number_of_modifiers())
 1867                }),
 1868        )
 1869    }
 1870
 1871    pub fn new_file(
 1872        workspace: &mut Workspace,
 1873        _: &workspace::NewFile,
 1874        window: &mut Window,
 1875        cx: &mut Context<Workspace>,
 1876    ) {
 1877        Self::new_in_workspace(workspace, window, cx).detach_and_prompt_err(
 1878            "Failed to create buffer",
 1879            window,
 1880            cx,
 1881            |e, _, _| match e.error_code() {
 1882                ErrorCode::RemoteUpgradeRequired => Some(format!(
 1883                "The remote instance of Zed does not support this yet. It must be upgraded to {}",
 1884                e.error_tag("required").unwrap_or("the latest version")
 1885            )),
 1886                _ => None,
 1887            },
 1888        );
 1889    }
 1890
 1891    pub fn new_in_workspace(
 1892        workspace: &mut Workspace,
 1893        window: &mut Window,
 1894        cx: &mut Context<Workspace>,
 1895    ) -> Task<Result<Entity<Editor>>> {
 1896        let project = workspace.project().clone();
 1897        let create = project.update(cx, |project, cx| project.create_buffer(cx));
 1898
 1899        cx.spawn_in(window, async move |workspace, cx| {
 1900            let buffer = create.await?;
 1901            workspace.update_in(cx, |workspace, window, cx| {
 1902                let editor =
 1903                    cx.new(|cx| Editor::for_buffer(buffer, Some(project.clone()), window, cx));
 1904                workspace.add_item_to_active_pane(Box::new(editor.clone()), None, true, window, cx);
 1905                editor
 1906            })
 1907        })
 1908    }
 1909
 1910    fn new_file_vertical(
 1911        workspace: &mut Workspace,
 1912        _: &workspace::NewFileSplitVertical,
 1913        window: &mut Window,
 1914        cx: &mut Context<Workspace>,
 1915    ) {
 1916        Self::new_file_in_direction(workspace, SplitDirection::vertical(cx), window, cx)
 1917    }
 1918
 1919    fn new_file_horizontal(
 1920        workspace: &mut Workspace,
 1921        _: &workspace::NewFileSplitHorizontal,
 1922        window: &mut Window,
 1923        cx: &mut Context<Workspace>,
 1924    ) {
 1925        Self::new_file_in_direction(workspace, SplitDirection::horizontal(cx), window, cx)
 1926    }
 1927
 1928    fn new_file_in_direction(
 1929        workspace: &mut Workspace,
 1930        direction: SplitDirection,
 1931        window: &mut Window,
 1932        cx: &mut Context<Workspace>,
 1933    ) {
 1934        let project = workspace.project().clone();
 1935        let create = project.update(cx, |project, cx| project.create_buffer(cx));
 1936
 1937        cx.spawn_in(window, async move |workspace, cx| {
 1938            let buffer = create.await?;
 1939            workspace.update_in(cx, move |workspace, window, cx| {
 1940                workspace.split_item(
 1941                    direction,
 1942                    Box::new(
 1943                        cx.new(|cx| Editor::for_buffer(buffer, Some(project.clone()), window, cx)),
 1944                    ),
 1945                    window,
 1946                    cx,
 1947                )
 1948            })?;
 1949            anyhow::Ok(())
 1950        })
 1951        .detach_and_prompt_err("Failed to create buffer", window, cx, |e, _, _| {
 1952            match e.error_code() {
 1953                ErrorCode::RemoteUpgradeRequired => Some(format!(
 1954                "The remote instance of Zed does not support this yet. It must be upgraded to {}",
 1955                e.error_tag("required").unwrap_or("the latest version")
 1956            )),
 1957                _ => None,
 1958            }
 1959        });
 1960    }
 1961
 1962    pub fn leader_peer_id(&self) -> Option<PeerId> {
 1963        self.leader_peer_id
 1964    }
 1965
 1966    pub fn buffer(&self) -> &Entity<MultiBuffer> {
 1967        &self.buffer
 1968    }
 1969
 1970    pub fn workspace(&self) -> Option<Entity<Workspace>> {
 1971        self.workspace.as_ref()?.0.upgrade()
 1972    }
 1973
 1974    pub fn title<'a>(&self, cx: &'a App) -> Cow<'a, str> {
 1975        self.buffer().read(cx).title(cx)
 1976    }
 1977
 1978    pub fn snapshot(&self, window: &mut Window, cx: &mut App) -> EditorSnapshot {
 1979        let git_blame_gutter_max_author_length = self
 1980            .render_git_blame_gutter(cx)
 1981            .then(|| {
 1982                if let Some(blame) = self.blame.as_ref() {
 1983                    let max_author_length =
 1984                        blame.update(cx, |blame, cx| blame.max_author_length(cx));
 1985                    Some(max_author_length)
 1986                } else {
 1987                    None
 1988                }
 1989            })
 1990            .flatten();
 1991
 1992        EditorSnapshot {
 1993            mode: self.mode,
 1994            show_gutter: self.show_gutter,
 1995            show_line_numbers: self.show_line_numbers,
 1996            show_git_diff_gutter: self.show_git_diff_gutter,
 1997            show_code_actions: self.show_code_actions,
 1998            show_runnables: self.show_runnables,
 1999            show_breakpoints: self.show_breakpoints,
 2000            git_blame_gutter_max_author_length,
 2001            display_snapshot: self.display_map.update(cx, |map, cx| map.snapshot(cx)),
 2002            scroll_anchor: self.scroll_manager.anchor(),
 2003            ongoing_scroll: self.scroll_manager.ongoing_scroll(),
 2004            placeholder_text: self.placeholder_text.clone(),
 2005            is_focused: self.focus_handle.is_focused(window),
 2006            current_line_highlight: self
 2007                .current_line_highlight
 2008                .unwrap_or_else(|| EditorSettings::get_global(cx).current_line_highlight),
 2009            gutter_hovered: self.gutter_hovered,
 2010        }
 2011    }
 2012
 2013    pub fn language_at<T: ToOffset>(&self, point: T, cx: &App) -> Option<Arc<Language>> {
 2014        self.buffer.read(cx).language_at(point, cx)
 2015    }
 2016
 2017    pub fn file_at<T: ToOffset>(&self, point: T, cx: &App) -> Option<Arc<dyn language::File>> {
 2018        self.buffer.read(cx).read(cx).file_at(point).cloned()
 2019    }
 2020
 2021    pub fn active_excerpt(
 2022        &self,
 2023        cx: &App,
 2024    ) -> Option<(ExcerptId, Entity<Buffer>, Range<text::Anchor>)> {
 2025        self.buffer
 2026            .read(cx)
 2027            .excerpt_containing(self.selections.newest_anchor().head(), cx)
 2028    }
 2029
 2030    pub fn mode(&self) -> EditorMode {
 2031        self.mode
 2032    }
 2033
 2034    pub fn set_mode(&mut self, mode: EditorMode) {
 2035        self.mode = mode;
 2036    }
 2037
 2038    pub fn collaboration_hub(&self) -> Option<&dyn CollaborationHub> {
 2039        self.collaboration_hub.as_deref()
 2040    }
 2041
 2042    pub fn set_collaboration_hub(&mut self, hub: Box<dyn CollaborationHub>) {
 2043        self.collaboration_hub = Some(hub);
 2044    }
 2045
 2046    pub fn set_in_project_search(&mut self, in_project_search: bool) {
 2047        self.in_project_search = in_project_search;
 2048    }
 2049
 2050    pub fn set_custom_context_menu(
 2051        &mut self,
 2052        f: impl 'static
 2053        + Fn(
 2054            &mut Self,
 2055            DisplayPoint,
 2056            &mut Window,
 2057            &mut Context<Self>,
 2058        ) -> Option<Entity<ui::ContextMenu>>,
 2059    ) {
 2060        self.custom_context_menu = Some(Box::new(f))
 2061    }
 2062
 2063    pub fn set_completion_provider(&mut self, provider: Option<Box<dyn CompletionProvider>>) {
 2064        self.completion_provider = provider;
 2065    }
 2066
 2067    pub fn semantics_provider(&self) -> Option<Rc<dyn SemanticsProvider>> {
 2068        self.semantics_provider.clone()
 2069    }
 2070
 2071    pub fn set_semantics_provider(&mut self, provider: Option<Rc<dyn SemanticsProvider>>) {
 2072        self.semantics_provider = provider;
 2073    }
 2074
 2075    pub fn set_edit_prediction_provider<T>(
 2076        &mut self,
 2077        provider: Option<Entity<T>>,
 2078        window: &mut Window,
 2079        cx: &mut Context<Self>,
 2080    ) where
 2081        T: EditPredictionProvider,
 2082    {
 2083        self.edit_prediction_provider =
 2084            provider.map(|provider| RegisteredInlineCompletionProvider {
 2085                _subscription: cx.observe_in(&provider, window, |this, _, window, cx| {
 2086                    if this.focus_handle.is_focused(window) {
 2087                        this.update_visible_inline_completion(window, cx);
 2088                    }
 2089                }),
 2090                provider: Arc::new(provider),
 2091            });
 2092        self.update_edit_prediction_settings(cx);
 2093        self.refresh_inline_completion(false, false, window, cx);
 2094    }
 2095
 2096    pub fn placeholder_text(&self) -> Option<&str> {
 2097        self.placeholder_text.as_deref()
 2098    }
 2099
 2100    pub fn set_placeholder_text(
 2101        &mut self,
 2102        placeholder_text: impl Into<Arc<str>>,
 2103        cx: &mut Context<Self>,
 2104    ) {
 2105        let placeholder_text = Some(placeholder_text.into());
 2106        if self.placeholder_text != placeholder_text {
 2107            self.placeholder_text = placeholder_text;
 2108            cx.notify();
 2109        }
 2110    }
 2111
 2112    pub fn set_cursor_shape(&mut self, cursor_shape: CursorShape, cx: &mut Context<Self>) {
 2113        self.cursor_shape = cursor_shape;
 2114
 2115        // Disrupt blink for immediate user feedback that the cursor shape has changed
 2116        self.blink_manager.update(cx, BlinkManager::show_cursor);
 2117
 2118        cx.notify();
 2119    }
 2120
 2121    pub fn set_current_line_highlight(
 2122        &mut self,
 2123        current_line_highlight: Option<CurrentLineHighlight>,
 2124    ) {
 2125        self.current_line_highlight = current_line_highlight;
 2126    }
 2127
 2128    pub fn set_collapse_matches(&mut self, collapse_matches: bool) {
 2129        self.collapse_matches = collapse_matches;
 2130    }
 2131
 2132    fn register_buffers_with_language_servers(&mut self, cx: &mut Context<Self>) {
 2133        let buffers = self.buffer.read(cx).all_buffers();
 2134        let Some(project) = self.project.as_ref() else {
 2135            return;
 2136        };
 2137        project.update(cx, |project, cx| {
 2138            for buffer in buffers {
 2139                self.registered_buffers
 2140                    .entry(buffer.read(cx).remote_id())
 2141                    .or_insert_with(|| project.register_buffer_with_language_servers(&buffer, cx));
 2142            }
 2143        })
 2144    }
 2145
 2146    pub fn range_for_match<T: std::marker::Copy>(&self, range: &Range<T>) -> Range<T> {
 2147        if self.collapse_matches {
 2148            return range.start..range.start;
 2149        }
 2150        range.clone()
 2151    }
 2152
 2153    pub fn set_clip_at_line_ends(&mut self, clip: bool, cx: &mut Context<Self>) {
 2154        if self.display_map.read(cx).clip_at_line_ends != clip {
 2155            self.display_map
 2156                .update(cx, |map, _| map.clip_at_line_ends = clip);
 2157        }
 2158    }
 2159
 2160    pub fn set_input_enabled(&mut self, input_enabled: bool) {
 2161        self.input_enabled = input_enabled;
 2162    }
 2163
 2164    pub fn set_inline_completions_hidden_for_vim_mode(
 2165        &mut self,
 2166        hidden: bool,
 2167        window: &mut Window,
 2168        cx: &mut Context<Self>,
 2169    ) {
 2170        if hidden != self.inline_completions_hidden_for_vim_mode {
 2171            self.inline_completions_hidden_for_vim_mode = hidden;
 2172            if hidden {
 2173                self.update_visible_inline_completion(window, cx);
 2174            } else {
 2175                self.refresh_inline_completion(true, false, window, cx);
 2176            }
 2177        }
 2178    }
 2179
 2180    pub fn set_menu_inline_completions_policy(&mut self, value: MenuInlineCompletionsPolicy) {
 2181        self.menu_inline_completions_policy = value;
 2182    }
 2183
 2184    pub fn set_autoindent(&mut self, autoindent: bool) {
 2185        if autoindent {
 2186            self.autoindent_mode = Some(AutoindentMode::EachLine);
 2187        } else {
 2188            self.autoindent_mode = None;
 2189        }
 2190    }
 2191
 2192    pub fn read_only(&self, cx: &App) -> bool {
 2193        self.read_only || self.buffer.read(cx).read_only()
 2194    }
 2195
 2196    pub fn set_read_only(&mut self, read_only: bool) {
 2197        self.read_only = read_only;
 2198    }
 2199
 2200    pub fn set_use_autoclose(&mut self, autoclose: bool) {
 2201        self.use_autoclose = autoclose;
 2202    }
 2203
 2204    pub fn set_use_auto_surround(&mut self, auto_surround: bool) {
 2205        self.use_auto_surround = auto_surround;
 2206    }
 2207
 2208    pub fn set_auto_replace_emoji_shortcode(&mut self, auto_replace: bool) {
 2209        self.auto_replace_emoji_shortcode = auto_replace;
 2210    }
 2211
 2212    pub fn toggle_edit_predictions(
 2213        &mut self,
 2214        _: &ToggleEditPrediction,
 2215        window: &mut Window,
 2216        cx: &mut Context<Self>,
 2217    ) {
 2218        if self.show_inline_completions_override.is_some() {
 2219            self.set_show_edit_predictions(None, window, cx);
 2220        } else {
 2221            let show_edit_predictions = !self.edit_predictions_enabled();
 2222            self.set_show_edit_predictions(Some(show_edit_predictions), window, cx);
 2223        }
 2224    }
 2225
 2226    pub fn set_show_edit_predictions(
 2227        &mut self,
 2228        show_edit_predictions: Option<bool>,
 2229        window: &mut Window,
 2230        cx: &mut Context<Self>,
 2231    ) {
 2232        self.show_inline_completions_override = show_edit_predictions;
 2233        self.update_edit_prediction_settings(cx);
 2234
 2235        if let Some(false) = show_edit_predictions {
 2236            self.discard_inline_completion(false, cx);
 2237        } else {
 2238            self.refresh_inline_completion(false, true, window, cx);
 2239        }
 2240    }
 2241
 2242    fn inline_completions_disabled_in_scope(
 2243        &self,
 2244        buffer: &Entity<Buffer>,
 2245        buffer_position: language::Anchor,
 2246        cx: &App,
 2247    ) -> bool {
 2248        let snapshot = buffer.read(cx).snapshot();
 2249        let settings = snapshot.settings_at(buffer_position, cx);
 2250
 2251        let Some(scope) = snapshot.language_scope_at(buffer_position) else {
 2252            return false;
 2253        };
 2254
 2255        scope.override_name().map_or(false, |scope_name| {
 2256            settings
 2257                .edit_predictions_disabled_in
 2258                .iter()
 2259                .any(|s| s == scope_name)
 2260        })
 2261    }
 2262
 2263    pub fn set_use_modal_editing(&mut self, to: bool) {
 2264        self.use_modal_editing = to;
 2265    }
 2266
 2267    pub fn use_modal_editing(&self) -> bool {
 2268        self.use_modal_editing
 2269    }
 2270
 2271    fn selections_did_change(
 2272        &mut self,
 2273        local: bool,
 2274        old_cursor_position: &Anchor,
 2275        show_completions: bool,
 2276        window: &mut Window,
 2277        cx: &mut Context<Self>,
 2278    ) {
 2279        window.invalidate_character_coordinates();
 2280
 2281        // Copy selections to primary selection buffer
 2282        #[cfg(any(target_os = "linux", target_os = "freebsd"))]
 2283        if local {
 2284            let selections = self.selections.all::<usize>(cx);
 2285            let buffer_handle = self.buffer.read(cx).read(cx);
 2286
 2287            let mut text = String::new();
 2288            for (index, selection) in selections.iter().enumerate() {
 2289                let text_for_selection = buffer_handle
 2290                    .text_for_range(selection.start..selection.end)
 2291                    .collect::<String>();
 2292
 2293                text.push_str(&text_for_selection);
 2294                if index != selections.len() - 1 {
 2295                    text.push('\n');
 2296                }
 2297            }
 2298
 2299            if !text.is_empty() {
 2300                cx.write_to_primary(ClipboardItem::new_string(text));
 2301            }
 2302        }
 2303
 2304        if self.focus_handle.is_focused(window) && self.leader_peer_id.is_none() {
 2305            self.buffer.update(cx, |buffer, cx| {
 2306                buffer.set_active_selections(
 2307                    &self.selections.disjoint_anchors(),
 2308                    self.selections.line_mode,
 2309                    self.cursor_shape,
 2310                    cx,
 2311                )
 2312            });
 2313        }
 2314        let display_map = self
 2315            .display_map
 2316            .update(cx, |display_map, cx| display_map.snapshot(cx));
 2317        let buffer = &display_map.buffer_snapshot;
 2318        self.add_selections_state = None;
 2319        self.select_next_state = None;
 2320        self.select_prev_state = None;
 2321        self.select_syntax_node_history.try_clear();
 2322        self.invalidate_autoclose_regions(&self.selections.disjoint_anchors(), buffer);
 2323        self.snippet_stack
 2324            .invalidate(&self.selections.disjoint_anchors(), buffer);
 2325        self.take_rename(false, window, cx);
 2326
 2327        let new_cursor_position = self.selections.newest_anchor().head();
 2328
 2329        self.push_to_nav_history(
 2330            *old_cursor_position,
 2331            Some(new_cursor_position.to_point(buffer)),
 2332            false,
 2333            cx,
 2334        );
 2335
 2336        if local {
 2337            let new_cursor_position = self.selections.newest_anchor().head();
 2338            let mut context_menu = self.context_menu.borrow_mut();
 2339            let completion_menu = match context_menu.as_ref() {
 2340                Some(CodeContextMenu::Completions(menu)) => Some(menu),
 2341                _ => {
 2342                    *context_menu = None;
 2343                    None
 2344                }
 2345            };
 2346            if let Some(buffer_id) = new_cursor_position.buffer_id {
 2347                if !self.registered_buffers.contains_key(&buffer_id) {
 2348                    if let Some(project) = self.project.as_ref() {
 2349                        project.update(cx, |project, cx| {
 2350                            let Some(buffer) = self.buffer.read(cx).buffer(buffer_id) else {
 2351                                return;
 2352                            };
 2353                            self.registered_buffers.insert(
 2354                                buffer_id,
 2355                                project.register_buffer_with_language_servers(&buffer, cx),
 2356                            );
 2357                        })
 2358                    }
 2359                }
 2360            }
 2361
 2362            if let Some(completion_menu) = completion_menu {
 2363                let cursor_position = new_cursor_position.to_offset(buffer);
 2364                let (word_range, kind) =
 2365                    buffer.surrounding_word(completion_menu.initial_position, true);
 2366                if kind == Some(CharKind::Word)
 2367                    && word_range.to_inclusive().contains(&cursor_position)
 2368                {
 2369                    let mut completion_menu = completion_menu.clone();
 2370                    drop(context_menu);
 2371
 2372                    let query = Self::completion_query(buffer, cursor_position);
 2373                    cx.spawn(async move |this, cx| {
 2374                        completion_menu
 2375                            .filter(query.as_deref(), cx.background_executor().clone())
 2376                            .await;
 2377
 2378                        this.update(cx, |this, cx| {
 2379                            let mut context_menu = this.context_menu.borrow_mut();
 2380                            let Some(CodeContextMenu::Completions(menu)) = context_menu.as_ref()
 2381                            else {
 2382                                return;
 2383                            };
 2384
 2385                            if menu.id > completion_menu.id {
 2386                                return;
 2387                            }
 2388
 2389                            *context_menu = Some(CodeContextMenu::Completions(completion_menu));
 2390                            drop(context_menu);
 2391                            cx.notify();
 2392                        })
 2393                    })
 2394                    .detach();
 2395
 2396                    if show_completions {
 2397                        self.show_completions(&ShowCompletions { trigger: None }, window, cx);
 2398                    }
 2399                } else {
 2400                    drop(context_menu);
 2401                    self.hide_context_menu(window, cx);
 2402                }
 2403            } else {
 2404                drop(context_menu);
 2405            }
 2406
 2407            hide_hover(self, cx);
 2408
 2409            if old_cursor_position.to_display_point(&display_map).row()
 2410                != new_cursor_position.to_display_point(&display_map).row()
 2411            {
 2412                self.available_code_actions.take();
 2413            }
 2414            self.refresh_code_actions(window, cx);
 2415            self.refresh_document_highlights(cx);
 2416            self.refresh_selected_text_highlights(window, cx);
 2417            refresh_matching_bracket_highlights(self, window, cx);
 2418            self.update_visible_inline_completion(window, cx);
 2419            self.edit_prediction_requires_modifier_in_indent_conflict = true;
 2420            linked_editing_ranges::refresh_linked_ranges(self, window, cx);
 2421            if self.git_blame_inline_enabled {
 2422                self.start_inline_blame_timer(window, cx);
 2423            }
 2424        }
 2425
 2426        self.blink_manager.update(cx, BlinkManager::pause_blinking);
 2427        cx.emit(EditorEvent::SelectionsChanged { local });
 2428
 2429        let selections = &self.selections.disjoint;
 2430        if selections.len() == 1 {
 2431            cx.emit(SearchEvent::ActiveMatchChanged)
 2432        }
 2433        if local {
 2434            if let Some((_, _, buffer_snapshot)) = buffer.as_singleton() {
 2435                let inmemory_selections = selections
 2436                    .iter()
 2437                    .map(|s| {
 2438                        text::ToPoint::to_point(&s.range().start.text_anchor, buffer_snapshot)
 2439                            ..text::ToPoint::to_point(&s.range().end.text_anchor, buffer_snapshot)
 2440                    })
 2441                    .collect();
 2442                self.update_restoration_data(cx, |data| {
 2443                    data.selections = inmemory_selections;
 2444                });
 2445
 2446                if WorkspaceSettings::get(None, cx).restore_on_startup
 2447                    != RestoreOnStartupBehavior::None
 2448                {
 2449                    if let Some(workspace_id) =
 2450                        self.workspace.as_ref().and_then(|workspace| workspace.1)
 2451                    {
 2452                        let snapshot = self.buffer().read(cx).snapshot(cx);
 2453                        let selections = selections.clone();
 2454                        let background_executor = cx.background_executor().clone();
 2455                        let editor_id = cx.entity().entity_id().as_u64() as ItemId;
 2456                        self.serialize_selections = cx.background_spawn(async move {
 2457                    background_executor.timer(SERIALIZATION_THROTTLE_TIME).await;
 2458                    let db_selections = selections
 2459                        .iter()
 2460                        .map(|selection| {
 2461                            (
 2462                                selection.start.to_offset(&snapshot),
 2463                                selection.end.to_offset(&snapshot),
 2464                            )
 2465                        })
 2466                        .collect();
 2467
 2468                    DB.save_editor_selections(editor_id, workspace_id, db_selections)
 2469                        .await
 2470                        .with_context(|| format!("persisting editor selections for editor {editor_id}, workspace {workspace_id:?}"))
 2471                        .log_err();
 2472                });
 2473                    }
 2474                }
 2475            }
 2476        }
 2477
 2478        cx.notify();
 2479    }
 2480
 2481    fn folds_did_change(&mut self, cx: &mut Context<Self>) {
 2482        use text::ToOffset as _;
 2483        use text::ToPoint as _;
 2484
 2485        if WorkspaceSettings::get(None, cx).restore_on_startup == RestoreOnStartupBehavior::None {
 2486            return;
 2487        }
 2488
 2489        let Some(singleton) = self.buffer().read(cx).as_singleton() else {
 2490            return;
 2491        };
 2492
 2493        let snapshot = singleton.read(cx).snapshot();
 2494        let inmemory_folds = self.display_map.update(cx, |display_map, cx| {
 2495            let display_snapshot = display_map.snapshot(cx);
 2496
 2497            display_snapshot
 2498                .folds_in_range(0..display_snapshot.buffer_snapshot.len())
 2499                .map(|fold| {
 2500                    fold.range.start.text_anchor.to_point(&snapshot)
 2501                        ..fold.range.end.text_anchor.to_point(&snapshot)
 2502                })
 2503                .collect()
 2504        });
 2505        self.update_restoration_data(cx, |data| {
 2506            data.folds = inmemory_folds;
 2507        });
 2508
 2509        let Some(workspace_id) = self.workspace.as_ref().and_then(|workspace| workspace.1) else {
 2510            return;
 2511        };
 2512        let background_executor = cx.background_executor().clone();
 2513        let editor_id = cx.entity().entity_id().as_u64() as ItemId;
 2514        let db_folds = self.display_map.update(cx, |display_map, cx| {
 2515            display_map
 2516                .snapshot(cx)
 2517                .folds_in_range(0..snapshot.len())
 2518                .map(|fold| {
 2519                    (
 2520                        fold.range.start.text_anchor.to_offset(&snapshot),
 2521                        fold.range.end.text_anchor.to_offset(&snapshot),
 2522                    )
 2523                })
 2524                .collect()
 2525        });
 2526        self.serialize_folds = cx.background_spawn(async move {
 2527            background_executor.timer(SERIALIZATION_THROTTLE_TIME).await;
 2528            DB.save_editor_folds(editor_id, workspace_id, db_folds)
 2529                .await
 2530                .with_context(|| {
 2531                    format!(
 2532                        "persisting editor folds for editor {editor_id}, workspace {workspace_id:?}"
 2533                    )
 2534                })
 2535                .log_err();
 2536        });
 2537    }
 2538
 2539    pub fn sync_selections(
 2540        &mut self,
 2541        other: Entity<Editor>,
 2542        cx: &mut Context<Self>,
 2543    ) -> gpui::Subscription {
 2544        let other_selections = other.read(cx).selections.disjoint.to_vec();
 2545        self.selections.change_with(cx, |selections| {
 2546            selections.select_anchors(other_selections);
 2547        });
 2548
 2549        let other_subscription =
 2550            cx.subscribe(&other, |this, other, other_evt, cx| match other_evt {
 2551                EditorEvent::SelectionsChanged { local: true } => {
 2552                    let other_selections = other.read(cx).selections.disjoint.to_vec();
 2553                    if other_selections.is_empty() {
 2554                        return;
 2555                    }
 2556                    this.selections.change_with(cx, |selections| {
 2557                        selections.select_anchors(other_selections);
 2558                    });
 2559                }
 2560                _ => {}
 2561            });
 2562
 2563        let this_subscription =
 2564            cx.subscribe_self::<EditorEvent>(move |this, this_evt, cx| match this_evt {
 2565                EditorEvent::SelectionsChanged { local: true } => {
 2566                    let these_selections = this.selections.disjoint.to_vec();
 2567                    if these_selections.is_empty() {
 2568                        return;
 2569                    }
 2570                    other.update(cx, |other_editor, cx| {
 2571                        other_editor.selections.change_with(cx, |selections| {
 2572                            selections.select_anchors(these_selections);
 2573                        })
 2574                    });
 2575                }
 2576                _ => {}
 2577            });
 2578
 2579        Subscription::join(other_subscription, this_subscription)
 2580    }
 2581
 2582    pub fn change_selections<R>(
 2583        &mut self,
 2584        autoscroll: Option<Autoscroll>,
 2585        window: &mut Window,
 2586        cx: &mut Context<Self>,
 2587        change: impl FnOnce(&mut MutableSelectionsCollection<'_>) -> R,
 2588    ) -> R {
 2589        self.change_selections_inner(autoscroll, true, window, cx, change)
 2590    }
 2591
 2592    fn change_selections_inner<R>(
 2593        &mut self,
 2594        autoscroll: Option<Autoscroll>,
 2595        request_completions: bool,
 2596        window: &mut Window,
 2597        cx: &mut Context<Self>,
 2598        change: impl FnOnce(&mut MutableSelectionsCollection<'_>) -> R,
 2599    ) -> R {
 2600        let old_cursor_position = self.selections.newest_anchor().head();
 2601        self.push_to_selection_history();
 2602
 2603        let (changed, result) = self.selections.change_with(cx, change);
 2604
 2605        if changed {
 2606            if let Some(autoscroll) = autoscroll {
 2607                self.request_autoscroll(autoscroll, cx);
 2608            }
 2609            self.selections_did_change(true, &old_cursor_position, request_completions, window, cx);
 2610
 2611            if self.should_open_signature_help_automatically(
 2612                &old_cursor_position,
 2613                self.signature_help_state.backspace_pressed(),
 2614                cx,
 2615            ) {
 2616                self.show_signature_help(&ShowSignatureHelp, window, cx);
 2617            }
 2618            self.signature_help_state.set_backspace_pressed(false);
 2619        }
 2620
 2621        result
 2622    }
 2623
 2624    pub fn edit<I, S, T>(&mut self, edits: I, cx: &mut Context<Self>)
 2625    where
 2626        I: IntoIterator<Item = (Range<S>, T)>,
 2627        S: ToOffset,
 2628        T: Into<Arc<str>>,
 2629    {
 2630        if self.read_only(cx) {
 2631            return;
 2632        }
 2633
 2634        self.buffer
 2635            .update(cx, |buffer, cx| buffer.edit(edits, None, cx));
 2636    }
 2637
 2638    pub fn edit_with_autoindent<I, S, T>(&mut self, edits: I, cx: &mut Context<Self>)
 2639    where
 2640        I: IntoIterator<Item = (Range<S>, T)>,
 2641        S: ToOffset,
 2642        T: Into<Arc<str>>,
 2643    {
 2644        if self.read_only(cx) {
 2645            return;
 2646        }
 2647
 2648        self.buffer.update(cx, |buffer, cx| {
 2649            buffer.edit(edits, self.autoindent_mode.clone(), cx)
 2650        });
 2651    }
 2652
 2653    pub fn edit_with_block_indent<I, S, T>(
 2654        &mut self,
 2655        edits: I,
 2656        original_indent_columns: Vec<Option<u32>>,
 2657        cx: &mut Context<Self>,
 2658    ) where
 2659        I: IntoIterator<Item = (Range<S>, T)>,
 2660        S: ToOffset,
 2661        T: Into<Arc<str>>,
 2662    {
 2663        if self.read_only(cx) {
 2664            return;
 2665        }
 2666
 2667        self.buffer.update(cx, |buffer, cx| {
 2668            buffer.edit(
 2669                edits,
 2670                Some(AutoindentMode::Block {
 2671                    original_indent_columns,
 2672                }),
 2673                cx,
 2674            )
 2675        });
 2676    }
 2677
 2678    fn select(&mut self, phase: SelectPhase, window: &mut Window, cx: &mut Context<Self>) {
 2679        self.hide_context_menu(window, cx);
 2680
 2681        match phase {
 2682            SelectPhase::Begin {
 2683                position,
 2684                add,
 2685                click_count,
 2686            } => self.begin_selection(position, add, click_count, window, cx),
 2687            SelectPhase::BeginColumnar {
 2688                position,
 2689                goal_column,
 2690                reset,
 2691            } => self.begin_columnar_selection(position, goal_column, reset, window, cx),
 2692            SelectPhase::Extend {
 2693                position,
 2694                click_count,
 2695            } => self.extend_selection(position, click_count, window, cx),
 2696            SelectPhase::Update {
 2697                position,
 2698                goal_column,
 2699                scroll_delta,
 2700            } => self.update_selection(position, goal_column, scroll_delta, window, cx),
 2701            SelectPhase::End => self.end_selection(window, cx),
 2702        }
 2703    }
 2704
 2705    fn extend_selection(
 2706        &mut self,
 2707        position: DisplayPoint,
 2708        click_count: usize,
 2709        window: &mut Window,
 2710        cx: &mut Context<Self>,
 2711    ) {
 2712        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 2713        let tail = self.selections.newest::<usize>(cx).tail();
 2714        self.begin_selection(position, false, click_count, window, cx);
 2715
 2716        let position = position.to_offset(&display_map, Bias::Left);
 2717        let tail_anchor = display_map.buffer_snapshot.anchor_before(tail);
 2718
 2719        let mut pending_selection = self
 2720            .selections
 2721            .pending_anchor()
 2722            .expect("extend_selection not called with pending selection");
 2723        if position >= tail {
 2724            pending_selection.start = tail_anchor;
 2725        } else {
 2726            pending_selection.end = tail_anchor;
 2727            pending_selection.reversed = true;
 2728        }
 2729
 2730        let mut pending_mode = self.selections.pending_mode().unwrap();
 2731        match &mut pending_mode {
 2732            SelectMode::Word(range) | SelectMode::Line(range) => *range = tail_anchor..tail_anchor,
 2733            _ => {}
 2734        }
 2735
 2736        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 2737            s.set_pending(pending_selection, pending_mode)
 2738        });
 2739    }
 2740
 2741    fn begin_selection(
 2742        &mut self,
 2743        position: DisplayPoint,
 2744        add: bool,
 2745        click_count: usize,
 2746        window: &mut Window,
 2747        cx: &mut Context<Self>,
 2748    ) {
 2749        if !self.focus_handle.is_focused(window) {
 2750            self.last_focused_descendant = None;
 2751            window.focus(&self.focus_handle);
 2752        }
 2753
 2754        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 2755        let buffer = &display_map.buffer_snapshot;
 2756        let newest_selection = self.selections.newest_anchor().clone();
 2757        let position = display_map.clip_point(position, Bias::Left);
 2758
 2759        let start;
 2760        let end;
 2761        let mode;
 2762        let mut auto_scroll;
 2763        match click_count {
 2764            1 => {
 2765                start = buffer.anchor_before(position.to_point(&display_map));
 2766                end = start;
 2767                mode = SelectMode::Character;
 2768                auto_scroll = true;
 2769            }
 2770            2 => {
 2771                let range = movement::surrounding_word(&display_map, position);
 2772                start = buffer.anchor_before(range.start.to_point(&display_map));
 2773                end = buffer.anchor_before(range.end.to_point(&display_map));
 2774                mode = SelectMode::Word(start..end);
 2775                auto_scroll = true;
 2776            }
 2777            3 => {
 2778                let position = display_map
 2779                    .clip_point(position, Bias::Left)
 2780                    .to_point(&display_map);
 2781                let line_start = display_map.prev_line_boundary(position).0;
 2782                let next_line_start = buffer.clip_point(
 2783                    display_map.next_line_boundary(position).0 + Point::new(1, 0),
 2784                    Bias::Left,
 2785                );
 2786                start = buffer.anchor_before(line_start);
 2787                end = buffer.anchor_before(next_line_start);
 2788                mode = SelectMode::Line(start..end);
 2789                auto_scroll = true;
 2790            }
 2791            _ => {
 2792                start = buffer.anchor_before(0);
 2793                end = buffer.anchor_before(buffer.len());
 2794                mode = SelectMode::All;
 2795                auto_scroll = false;
 2796            }
 2797        }
 2798        auto_scroll &= EditorSettings::get_global(cx).autoscroll_on_clicks;
 2799
 2800        let point_to_delete: Option<usize> = {
 2801            let selected_points: Vec<Selection<Point>> =
 2802                self.selections.disjoint_in_range(start..end, cx);
 2803
 2804            if !add || click_count > 1 {
 2805                None
 2806            } else if !selected_points.is_empty() {
 2807                Some(selected_points[0].id)
 2808            } else {
 2809                let clicked_point_already_selected =
 2810                    self.selections.disjoint.iter().find(|selection| {
 2811                        selection.start.to_point(buffer) == start.to_point(buffer)
 2812                            || selection.end.to_point(buffer) == end.to_point(buffer)
 2813                    });
 2814
 2815                clicked_point_already_selected.map(|selection| selection.id)
 2816            }
 2817        };
 2818
 2819        let selections_count = self.selections.count();
 2820
 2821        self.change_selections(auto_scroll.then(Autoscroll::newest), window, cx, |s| {
 2822            if let Some(point_to_delete) = point_to_delete {
 2823                s.delete(point_to_delete);
 2824
 2825                if selections_count == 1 {
 2826                    s.set_pending_anchor_range(start..end, mode);
 2827                }
 2828            } else {
 2829                if !add {
 2830                    s.clear_disjoint();
 2831                } else if click_count > 1 {
 2832                    s.delete(newest_selection.id)
 2833                }
 2834
 2835                s.set_pending_anchor_range(start..end, mode);
 2836            }
 2837        });
 2838    }
 2839
 2840    fn begin_columnar_selection(
 2841        &mut self,
 2842        position: DisplayPoint,
 2843        goal_column: u32,
 2844        reset: bool,
 2845        window: &mut Window,
 2846        cx: &mut Context<Self>,
 2847    ) {
 2848        if !self.focus_handle.is_focused(window) {
 2849            self.last_focused_descendant = None;
 2850            window.focus(&self.focus_handle);
 2851        }
 2852
 2853        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 2854
 2855        if reset {
 2856            let pointer_position = display_map
 2857                .buffer_snapshot
 2858                .anchor_before(position.to_point(&display_map));
 2859
 2860            self.change_selections(Some(Autoscroll::newest()), window, cx, |s| {
 2861                s.clear_disjoint();
 2862                s.set_pending_anchor_range(
 2863                    pointer_position..pointer_position,
 2864                    SelectMode::Character,
 2865                );
 2866            });
 2867        }
 2868
 2869        let tail = self.selections.newest::<Point>(cx).tail();
 2870        self.columnar_selection_tail = Some(display_map.buffer_snapshot.anchor_before(tail));
 2871
 2872        if !reset {
 2873            self.select_columns(
 2874                tail.to_display_point(&display_map),
 2875                position,
 2876                goal_column,
 2877                &display_map,
 2878                window,
 2879                cx,
 2880            );
 2881        }
 2882    }
 2883
 2884    fn update_selection(
 2885        &mut self,
 2886        position: DisplayPoint,
 2887        goal_column: u32,
 2888        scroll_delta: gpui::Point<f32>,
 2889        window: &mut Window,
 2890        cx: &mut Context<Self>,
 2891    ) {
 2892        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 2893
 2894        if let Some(tail) = self.columnar_selection_tail.as_ref() {
 2895            let tail = tail.to_display_point(&display_map);
 2896            self.select_columns(tail, position, goal_column, &display_map, window, cx);
 2897        } else if let Some(mut pending) = self.selections.pending_anchor() {
 2898            let buffer = self.buffer.read(cx).snapshot(cx);
 2899            let head;
 2900            let tail;
 2901            let mode = self.selections.pending_mode().unwrap();
 2902            match &mode {
 2903                SelectMode::Character => {
 2904                    head = position.to_point(&display_map);
 2905                    tail = pending.tail().to_point(&buffer);
 2906                }
 2907                SelectMode::Word(original_range) => {
 2908                    let original_display_range = original_range.start.to_display_point(&display_map)
 2909                        ..original_range.end.to_display_point(&display_map);
 2910                    let original_buffer_range = original_display_range.start.to_point(&display_map)
 2911                        ..original_display_range.end.to_point(&display_map);
 2912                    if movement::is_inside_word(&display_map, position)
 2913                        || original_display_range.contains(&position)
 2914                    {
 2915                        let word_range = movement::surrounding_word(&display_map, position);
 2916                        if word_range.start < original_display_range.start {
 2917                            head = word_range.start.to_point(&display_map);
 2918                        } else {
 2919                            head = word_range.end.to_point(&display_map);
 2920                        }
 2921                    } else {
 2922                        head = position.to_point(&display_map);
 2923                    }
 2924
 2925                    if head <= original_buffer_range.start {
 2926                        tail = original_buffer_range.end;
 2927                    } else {
 2928                        tail = original_buffer_range.start;
 2929                    }
 2930                }
 2931                SelectMode::Line(original_range) => {
 2932                    let original_range = original_range.to_point(&display_map.buffer_snapshot);
 2933
 2934                    let position = display_map
 2935                        .clip_point(position, Bias::Left)
 2936                        .to_point(&display_map);
 2937                    let line_start = display_map.prev_line_boundary(position).0;
 2938                    let next_line_start = buffer.clip_point(
 2939                        display_map.next_line_boundary(position).0 + Point::new(1, 0),
 2940                        Bias::Left,
 2941                    );
 2942
 2943                    if line_start < original_range.start {
 2944                        head = line_start
 2945                    } else {
 2946                        head = next_line_start
 2947                    }
 2948
 2949                    if head <= original_range.start {
 2950                        tail = original_range.end;
 2951                    } else {
 2952                        tail = original_range.start;
 2953                    }
 2954                }
 2955                SelectMode::All => {
 2956                    return;
 2957                }
 2958            };
 2959
 2960            if head < tail {
 2961                pending.start = buffer.anchor_before(head);
 2962                pending.end = buffer.anchor_before(tail);
 2963                pending.reversed = true;
 2964            } else {
 2965                pending.start = buffer.anchor_before(tail);
 2966                pending.end = buffer.anchor_before(head);
 2967                pending.reversed = false;
 2968            }
 2969
 2970            self.change_selections(None, window, cx, |s| {
 2971                s.set_pending(pending, mode);
 2972            });
 2973        } else {
 2974            log::error!("update_selection dispatched with no pending selection");
 2975            return;
 2976        }
 2977
 2978        self.apply_scroll_delta(scroll_delta, window, cx);
 2979        cx.notify();
 2980    }
 2981
 2982    fn end_selection(&mut self, window: &mut Window, cx: &mut Context<Self>) {
 2983        self.columnar_selection_tail.take();
 2984        if self.selections.pending_anchor().is_some() {
 2985            let selections = self.selections.all::<usize>(cx);
 2986            self.change_selections(None, window, cx, |s| {
 2987                s.select(selections);
 2988                s.clear_pending();
 2989            });
 2990        }
 2991    }
 2992
 2993    fn select_columns(
 2994        &mut self,
 2995        tail: DisplayPoint,
 2996        head: DisplayPoint,
 2997        goal_column: u32,
 2998        display_map: &DisplaySnapshot,
 2999        window: &mut Window,
 3000        cx: &mut Context<Self>,
 3001    ) {
 3002        let start_row = cmp::min(tail.row(), head.row());
 3003        let end_row = cmp::max(tail.row(), head.row());
 3004        let start_column = cmp::min(tail.column(), goal_column);
 3005        let end_column = cmp::max(tail.column(), goal_column);
 3006        let reversed = start_column < tail.column();
 3007
 3008        let selection_ranges = (start_row.0..=end_row.0)
 3009            .map(DisplayRow)
 3010            .filter_map(|row| {
 3011                if start_column <= display_map.line_len(row) && !display_map.is_block_line(row) {
 3012                    let start = display_map
 3013                        .clip_point(DisplayPoint::new(row, start_column), Bias::Left)
 3014                        .to_point(display_map);
 3015                    let end = display_map
 3016                        .clip_point(DisplayPoint::new(row, end_column), Bias::Right)
 3017                        .to_point(display_map);
 3018                    if reversed {
 3019                        Some(end..start)
 3020                    } else {
 3021                        Some(start..end)
 3022                    }
 3023                } else {
 3024                    None
 3025                }
 3026            })
 3027            .collect::<Vec<_>>();
 3028
 3029        self.change_selections(None, window, cx, |s| {
 3030            s.select_ranges(selection_ranges);
 3031        });
 3032        cx.notify();
 3033    }
 3034
 3035    pub fn has_pending_nonempty_selection(&self) -> bool {
 3036        let pending_nonempty_selection = match self.selections.pending_anchor() {
 3037            Some(Selection { start, end, .. }) => start != end,
 3038            None => false,
 3039        };
 3040
 3041        pending_nonempty_selection
 3042            || (self.columnar_selection_tail.is_some() && self.selections.disjoint.len() > 1)
 3043    }
 3044
 3045    pub fn has_pending_selection(&self) -> bool {
 3046        self.selections.pending_anchor().is_some() || self.columnar_selection_tail.is_some()
 3047    }
 3048
 3049    pub fn cancel(&mut self, _: &Cancel, window: &mut Window, cx: &mut Context<Self>) {
 3050        self.selection_mark_mode = false;
 3051
 3052        if self.clear_expanded_diff_hunks(cx) {
 3053            cx.notify();
 3054            return;
 3055        }
 3056        if self.dismiss_menus_and_popups(true, window, cx) {
 3057            return;
 3058        }
 3059
 3060        if self.mode.is_full()
 3061            && self.change_selections(Some(Autoscroll::fit()), window, cx, |s| s.try_cancel())
 3062        {
 3063            return;
 3064        }
 3065
 3066        cx.propagate();
 3067    }
 3068
 3069    pub fn dismiss_menus_and_popups(
 3070        &mut self,
 3071        is_user_requested: bool,
 3072        window: &mut Window,
 3073        cx: &mut Context<Self>,
 3074    ) -> bool {
 3075        if self.take_rename(false, window, cx).is_some() {
 3076            return true;
 3077        }
 3078
 3079        if hide_hover(self, cx) {
 3080            return true;
 3081        }
 3082
 3083        if self.hide_signature_help(cx, SignatureHelpHiddenBy::Escape) {
 3084            return true;
 3085        }
 3086
 3087        if self.hide_context_menu(window, cx).is_some() {
 3088            return true;
 3089        }
 3090
 3091        if self.mouse_context_menu.take().is_some() {
 3092            return true;
 3093        }
 3094
 3095        if is_user_requested && self.discard_inline_completion(true, cx) {
 3096            return true;
 3097        }
 3098
 3099        if self.snippet_stack.pop().is_some() {
 3100            return true;
 3101        }
 3102
 3103        if self.mode.is_full() && matches!(self.active_diagnostics, ActiveDiagnostic::Group(_)) {
 3104            self.dismiss_diagnostics(cx);
 3105            return true;
 3106        }
 3107
 3108        false
 3109    }
 3110
 3111    fn linked_editing_ranges_for(
 3112        &self,
 3113        selection: Range<text::Anchor>,
 3114        cx: &App,
 3115    ) -> Option<HashMap<Entity<Buffer>, Vec<Range<text::Anchor>>>> {
 3116        if self.linked_edit_ranges.is_empty() {
 3117            return None;
 3118        }
 3119        let ((base_range, linked_ranges), buffer_snapshot, buffer) =
 3120            selection.end.buffer_id.and_then(|end_buffer_id| {
 3121                if selection.start.buffer_id != Some(end_buffer_id) {
 3122                    return None;
 3123                }
 3124                let buffer = self.buffer.read(cx).buffer(end_buffer_id)?;
 3125                let snapshot = buffer.read(cx).snapshot();
 3126                self.linked_edit_ranges
 3127                    .get(end_buffer_id, selection.start..selection.end, &snapshot)
 3128                    .map(|ranges| (ranges, snapshot, buffer))
 3129            })?;
 3130        use text::ToOffset as TO;
 3131        // find offset from the start of current range to current cursor position
 3132        let start_byte_offset = TO::to_offset(&base_range.start, &buffer_snapshot);
 3133
 3134        let start_offset = TO::to_offset(&selection.start, &buffer_snapshot);
 3135        let start_difference = start_offset - start_byte_offset;
 3136        let end_offset = TO::to_offset(&selection.end, &buffer_snapshot);
 3137        let end_difference = end_offset - start_byte_offset;
 3138        // Current range has associated linked ranges.
 3139        let mut linked_edits = HashMap::<_, Vec<_>>::default();
 3140        for range in linked_ranges.iter() {
 3141            let start_offset = TO::to_offset(&range.start, &buffer_snapshot);
 3142            let end_offset = start_offset + end_difference;
 3143            let start_offset = start_offset + start_difference;
 3144            if start_offset > buffer_snapshot.len() || end_offset > buffer_snapshot.len() {
 3145                continue;
 3146            }
 3147            if self.selections.disjoint_anchor_ranges().any(|s| {
 3148                if s.start.buffer_id != selection.start.buffer_id
 3149                    || s.end.buffer_id != selection.end.buffer_id
 3150                {
 3151                    return false;
 3152                }
 3153                TO::to_offset(&s.start.text_anchor, &buffer_snapshot) <= end_offset
 3154                    && TO::to_offset(&s.end.text_anchor, &buffer_snapshot) >= start_offset
 3155            }) {
 3156                continue;
 3157            }
 3158            let start = buffer_snapshot.anchor_after(start_offset);
 3159            let end = buffer_snapshot.anchor_after(end_offset);
 3160            linked_edits
 3161                .entry(buffer.clone())
 3162                .or_default()
 3163                .push(start..end);
 3164        }
 3165        Some(linked_edits)
 3166    }
 3167
 3168    pub fn handle_input(&mut self, text: &str, window: &mut Window, cx: &mut Context<Self>) {
 3169        let text: Arc<str> = text.into();
 3170
 3171        if self.read_only(cx) {
 3172            return;
 3173        }
 3174
 3175        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
 3176
 3177        let selections = self.selections.all_adjusted(cx);
 3178        let mut bracket_inserted = false;
 3179        let mut edits = Vec::new();
 3180        let mut linked_edits = HashMap::<_, Vec<_>>::default();
 3181        let mut new_selections = Vec::with_capacity(selections.len());
 3182        let mut new_autoclose_regions = Vec::new();
 3183        let snapshot = self.buffer.read(cx).read(cx);
 3184        let mut clear_linked_edit_ranges = false;
 3185
 3186        for (selection, autoclose_region) in
 3187            self.selections_with_autoclose_regions(selections, &snapshot)
 3188        {
 3189            if let Some(scope) = snapshot.language_scope_at(selection.head()) {
 3190                // Determine if the inserted text matches the opening or closing
 3191                // bracket of any of this language's bracket pairs.
 3192                let mut bracket_pair = None;
 3193                let mut is_bracket_pair_start = false;
 3194                let mut is_bracket_pair_end = false;
 3195                if !text.is_empty() {
 3196                    let mut bracket_pair_matching_end = None;
 3197                    // `text` can be empty when a user is using IME (e.g. Chinese Wubi Simplified)
 3198                    //  and they are removing the character that triggered IME popup.
 3199                    for (pair, enabled) in scope.brackets() {
 3200                        if !pair.close && !pair.surround {
 3201                            continue;
 3202                        }
 3203
 3204                        if enabled && pair.start.ends_with(text.as_ref()) {
 3205                            let prefix_len = pair.start.len() - text.len();
 3206                            let preceding_text_matches_prefix = prefix_len == 0
 3207                                || (selection.start.column >= (prefix_len as u32)
 3208                                    && snapshot.contains_str_at(
 3209                                        Point::new(
 3210                                            selection.start.row,
 3211                                            selection.start.column - (prefix_len as u32),
 3212                                        ),
 3213                                        &pair.start[..prefix_len],
 3214                                    ));
 3215                            if preceding_text_matches_prefix {
 3216                                bracket_pair = Some(pair.clone());
 3217                                is_bracket_pair_start = true;
 3218                                break;
 3219                            }
 3220                        }
 3221                        if pair.end.as_str() == text.as_ref() && bracket_pair_matching_end.is_none()
 3222                        {
 3223                            // take first bracket pair matching end, but don't break in case a later bracket
 3224                            // pair matches start
 3225                            bracket_pair_matching_end = Some(pair.clone());
 3226                        }
 3227                    }
 3228                    if bracket_pair.is_none() && bracket_pair_matching_end.is_some() {
 3229                        bracket_pair = Some(bracket_pair_matching_end.unwrap());
 3230                        is_bracket_pair_end = true;
 3231                    }
 3232                }
 3233
 3234                if let Some(bracket_pair) = bracket_pair {
 3235                    let snapshot_settings = snapshot.language_settings_at(selection.start, cx);
 3236                    let autoclose = self.use_autoclose && snapshot_settings.use_autoclose;
 3237                    let auto_surround =
 3238                        self.use_auto_surround && snapshot_settings.use_auto_surround;
 3239                    if selection.is_empty() {
 3240                        if is_bracket_pair_start {
 3241                            // If the inserted text is a suffix of an opening bracket and the
 3242                            // selection is preceded by the rest of the opening bracket, then
 3243                            // insert the closing bracket.
 3244                            let following_text_allows_autoclose = snapshot
 3245                                .chars_at(selection.start)
 3246                                .next()
 3247                                .map_or(true, |c| scope.should_autoclose_before(c));
 3248
 3249                            let preceding_text_allows_autoclose = selection.start.column == 0
 3250                                || snapshot.reversed_chars_at(selection.start).next().map_or(
 3251                                    true,
 3252                                    |c| {
 3253                                        bracket_pair.start != bracket_pair.end
 3254                                            || !snapshot
 3255                                                .char_classifier_at(selection.start)
 3256                                                .is_word(c)
 3257                                    },
 3258                                );
 3259
 3260                            let is_closing_quote = if bracket_pair.end == bracket_pair.start
 3261                                && bracket_pair.start.len() == 1
 3262                            {
 3263                                let target = bracket_pair.start.chars().next().unwrap();
 3264                                let current_line_count = snapshot
 3265                                    .reversed_chars_at(selection.start)
 3266                                    .take_while(|&c| c != '\n')
 3267                                    .filter(|&c| c == target)
 3268                                    .count();
 3269                                current_line_count % 2 == 1
 3270                            } else {
 3271                                false
 3272                            };
 3273
 3274                            if autoclose
 3275                                && bracket_pair.close
 3276                                && following_text_allows_autoclose
 3277                                && preceding_text_allows_autoclose
 3278                                && !is_closing_quote
 3279                            {
 3280                                let anchor = snapshot.anchor_before(selection.end);
 3281                                new_selections.push((selection.map(|_| anchor), text.len()));
 3282                                new_autoclose_regions.push((
 3283                                    anchor,
 3284                                    text.len(),
 3285                                    selection.id,
 3286                                    bracket_pair.clone(),
 3287                                ));
 3288                                edits.push((
 3289                                    selection.range(),
 3290                                    format!("{}{}", text, bracket_pair.end).into(),
 3291                                ));
 3292                                bracket_inserted = true;
 3293                                continue;
 3294                            }
 3295                        }
 3296
 3297                        if let Some(region) = autoclose_region {
 3298                            // If the selection is followed by an auto-inserted closing bracket,
 3299                            // then don't insert that closing bracket again; just move the selection
 3300                            // past the closing bracket.
 3301                            let should_skip = selection.end == region.range.end.to_point(&snapshot)
 3302                                && text.as_ref() == region.pair.end.as_str();
 3303                            if should_skip {
 3304                                let anchor = snapshot.anchor_after(selection.end);
 3305                                new_selections
 3306                                    .push((selection.map(|_| anchor), region.pair.end.len()));
 3307                                continue;
 3308                            }
 3309                        }
 3310
 3311                        let always_treat_brackets_as_autoclosed = snapshot
 3312                            .language_settings_at(selection.start, cx)
 3313                            .always_treat_brackets_as_autoclosed;
 3314                        if always_treat_brackets_as_autoclosed
 3315                            && is_bracket_pair_end
 3316                            && snapshot.contains_str_at(selection.end, text.as_ref())
 3317                        {
 3318                            // Otherwise, when `always_treat_brackets_as_autoclosed` is set to `true
 3319                            // and the inserted text is a closing bracket and the selection is followed
 3320                            // by the closing bracket then move the selection past the closing bracket.
 3321                            let anchor = snapshot.anchor_after(selection.end);
 3322                            new_selections.push((selection.map(|_| anchor), text.len()));
 3323                            continue;
 3324                        }
 3325                    }
 3326                    // If an opening bracket is 1 character long and is typed while
 3327                    // text is selected, then surround that text with the bracket pair.
 3328                    else if auto_surround
 3329                        && bracket_pair.surround
 3330                        && is_bracket_pair_start
 3331                        && bracket_pair.start.chars().count() == 1
 3332                    {
 3333                        edits.push((selection.start..selection.start, text.clone()));
 3334                        edits.push((
 3335                            selection.end..selection.end,
 3336                            bracket_pair.end.as_str().into(),
 3337                        ));
 3338                        bracket_inserted = true;
 3339                        new_selections.push((
 3340                            Selection {
 3341                                id: selection.id,
 3342                                start: snapshot.anchor_after(selection.start),
 3343                                end: snapshot.anchor_before(selection.end),
 3344                                reversed: selection.reversed,
 3345                                goal: selection.goal,
 3346                            },
 3347                            0,
 3348                        ));
 3349                        continue;
 3350                    }
 3351                }
 3352            }
 3353
 3354            if self.auto_replace_emoji_shortcode
 3355                && selection.is_empty()
 3356                && text.as_ref().ends_with(':')
 3357            {
 3358                if let Some(possible_emoji_short_code) =
 3359                    Self::find_possible_emoji_shortcode_at_position(&snapshot, selection.start)
 3360                {
 3361                    if !possible_emoji_short_code.is_empty() {
 3362                        if let Some(emoji) = emojis::get_by_shortcode(&possible_emoji_short_code) {
 3363                            let emoji_shortcode_start = Point::new(
 3364                                selection.start.row,
 3365                                selection.start.column - possible_emoji_short_code.len() as u32 - 1,
 3366                            );
 3367
 3368                            // Remove shortcode from buffer
 3369                            edits.push((
 3370                                emoji_shortcode_start..selection.start,
 3371                                "".to_string().into(),
 3372                            ));
 3373                            new_selections.push((
 3374                                Selection {
 3375                                    id: selection.id,
 3376                                    start: snapshot.anchor_after(emoji_shortcode_start),
 3377                                    end: snapshot.anchor_before(selection.start),
 3378                                    reversed: selection.reversed,
 3379                                    goal: selection.goal,
 3380                                },
 3381                                0,
 3382                            ));
 3383
 3384                            // Insert emoji
 3385                            let selection_start_anchor = snapshot.anchor_after(selection.start);
 3386                            new_selections.push((selection.map(|_| selection_start_anchor), 0));
 3387                            edits.push((selection.start..selection.end, emoji.to_string().into()));
 3388
 3389                            continue;
 3390                        }
 3391                    }
 3392                }
 3393            }
 3394
 3395            // If not handling any auto-close operation, then just replace the selected
 3396            // text with the given input and move the selection to the end of the
 3397            // newly inserted text.
 3398            let anchor = snapshot.anchor_after(selection.end);
 3399            if !self.linked_edit_ranges.is_empty() {
 3400                let start_anchor = snapshot.anchor_before(selection.start);
 3401
 3402                let is_word_char = text.chars().next().map_or(true, |char| {
 3403                    let classifier = snapshot.char_classifier_at(start_anchor.to_offset(&snapshot));
 3404                    classifier.is_word(char)
 3405                });
 3406
 3407                if is_word_char {
 3408                    if let Some(ranges) = self
 3409                        .linked_editing_ranges_for(start_anchor.text_anchor..anchor.text_anchor, cx)
 3410                    {
 3411                        for (buffer, edits) in ranges {
 3412                            linked_edits
 3413                                .entry(buffer.clone())
 3414                                .or_default()
 3415                                .extend(edits.into_iter().map(|range| (range, text.clone())));
 3416                        }
 3417                    }
 3418                } else {
 3419                    clear_linked_edit_ranges = true;
 3420                }
 3421            }
 3422
 3423            new_selections.push((selection.map(|_| anchor), 0));
 3424            edits.push((selection.start..selection.end, text.clone()));
 3425        }
 3426
 3427        drop(snapshot);
 3428
 3429        self.transact(window, cx, |this, window, cx| {
 3430            if clear_linked_edit_ranges {
 3431                this.linked_edit_ranges.clear();
 3432            }
 3433            let initial_buffer_versions =
 3434                jsx_tag_auto_close::construct_initial_buffer_versions_map(this, &edits, cx);
 3435
 3436            this.buffer.update(cx, |buffer, cx| {
 3437                buffer.edit(edits, this.autoindent_mode.clone(), cx);
 3438            });
 3439            for (buffer, edits) in linked_edits {
 3440                buffer.update(cx, |buffer, cx| {
 3441                    let snapshot = buffer.snapshot();
 3442                    let edits = edits
 3443                        .into_iter()
 3444                        .map(|(range, text)| {
 3445                            use text::ToPoint as TP;
 3446                            let end_point = TP::to_point(&range.end, &snapshot);
 3447                            let start_point = TP::to_point(&range.start, &snapshot);
 3448                            (start_point..end_point, text)
 3449                        })
 3450                        .sorted_by_key(|(range, _)| range.start);
 3451                    buffer.edit(edits, None, cx);
 3452                })
 3453            }
 3454            let new_anchor_selections = new_selections.iter().map(|e| &e.0);
 3455            let new_selection_deltas = new_selections.iter().map(|e| e.1);
 3456            let map = this.display_map.update(cx, |map, cx| map.snapshot(cx));
 3457            let new_selections = resolve_selections::<usize, _>(new_anchor_selections, &map)
 3458                .zip(new_selection_deltas)
 3459                .map(|(selection, delta)| Selection {
 3460                    id: selection.id,
 3461                    start: selection.start + delta,
 3462                    end: selection.end + delta,
 3463                    reversed: selection.reversed,
 3464                    goal: SelectionGoal::None,
 3465                })
 3466                .collect::<Vec<_>>();
 3467
 3468            let mut i = 0;
 3469            for (position, delta, selection_id, pair) in new_autoclose_regions {
 3470                let position = position.to_offset(&map.buffer_snapshot) + delta;
 3471                let start = map.buffer_snapshot.anchor_before(position);
 3472                let end = map.buffer_snapshot.anchor_after(position);
 3473                while let Some(existing_state) = this.autoclose_regions.get(i) {
 3474                    match existing_state.range.start.cmp(&start, &map.buffer_snapshot) {
 3475                        Ordering::Less => i += 1,
 3476                        Ordering::Greater => break,
 3477                        Ordering::Equal => {
 3478                            match end.cmp(&existing_state.range.end, &map.buffer_snapshot) {
 3479                                Ordering::Less => i += 1,
 3480                                Ordering::Equal => break,
 3481                                Ordering::Greater => break,
 3482                            }
 3483                        }
 3484                    }
 3485                }
 3486                this.autoclose_regions.insert(
 3487                    i,
 3488                    AutocloseRegion {
 3489                        selection_id,
 3490                        range: start..end,
 3491                        pair,
 3492                    },
 3493                );
 3494            }
 3495
 3496            let had_active_inline_completion = this.has_active_inline_completion();
 3497            this.change_selections_inner(Some(Autoscroll::fit()), false, window, cx, |s| {
 3498                s.select(new_selections)
 3499            });
 3500
 3501            if !bracket_inserted {
 3502                if let Some(on_type_format_task) =
 3503                    this.trigger_on_type_formatting(text.to_string(), window, cx)
 3504                {
 3505                    on_type_format_task.detach_and_log_err(cx);
 3506                }
 3507            }
 3508
 3509            let editor_settings = EditorSettings::get_global(cx);
 3510            if bracket_inserted
 3511                && (editor_settings.auto_signature_help
 3512                    || editor_settings.show_signature_help_after_edits)
 3513            {
 3514                this.show_signature_help(&ShowSignatureHelp, window, cx);
 3515            }
 3516
 3517            let trigger_in_words =
 3518                this.show_edit_predictions_in_menu() || !had_active_inline_completion;
 3519            if this.hard_wrap.is_some() {
 3520                let latest: Range<Point> = this.selections.newest(cx).range();
 3521                if latest.is_empty()
 3522                    && this
 3523                        .buffer()
 3524                        .read(cx)
 3525                        .snapshot(cx)
 3526                        .line_len(MultiBufferRow(latest.start.row))
 3527                        == latest.start.column
 3528                {
 3529                    this.rewrap_impl(
 3530                        RewrapOptions {
 3531                            override_language_settings: true,
 3532                            preserve_existing_whitespace: true,
 3533                        },
 3534                        cx,
 3535                    )
 3536                }
 3537            }
 3538            this.trigger_completion_on_input(&text, trigger_in_words, window, cx);
 3539            linked_editing_ranges::refresh_linked_ranges(this, window, cx);
 3540            this.refresh_inline_completion(true, false, window, cx);
 3541            jsx_tag_auto_close::handle_from(this, initial_buffer_versions, window, cx);
 3542        });
 3543    }
 3544
 3545    fn find_possible_emoji_shortcode_at_position(
 3546        snapshot: &MultiBufferSnapshot,
 3547        position: Point,
 3548    ) -> Option<String> {
 3549        let mut chars = Vec::new();
 3550        let mut found_colon = false;
 3551        for char in snapshot.reversed_chars_at(position).take(100) {
 3552            // Found a possible emoji shortcode in the middle of the buffer
 3553            if found_colon {
 3554                if char.is_whitespace() {
 3555                    chars.reverse();
 3556                    return Some(chars.iter().collect());
 3557                }
 3558                // If the previous character is not a whitespace, we are in the middle of a word
 3559                // and we only want to complete the shortcode if the word is made up of other emojis
 3560                let mut containing_word = String::new();
 3561                for ch in snapshot
 3562                    .reversed_chars_at(position)
 3563                    .skip(chars.len() + 1)
 3564                    .take(100)
 3565                {
 3566                    if ch.is_whitespace() {
 3567                        break;
 3568                    }
 3569                    containing_word.push(ch);
 3570                }
 3571                let containing_word = containing_word.chars().rev().collect::<String>();
 3572                if util::word_consists_of_emojis(containing_word.as_str()) {
 3573                    chars.reverse();
 3574                    return Some(chars.iter().collect());
 3575                }
 3576            }
 3577
 3578            if char.is_whitespace() || !char.is_ascii() {
 3579                return None;
 3580            }
 3581            if char == ':' {
 3582                found_colon = true;
 3583            } else {
 3584                chars.push(char);
 3585            }
 3586        }
 3587        // Found a possible emoji shortcode at the beginning of the buffer
 3588        chars.reverse();
 3589        Some(chars.iter().collect())
 3590    }
 3591
 3592    pub fn newline(&mut self, _: &Newline, window: &mut Window, cx: &mut Context<Self>) {
 3593        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
 3594        self.transact(window, cx, |this, window, cx| {
 3595            let (edits, selection_fixup_info): (Vec<_>, Vec<_>) = {
 3596                let selections = this.selections.all::<usize>(cx);
 3597                let multi_buffer = this.buffer.read(cx);
 3598                let buffer = multi_buffer.snapshot(cx);
 3599                selections
 3600                    .iter()
 3601                    .map(|selection| {
 3602                        let start_point = selection.start.to_point(&buffer);
 3603                        let mut indent =
 3604                            buffer.indent_size_for_line(MultiBufferRow(start_point.row));
 3605                        indent.len = cmp::min(indent.len, start_point.column);
 3606                        let start = selection.start;
 3607                        let end = selection.end;
 3608                        let selection_is_empty = start == end;
 3609                        let language_scope = buffer.language_scope_at(start);
 3610                        let (comment_delimiter, insert_extra_newline) = if let Some(language) =
 3611                            &language_scope
 3612                        {
 3613                            let insert_extra_newline =
 3614                                insert_extra_newline_brackets(&buffer, start..end, language)
 3615                                    || insert_extra_newline_tree_sitter(&buffer, start..end);
 3616
 3617                            // Comment extension on newline is allowed only for cursor selections
 3618                            let comment_delimiter = maybe!({
 3619                                if !selection_is_empty {
 3620                                    return None;
 3621                                }
 3622
 3623                                if !multi_buffer.language_settings(cx).extend_comment_on_newline {
 3624                                    return None;
 3625                                }
 3626
 3627                                let delimiters = language.line_comment_prefixes();
 3628                                let max_len_of_delimiter =
 3629                                    delimiters.iter().map(|delimiter| delimiter.len()).max()?;
 3630                                let (snapshot, range) =
 3631                                    buffer.buffer_line_for_row(MultiBufferRow(start_point.row))?;
 3632
 3633                                let mut index_of_first_non_whitespace = 0;
 3634                                let comment_candidate = snapshot
 3635                                    .chars_for_range(range)
 3636                                    .skip_while(|c| {
 3637                                        let should_skip = c.is_whitespace();
 3638                                        if should_skip {
 3639                                            index_of_first_non_whitespace += 1;
 3640                                        }
 3641                                        should_skip
 3642                                    })
 3643                                    .take(max_len_of_delimiter)
 3644                                    .collect::<String>();
 3645                                let comment_prefix = delimiters.iter().find(|comment_prefix| {
 3646                                    comment_candidate.starts_with(comment_prefix.as_ref())
 3647                                })?;
 3648                                let cursor_is_placed_after_comment_marker =
 3649                                    index_of_first_non_whitespace + comment_prefix.len()
 3650                                        <= start_point.column as usize;
 3651                                if cursor_is_placed_after_comment_marker {
 3652                                    Some(comment_prefix.clone())
 3653                                } else {
 3654                                    None
 3655                                }
 3656                            });
 3657                            (comment_delimiter, insert_extra_newline)
 3658                        } else {
 3659                            (None, false)
 3660                        };
 3661
 3662                        let capacity_for_delimiter = comment_delimiter
 3663                            .as_deref()
 3664                            .map(str::len)
 3665                            .unwrap_or_default();
 3666                        let mut new_text =
 3667                            String::with_capacity(1 + capacity_for_delimiter + indent.len as usize);
 3668                        new_text.push('\n');
 3669                        new_text.extend(indent.chars());
 3670                        if let Some(delimiter) = &comment_delimiter {
 3671                            new_text.push_str(delimiter);
 3672                        }
 3673                        if insert_extra_newline {
 3674                            new_text = new_text.repeat(2);
 3675                        }
 3676
 3677                        let anchor = buffer.anchor_after(end);
 3678                        let new_selection = selection.map(|_| anchor);
 3679                        (
 3680                            (start..end, new_text),
 3681                            (insert_extra_newline, new_selection),
 3682                        )
 3683                    })
 3684                    .unzip()
 3685            };
 3686
 3687            this.edit_with_autoindent(edits, cx);
 3688            let buffer = this.buffer.read(cx).snapshot(cx);
 3689            let new_selections = selection_fixup_info
 3690                .into_iter()
 3691                .map(|(extra_newline_inserted, new_selection)| {
 3692                    let mut cursor = new_selection.end.to_point(&buffer);
 3693                    if extra_newline_inserted {
 3694                        cursor.row -= 1;
 3695                        cursor.column = buffer.line_len(MultiBufferRow(cursor.row));
 3696                    }
 3697                    new_selection.map(|_| cursor)
 3698                })
 3699                .collect();
 3700
 3701            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 3702                s.select(new_selections)
 3703            });
 3704            this.refresh_inline_completion(true, false, window, cx);
 3705        });
 3706    }
 3707
 3708    pub fn newline_above(&mut self, _: &NewlineAbove, window: &mut Window, cx: &mut Context<Self>) {
 3709        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
 3710
 3711        let buffer = self.buffer.read(cx);
 3712        let snapshot = buffer.snapshot(cx);
 3713
 3714        let mut edits = Vec::new();
 3715        let mut rows = Vec::new();
 3716
 3717        for (rows_inserted, selection) in self.selections.all_adjusted(cx).into_iter().enumerate() {
 3718            let cursor = selection.head();
 3719            let row = cursor.row;
 3720
 3721            let start_of_line = snapshot.clip_point(Point::new(row, 0), Bias::Left);
 3722
 3723            let newline = "\n".to_string();
 3724            edits.push((start_of_line..start_of_line, newline));
 3725
 3726            rows.push(row + rows_inserted as u32);
 3727        }
 3728
 3729        self.transact(window, cx, |editor, window, cx| {
 3730            editor.edit(edits, cx);
 3731
 3732            editor.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 3733                let mut index = 0;
 3734                s.move_cursors_with(|map, _, _| {
 3735                    let row = rows[index];
 3736                    index += 1;
 3737
 3738                    let point = Point::new(row, 0);
 3739                    let boundary = map.next_line_boundary(point).1;
 3740                    let clipped = map.clip_point(boundary, Bias::Left);
 3741
 3742                    (clipped, SelectionGoal::None)
 3743                });
 3744            });
 3745
 3746            let mut indent_edits = Vec::new();
 3747            let multibuffer_snapshot = editor.buffer.read(cx).snapshot(cx);
 3748            for row in rows {
 3749                let indents = multibuffer_snapshot.suggested_indents(row..row + 1, cx);
 3750                for (row, indent) in indents {
 3751                    if indent.len == 0 {
 3752                        continue;
 3753                    }
 3754
 3755                    let text = match indent.kind {
 3756                        IndentKind::Space => " ".repeat(indent.len as usize),
 3757                        IndentKind::Tab => "\t".repeat(indent.len as usize),
 3758                    };
 3759                    let point = Point::new(row.0, 0);
 3760                    indent_edits.push((point..point, text));
 3761                }
 3762            }
 3763            editor.edit(indent_edits, cx);
 3764        });
 3765    }
 3766
 3767    pub fn newline_below(&mut self, _: &NewlineBelow, window: &mut Window, cx: &mut Context<Self>) {
 3768        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
 3769
 3770        let buffer = self.buffer.read(cx);
 3771        let snapshot = buffer.snapshot(cx);
 3772
 3773        let mut edits = Vec::new();
 3774        let mut rows = Vec::new();
 3775        let mut rows_inserted = 0;
 3776
 3777        for selection in self.selections.all_adjusted(cx) {
 3778            let cursor = selection.head();
 3779            let row = cursor.row;
 3780
 3781            let point = Point::new(row + 1, 0);
 3782            let start_of_line = snapshot.clip_point(point, Bias::Left);
 3783
 3784            let newline = "\n".to_string();
 3785            edits.push((start_of_line..start_of_line, newline));
 3786
 3787            rows_inserted += 1;
 3788            rows.push(row + rows_inserted);
 3789        }
 3790
 3791        self.transact(window, cx, |editor, window, cx| {
 3792            editor.edit(edits, cx);
 3793
 3794            editor.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 3795                let mut index = 0;
 3796                s.move_cursors_with(|map, _, _| {
 3797                    let row = rows[index];
 3798                    index += 1;
 3799
 3800                    let point = Point::new(row, 0);
 3801                    let boundary = map.next_line_boundary(point).1;
 3802                    let clipped = map.clip_point(boundary, Bias::Left);
 3803
 3804                    (clipped, SelectionGoal::None)
 3805                });
 3806            });
 3807
 3808            let mut indent_edits = Vec::new();
 3809            let multibuffer_snapshot = editor.buffer.read(cx).snapshot(cx);
 3810            for row in rows {
 3811                let indents = multibuffer_snapshot.suggested_indents(row..row + 1, cx);
 3812                for (row, indent) in indents {
 3813                    if indent.len == 0 {
 3814                        continue;
 3815                    }
 3816
 3817                    let text = match indent.kind {
 3818                        IndentKind::Space => " ".repeat(indent.len as usize),
 3819                        IndentKind::Tab => "\t".repeat(indent.len as usize),
 3820                    };
 3821                    let point = Point::new(row.0, 0);
 3822                    indent_edits.push((point..point, text));
 3823                }
 3824            }
 3825            editor.edit(indent_edits, cx);
 3826        });
 3827    }
 3828
 3829    pub fn insert(&mut self, text: &str, window: &mut Window, cx: &mut Context<Self>) {
 3830        let autoindent = text.is_empty().not().then(|| AutoindentMode::Block {
 3831            original_indent_columns: Vec::new(),
 3832        });
 3833        self.insert_with_autoindent_mode(text, autoindent, window, cx);
 3834    }
 3835
 3836    fn insert_with_autoindent_mode(
 3837        &mut self,
 3838        text: &str,
 3839        autoindent_mode: Option<AutoindentMode>,
 3840        window: &mut Window,
 3841        cx: &mut Context<Self>,
 3842    ) {
 3843        if self.read_only(cx) {
 3844            return;
 3845        }
 3846
 3847        let text: Arc<str> = text.into();
 3848        self.transact(window, cx, |this, window, cx| {
 3849            let old_selections = this.selections.all_adjusted(cx);
 3850            let selection_anchors = this.buffer.update(cx, |buffer, cx| {
 3851                let anchors = {
 3852                    let snapshot = buffer.read(cx);
 3853                    old_selections
 3854                        .iter()
 3855                        .map(|s| {
 3856                            let anchor = snapshot.anchor_after(s.head());
 3857                            s.map(|_| anchor)
 3858                        })
 3859                        .collect::<Vec<_>>()
 3860                };
 3861                buffer.edit(
 3862                    old_selections
 3863                        .iter()
 3864                        .map(|s| (s.start..s.end, text.clone())),
 3865                    autoindent_mode,
 3866                    cx,
 3867                );
 3868                anchors
 3869            });
 3870
 3871            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 3872                s.select_anchors(selection_anchors);
 3873            });
 3874
 3875            cx.notify();
 3876        });
 3877    }
 3878
 3879    fn trigger_completion_on_input(
 3880        &mut self,
 3881        text: &str,
 3882        trigger_in_words: bool,
 3883        window: &mut Window,
 3884        cx: &mut Context<Self>,
 3885    ) {
 3886        let ignore_completion_provider = self
 3887            .context_menu
 3888            .borrow()
 3889            .as_ref()
 3890            .map(|menu| match menu {
 3891                CodeContextMenu::Completions(completions_menu) => {
 3892                    completions_menu.ignore_completion_provider
 3893                }
 3894                CodeContextMenu::CodeActions(_) => false,
 3895            })
 3896            .unwrap_or(false);
 3897
 3898        if ignore_completion_provider {
 3899            self.show_word_completions(&ShowWordCompletions, window, cx);
 3900        } else if self.is_completion_trigger(text, trigger_in_words, cx) {
 3901            self.show_completions(
 3902                &ShowCompletions {
 3903                    trigger: Some(text.to_owned()).filter(|x| !x.is_empty()),
 3904                },
 3905                window,
 3906                cx,
 3907            );
 3908        } else {
 3909            self.hide_context_menu(window, cx);
 3910        }
 3911    }
 3912
 3913    fn is_completion_trigger(
 3914        &self,
 3915        text: &str,
 3916        trigger_in_words: bool,
 3917        cx: &mut Context<Self>,
 3918    ) -> bool {
 3919        let position = self.selections.newest_anchor().head();
 3920        let multibuffer = self.buffer.read(cx);
 3921        let Some(buffer) = position
 3922            .buffer_id
 3923            .and_then(|buffer_id| multibuffer.buffer(buffer_id).clone())
 3924        else {
 3925            return false;
 3926        };
 3927
 3928        if let Some(completion_provider) = &self.completion_provider {
 3929            completion_provider.is_completion_trigger(
 3930                &buffer,
 3931                position.text_anchor,
 3932                text,
 3933                trigger_in_words,
 3934                cx,
 3935            )
 3936        } else {
 3937            false
 3938        }
 3939    }
 3940
 3941    /// If any empty selections is touching the start of its innermost containing autoclose
 3942    /// region, expand it to select the brackets.
 3943    fn select_autoclose_pair(&mut self, window: &mut Window, cx: &mut Context<Self>) {
 3944        let selections = self.selections.all::<usize>(cx);
 3945        let buffer = self.buffer.read(cx).read(cx);
 3946        let new_selections = self
 3947            .selections_with_autoclose_regions(selections, &buffer)
 3948            .map(|(mut selection, region)| {
 3949                if !selection.is_empty() {
 3950                    return selection;
 3951                }
 3952
 3953                if let Some(region) = region {
 3954                    let mut range = region.range.to_offset(&buffer);
 3955                    if selection.start == range.start && range.start >= region.pair.start.len() {
 3956                        range.start -= region.pair.start.len();
 3957                        if buffer.contains_str_at(range.start, &region.pair.start)
 3958                            && buffer.contains_str_at(range.end, &region.pair.end)
 3959                        {
 3960                            range.end += region.pair.end.len();
 3961                            selection.start = range.start;
 3962                            selection.end = range.end;
 3963
 3964                            return selection;
 3965                        }
 3966                    }
 3967                }
 3968
 3969                let always_treat_brackets_as_autoclosed = buffer
 3970                    .language_settings_at(selection.start, cx)
 3971                    .always_treat_brackets_as_autoclosed;
 3972
 3973                if !always_treat_brackets_as_autoclosed {
 3974                    return selection;
 3975                }
 3976
 3977                if let Some(scope) = buffer.language_scope_at(selection.start) {
 3978                    for (pair, enabled) in scope.brackets() {
 3979                        if !enabled || !pair.close {
 3980                            continue;
 3981                        }
 3982
 3983                        if buffer.contains_str_at(selection.start, &pair.end) {
 3984                            let pair_start_len = pair.start.len();
 3985                            if buffer.contains_str_at(
 3986                                selection.start.saturating_sub(pair_start_len),
 3987                                &pair.start,
 3988                            ) {
 3989                                selection.start -= pair_start_len;
 3990                                selection.end += pair.end.len();
 3991
 3992                                return selection;
 3993                            }
 3994                        }
 3995                    }
 3996                }
 3997
 3998                selection
 3999            })
 4000            .collect();
 4001
 4002        drop(buffer);
 4003        self.change_selections(None, window, cx, |selections| {
 4004            selections.select(new_selections)
 4005        });
 4006    }
 4007
 4008    /// Iterate the given selections, and for each one, find the smallest surrounding
 4009    /// autoclose region. This uses the ordering of the selections and the autoclose
 4010    /// regions to avoid repeated comparisons.
 4011    fn selections_with_autoclose_regions<'a, D: ToOffset + Clone>(
 4012        &'a self,
 4013        selections: impl IntoIterator<Item = Selection<D>>,
 4014        buffer: &'a MultiBufferSnapshot,
 4015    ) -> impl Iterator<Item = (Selection<D>, Option<&'a AutocloseRegion>)> {
 4016        let mut i = 0;
 4017        let mut regions = self.autoclose_regions.as_slice();
 4018        selections.into_iter().map(move |selection| {
 4019            let range = selection.start.to_offset(buffer)..selection.end.to_offset(buffer);
 4020
 4021            let mut enclosing = None;
 4022            while let Some(pair_state) = regions.get(i) {
 4023                if pair_state.range.end.to_offset(buffer) < range.start {
 4024                    regions = &regions[i + 1..];
 4025                    i = 0;
 4026                } else if pair_state.range.start.to_offset(buffer) > range.end {
 4027                    break;
 4028                } else {
 4029                    if pair_state.selection_id == selection.id {
 4030                        enclosing = Some(pair_state);
 4031                    }
 4032                    i += 1;
 4033                }
 4034            }
 4035
 4036            (selection, enclosing)
 4037        })
 4038    }
 4039
 4040    /// Remove any autoclose regions that no longer contain their selection.
 4041    fn invalidate_autoclose_regions(
 4042        &mut self,
 4043        mut selections: &[Selection<Anchor>],
 4044        buffer: &MultiBufferSnapshot,
 4045    ) {
 4046        self.autoclose_regions.retain(|state| {
 4047            let mut i = 0;
 4048            while let Some(selection) = selections.get(i) {
 4049                if selection.end.cmp(&state.range.start, buffer).is_lt() {
 4050                    selections = &selections[1..];
 4051                    continue;
 4052                }
 4053                if selection.start.cmp(&state.range.end, buffer).is_gt() {
 4054                    break;
 4055                }
 4056                if selection.id == state.selection_id {
 4057                    return true;
 4058                } else {
 4059                    i += 1;
 4060                }
 4061            }
 4062            false
 4063        });
 4064    }
 4065
 4066    fn completion_query(buffer: &MultiBufferSnapshot, position: impl ToOffset) -> Option<String> {
 4067        let offset = position.to_offset(buffer);
 4068        let (word_range, kind) = buffer.surrounding_word(offset, true);
 4069        if offset > word_range.start && kind == Some(CharKind::Word) {
 4070            Some(
 4071                buffer
 4072                    .text_for_range(word_range.start..offset)
 4073                    .collect::<String>(),
 4074            )
 4075        } else {
 4076            None
 4077        }
 4078    }
 4079
 4080    pub fn toggle_inlay_hints(
 4081        &mut self,
 4082        _: &ToggleInlayHints,
 4083        _: &mut Window,
 4084        cx: &mut Context<Self>,
 4085    ) {
 4086        self.refresh_inlay_hints(
 4087            InlayHintRefreshReason::Toggle(!self.inlay_hints_enabled()),
 4088            cx,
 4089        );
 4090    }
 4091
 4092    pub fn inlay_hints_enabled(&self) -> bool {
 4093        self.inlay_hint_cache.enabled
 4094    }
 4095
 4096    fn refresh_inlay_hints(&mut self, reason: InlayHintRefreshReason, cx: &mut Context<Self>) {
 4097        if self.semantics_provider.is_none() || !self.mode.is_full() {
 4098            return;
 4099        }
 4100
 4101        let reason_description = reason.description();
 4102        let ignore_debounce = matches!(
 4103            reason,
 4104            InlayHintRefreshReason::SettingsChange(_)
 4105                | InlayHintRefreshReason::Toggle(_)
 4106                | InlayHintRefreshReason::ExcerptsRemoved(_)
 4107                | InlayHintRefreshReason::ModifiersChanged(_)
 4108        );
 4109        let (invalidate_cache, required_languages) = match reason {
 4110            InlayHintRefreshReason::ModifiersChanged(enabled) => {
 4111                match self.inlay_hint_cache.modifiers_override(enabled) {
 4112                    Some(enabled) => {
 4113                        if enabled {
 4114                            (InvalidationStrategy::RefreshRequested, None)
 4115                        } else {
 4116                            self.splice_inlays(
 4117                                &self
 4118                                    .visible_inlay_hints(cx)
 4119                                    .iter()
 4120                                    .map(|inlay| inlay.id)
 4121                                    .collect::<Vec<InlayId>>(),
 4122                                Vec::new(),
 4123                                cx,
 4124                            );
 4125                            return;
 4126                        }
 4127                    }
 4128                    None => return,
 4129                }
 4130            }
 4131            InlayHintRefreshReason::Toggle(enabled) => {
 4132                if self.inlay_hint_cache.toggle(enabled) {
 4133                    if enabled {
 4134                        (InvalidationStrategy::RefreshRequested, None)
 4135                    } else {
 4136                        self.splice_inlays(
 4137                            &self
 4138                                .visible_inlay_hints(cx)
 4139                                .iter()
 4140                                .map(|inlay| inlay.id)
 4141                                .collect::<Vec<InlayId>>(),
 4142                            Vec::new(),
 4143                            cx,
 4144                        );
 4145                        return;
 4146                    }
 4147                } else {
 4148                    return;
 4149                }
 4150            }
 4151            InlayHintRefreshReason::SettingsChange(new_settings) => {
 4152                match self.inlay_hint_cache.update_settings(
 4153                    &self.buffer,
 4154                    new_settings,
 4155                    self.visible_inlay_hints(cx),
 4156                    cx,
 4157                ) {
 4158                    ControlFlow::Break(Some(InlaySplice {
 4159                        to_remove,
 4160                        to_insert,
 4161                    })) => {
 4162                        self.splice_inlays(&to_remove, to_insert, cx);
 4163                        return;
 4164                    }
 4165                    ControlFlow::Break(None) => return,
 4166                    ControlFlow::Continue(()) => (InvalidationStrategy::RefreshRequested, None),
 4167                }
 4168            }
 4169            InlayHintRefreshReason::ExcerptsRemoved(excerpts_removed) => {
 4170                if let Some(InlaySplice {
 4171                    to_remove,
 4172                    to_insert,
 4173                }) = self.inlay_hint_cache.remove_excerpts(&excerpts_removed)
 4174                {
 4175                    self.splice_inlays(&to_remove, to_insert, cx);
 4176                }
 4177                self.display_map.update(cx, |display_map, _| {
 4178                    display_map.remove_inlays_for_excerpts(&excerpts_removed)
 4179                });
 4180                return;
 4181            }
 4182            InlayHintRefreshReason::NewLinesShown => (InvalidationStrategy::None, None),
 4183            InlayHintRefreshReason::BufferEdited(buffer_languages) => {
 4184                (InvalidationStrategy::BufferEdited, Some(buffer_languages))
 4185            }
 4186            InlayHintRefreshReason::RefreshRequested => {
 4187                (InvalidationStrategy::RefreshRequested, None)
 4188            }
 4189        };
 4190
 4191        if let Some(InlaySplice {
 4192            to_remove,
 4193            to_insert,
 4194        }) = self.inlay_hint_cache.spawn_hint_refresh(
 4195            reason_description,
 4196            self.excerpts_for_inlay_hints_query(required_languages.as_ref(), cx),
 4197            invalidate_cache,
 4198            ignore_debounce,
 4199            cx,
 4200        ) {
 4201            self.splice_inlays(&to_remove, to_insert, cx);
 4202        }
 4203    }
 4204
 4205    fn visible_inlay_hints(&self, cx: &Context<Editor>) -> Vec<Inlay> {
 4206        self.display_map
 4207            .read(cx)
 4208            .current_inlays()
 4209            .filter(move |inlay| matches!(inlay.id, InlayId::Hint(_)))
 4210            .cloned()
 4211            .collect()
 4212    }
 4213
 4214    pub fn excerpts_for_inlay_hints_query(
 4215        &self,
 4216        restrict_to_languages: Option<&HashSet<Arc<Language>>>,
 4217        cx: &mut Context<Editor>,
 4218    ) -> HashMap<ExcerptId, (Entity<Buffer>, clock::Global, Range<usize>)> {
 4219        let Some(project) = self.project.as_ref() else {
 4220            return HashMap::default();
 4221        };
 4222        let project = project.read(cx);
 4223        let multi_buffer = self.buffer().read(cx);
 4224        let multi_buffer_snapshot = multi_buffer.snapshot(cx);
 4225        let multi_buffer_visible_start = self
 4226            .scroll_manager
 4227            .anchor()
 4228            .anchor
 4229            .to_point(&multi_buffer_snapshot);
 4230        let multi_buffer_visible_end = multi_buffer_snapshot.clip_point(
 4231            multi_buffer_visible_start
 4232                + Point::new(self.visible_line_count().unwrap_or(0.).ceil() as u32, 0),
 4233            Bias::Left,
 4234        );
 4235        let multi_buffer_visible_range = multi_buffer_visible_start..multi_buffer_visible_end;
 4236        multi_buffer_snapshot
 4237            .range_to_buffer_ranges(multi_buffer_visible_range)
 4238            .into_iter()
 4239            .filter(|(_, excerpt_visible_range, _)| !excerpt_visible_range.is_empty())
 4240            .filter_map(|(buffer, excerpt_visible_range, excerpt_id)| {
 4241                let buffer_file = project::File::from_dyn(buffer.file())?;
 4242                let buffer_worktree = project.worktree_for_id(buffer_file.worktree_id(cx), cx)?;
 4243                let worktree_entry = buffer_worktree
 4244                    .read(cx)
 4245                    .entry_for_id(buffer_file.project_entry_id(cx)?)?;
 4246                if worktree_entry.is_ignored {
 4247                    return None;
 4248                }
 4249
 4250                let language = buffer.language()?;
 4251                if let Some(restrict_to_languages) = restrict_to_languages {
 4252                    if !restrict_to_languages.contains(language) {
 4253                        return None;
 4254                    }
 4255                }
 4256                Some((
 4257                    excerpt_id,
 4258                    (
 4259                        multi_buffer.buffer(buffer.remote_id()).unwrap(),
 4260                        buffer.version().clone(),
 4261                        excerpt_visible_range,
 4262                    ),
 4263                ))
 4264            })
 4265            .collect()
 4266    }
 4267
 4268    pub fn text_layout_details(&self, window: &mut Window) -> TextLayoutDetails {
 4269        TextLayoutDetails {
 4270            text_system: window.text_system().clone(),
 4271            editor_style: self.style.clone().unwrap(),
 4272            rem_size: window.rem_size(),
 4273            scroll_anchor: self.scroll_manager.anchor(),
 4274            visible_rows: self.visible_line_count(),
 4275            vertical_scroll_margin: self.scroll_manager.vertical_scroll_margin,
 4276        }
 4277    }
 4278
 4279    pub fn splice_inlays(
 4280        &self,
 4281        to_remove: &[InlayId],
 4282        to_insert: Vec<Inlay>,
 4283        cx: &mut Context<Self>,
 4284    ) {
 4285        self.display_map.update(cx, |display_map, cx| {
 4286            display_map.splice_inlays(to_remove, to_insert, cx)
 4287        });
 4288        cx.notify();
 4289    }
 4290
 4291    fn trigger_on_type_formatting(
 4292        &self,
 4293        input: String,
 4294        window: &mut Window,
 4295        cx: &mut Context<Self>,
 4296    ) -> Option<Task<Result<()>>> {
 4297        if input.len() != 1 {
 4298            return None;
 4299        }
 4300
 4301        let project = self.project.as_ref()?;
 4302        let position = self.selections.newest_anchor().head();
 4303        let (buffer, buffer_position) = self
 4304            .buffer
 4305            .read(cx)
 4306            .text_anchor_for_position(position, cx)?;
 4307
 4308        let settings = language_settings::language_settings(
 4309            buffer
 4310                .read(cx)
 4311                .language_at(buffer_position)
 4312                .map(|l| l.name()),
 4313            buffer.read(cx).file(),
 4314            cx,
 4315        );
 4316        if !settings.use_on_type_format {
 4317            return None;
 4318        }
 4319
 4320        // OnTypeFormatting returns a list of edits, no need to pass them between Zed instances,
 4321        // hence we do LSP request & edit on host side only — add formats to host's history.
 4322        let push_to_lsp_host_history = true;
 4323        // If this is not the host, append its history with new edits.
 4324        let push_to_client_history = project.read(cx).is_via_collab();
 4325
 4326        let on_type_formatting = project.update(cx, |project, cx| {
 4327            project.on_type_format(
 4328                buffer.clone(),
 4329                buffer_position,
 4330                input,
 4331                push_to_lsp_host_history,
 4332                cx,
 4333            )
 4334        });
 4335        Some(cx.spawn_in(window, async move |editor, cx| {
 4336            if let Some(transaction) = on_type_formatting.await? {
 4337                if push_to_client_history {
 4338                    buffer
 4339                        .update(cx, |buffer, _| {
 4340                            buffer.push_transaction(transaction, Instant::now());
 4341                            buffer.finalize_last_transaction();
 4342                        })
 4343                        .ok();
 4344                }
 4345                editor.update(cx, |editor, cx| {
 4346                    editor.refresh_document_highlights(cx);
 4347                })?;
 4348            }
 4349            Ok(())
 4350        }))
 4351    }
 4352
 4353    pub fn show_word_completions(
 4354        &mut self,
 4355        _: &ShowWordCompletions,
 4356        window: &mut Window,
 4357        cx: &mut Context<Self>,
 4358    ) {
 4359        self.open_completions_menu(true, None, window, cx);
 4360    }
 4361
 4362    pub fn show_completions(
 4363        &mut self,
 4364        options: &ShowCompletions,
 4365        window: &mut Window,
 4366        cx: &mut Context<Self>,
 4367    ) {
 4368        self.open_completions_menu(false, options.trigger.as_deref(), window, cx);
 4369    }
 4370
 4371    fn open_completions_menu(
 4372        &mut self,
 4373        ignore_completion_provider: bool,
 4374        trigger: Option<&str>,
 4375        window: &mut Window,
 4376        cx: &mut Context<Self>,
 4377    ) {
 4378        if self.pending_rename.is_some() {
 4379            return;
 4380        }
 4381        if !self.snippet_stack.is_empty() && self.context_menu.borrow().as_ref().is_some() {
 4382            return;
 4383        }
 4384
 4385        let position = self.selections.newest_anchor().head();
 4386        if position.diff_base_anchor.is_some() {
 4387            return;
 4388        }
 4389        let (buffer, buffer_position) =
 4390            if let Some(output) = self.buffer.read(cx).text_anchor_for_position(position, cx) {
 4391                output
 4392            } else {
 4393                return;
 4394            };
 4395        let buffer_snapshot = buffer.read(cx).snapshot();
 4396        let show_completion_documentation = buffer_snapshot
 4397            .settings_at(buffer_position, cx)
 4398            .show_completion_documentation;
 4399
 4400        let query = Self::completion_query(&self.buffer.read(cx).read(cx), position);
 4401
 4402        let trigger_kind = match trigger {
 4403            Some(trigger) if buffer.read(cx).completion_triggers().contains(trigger) => {
 4404                CompletionTriggerKind::TRIGGER_CHARACTER
 4405            }
 4406            _ => CompletionTriggerKind::INVOKED,
 4407        };
 4408        let completion_context = CompletionContext {
 4409            trigger_character: trigger.and_then(|trigger| {
 4410                if trigger_kind == CompletionTriggerKind::TRIGGER_CHARACTER {
 4411                    Some(String::from(trigger))
 4412                } else {
 4413                    None
 4414                }
 4415            }),
 4416            trigger_kind,
 4417        };
 4418
 4419        let (old_range, word_kind) = buffer_snapshot.surrounding_word(buffer_position);
 4420        let (old_range, word_to_exclude) = if word_kind == Some(CharKind::Word) {
 4421            let word_to_exclude = buffer_snapshot
 4422                .text_for_range(old_range.clone())
 4423                .collect::<String>();
 4424            (
 4425                buffer_snapshot.anchor_before(old_range.start)
 4426                    ..buffer_snapshot.anchor_after(old_range.end),
 4427                Some(word_to_exclude),
 4428            )
 4429        } else {
 4430            (buffer_position..buffer_position, None)
 4431        };
 4432
 4433        let completion_settings = language_settings(
 4434            buffer_snapshot
 4435                .language_at(buffer_position)
 4436                .map(|language| language.name()),
 4437            buffer_snapshot.file(),
 4438            cx,
 4439        )
 4440        .completions;
 4441
 4442        // The document can be large, so stay in reasonable bounds when searching for words,
 4443        // otherwise completion pop-up might be slow to appear.
 4444        const WORD_LOOKUP_ROWS: u32 = 5_000;
 4445        let buffer_row = text::ToPoint::to_point(&buffer_position, &buffer_snapshot).row;
 4446        let min_word_search = buffer_snapshot.clip_point(
 4447            Point::new(buffer_row.saturating_sub(WORD_LOOKUP_ROWS), 0),
 4448            Bias::Left,
 4449        );
 4450        let max_word_search = buffer_snapshot.clip_point(
 4451            Point::new(buffer_row + WORD_LOOKUP_ROWS, 0).min(buffer_snapshot.max_point()),
 4452            Bias::Right,
 4453        );
 4454        let word_search_range = buffer_snapshot.point_to_offset(min_word_search)
 4455            ..buffer_snapshot.point_to_offset(max_word_search);
 4456
 4457        let provider = self
 4458            .completion_provider
 4459            .as_ref()
 4460            .filter(|_| !ignore_completion_provider);
 4461        let skip_digits = query
 4462            .as_ref()
 4463            .map_or(true, |query| !query.chars().any(|c| c.is_digit(10)));
 4464
 4465        let (mut words, provided_completions) = match provider {
 4466            Some(provider) => {
 4467                let completions = provider.completions(
 4468                    position.excerpt_id,
 4469                    &buffer,
 4470                    buffer_position,
 4471                    completion_context,
 4472                    window,
 4473                    cx,
 4474                );
 4475
 4476                let words = match completion_settings.words {
 4477                    WordsCompletionMode::Disabled => Task::ready(BTreeMap::default()),
 4478                    WordsCompletionMode::Enabled | WordsCompletionMode::Fallback => cx
 4479                        .background_spawn(async move {
 4480                            buffer_snapshot.words_in_range(WordsQuery {
 4481                                fuzzy_contents: None,
 4482                                range: word_search_range,
 4483                                skip_digits,
 4484                            })
 4485                        }),
 4486                };
 4487
 4488                (words, completions)
 4489            }
 4490            None => (
 4491                cx.background_spawn(async move {
 4492                    buffer_snapshot.words_in_range(WordsQuery {
 4493                        fuzzy_contents: None,
 4494                        range: word_search_range,
 4495                        skip_digits,
 4496                    })
 4497                }),
 4498                Task::ready(Ok(None)),
 4499            ),
 4500        };
 4501
 4502        let sort_completions = provider
 4503            .as_ref()
 4504            .map_or(false, |provider| provider.sort_completions());
 4505
 4506        let filter_completions = provider
 4507            .as_ref()
 4508            .map_or(true, |provider| provider.filter_completions());
 4509
 4510        let id = post_inc(&mut self.next_completion_id);
 4511        let task = cx.spawn_in(window, async move |editor, cx| {
 4512            async move {
 4513                editor.update(cx, |this, _| {
 4514                    this.completion_tasks.retain(|(task_id, _)| *task_id >= id);
 4515                })?;
 4516
 4517                let mut completions = Vec::new();
 4518                if let Some(provided_completions) = provided_completions.await.log_err().flatten() {
 4519                    completions.extend(provided_completions);
 4520                    if completion_settings.words == WordsCompletionMode::Fallback {
 4521                        words = Task::ready(BTreeMap::default());
 4522                    }
 4523                }
 4524
 4525                let mut words = words.await;
 4526                if let Some(word_to_exclude) = &word_to_exclude {
 4527                    words.remove(word_to_exclude);
 4528                }
 4529                for lsp_completion in &completions {
 4530                    words.remove(&lsp_completion.new_text);
 4531                }
 4532                completions.extend(words.into_iter().map(|(word, word_range)| Completion {
 4533                    replace_range: old_range.clone(),
 4534                    new_text: word.clone(),
 4535                    label: CodeLabel::plain(word, None),
 4536                    icon_path: None,
 4537                    documentation: None,
 4538                    source: CompletionSource::BufferWord {
 4539                        word_range,
 4540                        resolved: false,
 4541                    },
 4542                    insert_text_mode: Some(InsertTextMode::AS_IS),
 4543                    confirm: None,
 4544                }));
 4545
 4546                let menu = if completions.is_empty() {
 4547                    None
 4548                } else {
 4549                    let mut menu = CompletionsMenu::new(
 4550                        id,
 4551                        sort_completions,
 4552                        show_completion_documentation,
 4553                        ignore_completion_provider,
 4554                        position,
 4555                        buffer.clone(),
 4556                        completions.into(),
 4557                    );
 4558
 4559                    menu.filter(
 4560                        if filter_completions {
 4561                            query.as_deref()
 4562                        } else {
 4563                            None
 4564                        },
 4565                        cx.background_executor().clone(),
 4566                    )
 4567                    .await;
 4568
 4569                    menu.visible().then_some(menu)
 4570                };
 4571
 4572                editor.update_in(cx, |editor, window, cx| {
 4573                    match editor.context_menu.borrow().as_ref() {
 4574                        None => {}
 4575                        Some(CodeContextMenu::Completions(prev_menu)) => {
 4576                            if prev_menu.id > id {
 4577                                return;
 4578                            }
 4579                        }
 4580                        _ => return,
 4581                    }
 4582
 4583                    if editor.focus_handle.is_focused(window) && menu.is_some() {
 4584                        let mut menu = menu.unwrap();
 4585                        menu.resolve_visible_completions(editor.completion_provider.as_deref(), cx);
 4586
 4587                        *editor.context_menu.borrow_mut() =
 4588                            Some(CodeContextMenu::Completions(menu));
 4589
 4590                        if editor.show_edit_predictions_in_menu() {
 4591                            editor.update_visible_inline_completion(window, cx);
 4592                        } else {
 4593                            editor.discard_inline_completion(false, cx);
 4594                        }
 4595
 4596                        cx.notify();
 4597                    } else if editor.completion_tasks.len() <= 1 {
 4598                        // If there are no more completion tasks and the last menu was
 4599                        // empty, we should hide it.
 4600                        let was_hidden = editor.hide_context_menu(window, cx).is_none();
 4601                        // If it was already hidden and we don't show inline
 4602                        // completions in the menu, we should also show the
 4603                        // inline-completion when available.
 4604                        if was_hidden && editor.show_edit_predictions_in_menu() {
 4605                            editor.update_visible_inline_completion(window, cx);
 4606                        }
 4607                    }
 4608                })?;
 4609
 4610                anyhow::Ok(())
 4611            }
 4612            .log_err()
 4613            .await
 4614        });
 4615
 4616        self.completion_tasks.push((id, task));
 4617    }
 4618
 4619    #[cfg(feature = "test-support")]
 4620    pub fn current_completions(&self) -> Option<Vec<project::Completion>> {
 4621        let menu = self.context_menu.borrow();
 4622        if let CodeContextMenu::Completions(menu) = menu.as_ref()? {
 4623            let completions = menu.completions.borrow();
 4624            Some(completions.to_vec())
 4625        } else {
 4626            None
 4627        }
 4628    }
 4629
 4630    pub fn confirm_completion(
 4631        &mut self,
 4632        action: &ConfirmCompletion,
 4633        window: &mut Window,
 4634        cx: &mut Context<Self>,
 4635    ) -> Option<Task<Result<()>>> {
 4636        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
 4637        self.do_completion(action.item_ix, CompletionIntent::Complete, window, cx)
 4638    }
 4639
 4640    pub fn confirm_completion_insert(
 4641        &mut self,
 4642        _: &ConfirmCompletionInsert,
 4643        window: &mut Window,
 4644        cx: &mut Context<Self>,
 4645    ) -> Option<Task<Result<()>>> {
 4646        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
 4647        self.do_completion(None, CompletionIntent::CompleteWithInsert, window, cx)
 4648    }
 4649
 4650    pub fn confirm_completion_replace(
 4651        &mut self,
 4652        _: &ConfirmCompletionReplace,
 4653        window: &mut Window,
 4654        cx: &mut Context<Self>,
 4655    ) -> Option<Task<Result<()>>> {
 4656        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
 4657        self.do_completion(None, CompletionIntent::CompleteWithReplace, window, cx)
 4658    }
 4659
 4660    pub fn compose_completion(
 4661        &mut self,
 4662        action: &ComposeCompletion,
 4663        window: &mut Window,
 4664        cx: &mut Context<Self>,
 4665    ) -> Option<Task<Result<()>>> {
 4666        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
 4667        self.do_completion(action.item_ix, CompletionIntent::Compose, window, cx)
 4668    }
 4669
 4670    fn do_completion(
 4671        &mut self,
 4672        item_ix: Option<usize>,
 4673        intent: CompletionIntent,
 4674        window: &mut Window,
 4675        cx: &mut Context<Editor>,
 4676    ) -> Option<Task<Result<()>>> {
 4677        use language::ToOffset as _;
 4678
 4679        let CodeContextMenu::Completions(completions_menu) = self.hide_context_menu(window, cx)?
 4680        else {
 4681            return None;
 4682        };
 4683
 4684        let candidate_id = {
 4685            let entries = completions_menu.entries.borrow();
 4686            let mat = entries.get(item_ix.unwrap_or(completions_menu.selected_item))?;
 4687            if self.show_edit_predictions_in_menu() {
 4688                self.discard_inline_completion(true, cx);
 4689            }
 4690            mat.candidate_id
 4691        };
 4692
 4693        let buffer_handle = completions_menu.buffer;
 4694        let completion = completions_menu
 4695            .completions
 4696            .borrow()
 4697            .get(candidate_id)?
 4698            .clone();
 4699        cx.stop_propagation();
 4700
 4701        let snippet;
 4702        let new_text;
 4703        if completion.is_snippet() {
 4704            snippet = Some(Snippet::parse(&completion.new_text).log_err()?);
 4705            new_text = snippet.as_ref().unwrap().text.clone();
 4706        } else {
 4707            snippet = None;
 4708            new_text = completion.new_text.clone();
 4709        };
 4710
 4711        let replace_range = choose_completion_range(&completion, intent, &buffer_handle, cx);
 4712        let buffer = buffer_handle.read(cx);
 4713        let snapshot = self.buffer.read(cx).snapshot(cx);
 4714        let replace_range_multibuffer = {
 4715            let excerpt = snapshot
 4716                .excerpt_containing(self.selections.newest_anchor().range())
 4717                .unwrap();
 4718            let multibuffer_anchor = snapshot
 4719                .anchor_in_excerpt(excerpt.id(), buffer.anchor_before(replace_range.start))
 4720                .unwrap()
 4721                ..snapshot
 4722                    .anchor_in_excerpt(excerpt.id(), buffer.anchor_before(replace_range.end))
 4723                    .unwrap();
 4724            multibuffer_anchor.start.to_offset(&snapshot)
 4725                ..multibuffer_anchor.end.to_offset(&snapshot)
 4726        };
 4727        let newest_anchor = self.selections.newest_anchor();
 4728        if newest_anchor.head().buffer_id != Some(buffer.remote_id()) {
 4729            return None;
 4730        }
 4731
 4732        let old_text = buffer
 4733            .text_for_range(replace_range.clone())
 4734            .collect::<String>();
 4735        let lookbehind = newest_anchor
 4736            .start
 4737            .text_anchor
 4738            .to_offset(buffer)
 4739            .saturating_sub(replace_range.start);
 4740        let lookahead = replace_range
 4741            .end
 4742            .saturating_sub(newest_anchor.end.text_anchor.to_offset(buffer));
 4743        let prefix = &old_text[..old_text.len().saturating_sub(lookahead)];
 4744        let suffix = &old_text[lookbehind.min(old_text.len())..];
 4745
 4746        let selections = self.selections.all::<usize>(cx);
 4747        let mut ranges = Vec::new();
 4748        let mut linked_edits = HashMap::<_, Vec<_>>::default();
 4749
 4750        for selection in &selections {
 4751            let range = if selection.id == newest_anchor.id {
 4752                replace_range_multibuffer.clone()
 4753            } else {
 4754                let mut range = selection.range();
 4755
 4756                // if prefix is present, don't duplicate it
 4757                if snapshot.contains_str_at(range.start.saturating_sub(lookbehind), prefix) {
 4758                    range.start = range.start.saturating_sub(lookbehind);
 4759
 4760                    // if suffix is also present, mimic the newest cursor and replace it
 4761                    if selection.id != newest_anchor.id
 4762                        && snapshot.contains_str_at(range.end, suffix)
 4763                    {
 4764                        range.end += lookahead;
 4765                    }
 4766                }
 4767                range
 4768            };
 4769
 4770            ranges.push(range);
 4771
 4772            if !self.linked_edit_ranges.is_empty() {
 4773                let start_anchor = snapshot.anchor_before(selection.head());
 4774                let end_anchor = snapshot.anchor_after(selection.tail());
 4775                if let Some(ranges) = self
 4776                    .linked_editing_ranges_for(start_anchor.text_anchor..end_anchor.text_anchor, cx)
 4777                {
 4778                    for (buffer, edits) in ranges {
 4779                        linked_edits
 4780                            .entry(buffer.clone())
 4781                            .or_default()
 4782                            .extend(edits.into_iter().map(|range| (range, new_text.to_owned())));
 4783                    }
 4784                }
 4785            }
 4786        }
 4787
 4788        cx.emit(EditorEvent::InputHandled {
 4789            utf16_range_to_replace: None,
 4790            text: new_text.clone().into(),
 4791        });
 4792
 4793        self.transact(window, cx, |this, window, cx| {
 4794            if let Some(mut snippet) = snippet {
 4795                snippet.text = new_text.to_string();
 4796                this.insert_snippet(&ranges, snippet, window, cx).log_err();
 4797            } else {
 4798                this.buffer.update(cx, |buffer, cx| {
 4799                    let auto_indent = match completion.insert_text_mode {
 4800                        Some(InsertTextMode::AS_IS) => None,
 4801                        _ => this.autoindent_mode.clone(),
 4802                    };
 4803                    let edits = ranges.into_iter().map(|range| (range, new_text.as_str()));
 4804                    buffer.edit(edits, auto_indent, cx);
 4805                });
 4806            }
 4807            for (buffer, edits) in linked_edits {
 4808                buffer.update(cx, |buffer, cx| {
 4809                    let snapshot = buffer.snapshot();
 4810                    let edits = edits
 4811                        .into_iter()
 4812                        .map(|(range, text)| {
 4813                            use text::ToPoint as TP;
 4814                            let end_point = TP::to_point(&range.end, &snapshot);
 4815                            let start_point = TP::to_point(&range.start, &snapshot);
 4816                            (start_point..end_point, text)
 4817                        })
 4818                        .sorted_by_key(|(range, _)| range.start);
 4819                    buffer.edit(edits, None, cx);
 4820                })
 4821            }
 4822
 4823            this.refresh_inline_completion(true, false, window, cx);
 4824        });
 4825
 4826        let show_new_completions_on_confirm = completion
 4827            .confirm
 4828            .as_ref()
 4829            .map_or(false, |confirm| confirm(intent, window, cx));
 4830        if show_new_completions_on_confirm {
 4831            self.show_completions(&ShowCompletions { trigger: None }, window, cx);
 4832        }
 4833
 4834        let provider = self.completion_provider.as_ref()?;
 4835        drop(completion);
 4836        let apply_edits = provider.apply_additional_edits_for_completion(
 4837            buffer_handle,
 4838            completions_menu.completions.clone(),
 4839            candidate_id,
 4840            true,
 4841            cx,
 4842        );
 4843
 4844        let editor_settings = EditorSettings::get_global(cx);
 4845        if editor_settings.show_signature_help_after_edits || editor_settings.auto_signature_help {
 4846            // After the code completion is finished, users often want to know what signatures are needed.
 4847            // so we should automatically call signature_help
 4848            self.show_signature_help(&ShowSignatureHelp, window, cx);
 4849        }
 4850
 4851        Some(cx.foreground_executor().spawn(async move {
 4852            apply_edits.await?;
 4853            Ok(())
 4854        }))
 4855    }
 4856
 4857    fn prepare_code_actions_task(
 4858        &mut self,
 4859        action: &ToggleCodeActions,
 4860        window: &mut Window,
 4861        cx: &mut Context<Self>,
 4862    ) -> Task<Option<(Entity<Buffer>, CodeActionContents)>> {
 4863        let snapshot = self.snapshot(window, cx);
 4864        let multibuffer_point = action
 4865            .deployed_from_indicator
 4866            .map(|row| DisplayPoint::new(row, 0).to_point(&snapshot))
 4867            .unwrap_or_else(|| self.selections.newest::<Point>(cx).head());
 4868
 4869        let Some((buffer, buffer_row)) = snapshot
 4870            .buffer_snapshot
 4871            .buffer_line_for_row(MultiBufferRow(multibuffer_point.row))
 4872            .and_then(|(buffer_snapshot, range)| {
 4873                self.buffer
 4874                    .read(cx)
 4875                    .buffer(buffer_snapshot.remote_id())
 4876                    .map(|buffer| (buffer, range.start.row))
 4877            })
 4878        else {
 4879            return Task::ready(None);
 4880        };
 4881
 4882        let (_, code_actions) = self
 4883            .available_code_actions
 4884            .clone()
 4885            .and_then(|(location, code_actions)| {
 4886                let snapshot = location.buffer.read(cx).snapshot();
 4887                let point_range = location.range.to_point(&snapshot);
 4888                let point_range = point_range.start.row..=point_range.end.row;
 4889                if point_range.contains(&buffer_row) {
 4890                    Some((location, code_actions))
 4891                } else {
 4892                    None
 4893                }
 4894            })
 4895            .unzip();
 4896
 4897        let buffer_id = buffer.read(cx).remote_id();
 4898        let tasks = self
 4899            .tasks
 4900            .get(&(buffer_id, buffer_row))
 4901            .map(|t| Arc::new(t.to_owned()));
 4902
 4903        if tasks.is_none() && code_actions.is_none() {
 4904            return Task::ready(None);
 4905        }
 4906
 4907        self.completion_tasks.clear();
 4908        self.discard_inline_completion(false, cx);
 4909
 4910        let task_context = tasks
 4911            .as_ref()
 4912            .zip(self.project.clone())
 4913            .map(|(tasks, project)| {
 4914                Self::build_tasks_context(&project, &buffer, buffer_row, tasks, cx)
 4915            });
 4916
 4917        cx.spawn_in(window, async move |_, _| {
 4918            let task_context = match task_context {
 4919                Some(task_context) => task_context.await,
 4920                None => None,
 4921            };
 4922            let resolved_tasks = tasks.zip(task_context).map(|(tasks, task_context)| {
 4923                Rc::new(ResolvedTasks {
 4924                    templates: tasks.resolve(&task_context).collect(),
 4925                    position: snapshot
 4926                        .buffer_snapshot
 4927                        .anchor_before(Point::new(multibuffer_point.row, tasks.column)),
 4928                })
 4929            });
 4930            Some((
 4931                buffer,
 4932                CodeActionContents {
 4933                    actions: code_actions,
 4934                    tasks: resolved_tasks,
 4935                },
 4936            ))
 4937        })
 4938    }
 4939
 4940    pub fn toggle_code_actions(
 4941        &mut self,
 4942        action: &ToggleCodeActions,
 4943        window: &mut Window,
 4944        cx: &mut Context<Self>,
 4945    ) {
 4946        let mut context_menu = self.context_menu.borrow_mut();
 4947        if let Some(CodeContextMenu::CodeActions(code_actions)) = context_menu.as_ref() {
 4948            if code_actions.deployed_from_indicator == action.deployed_from_indicator {
 4949                // Toggle if we're selecting the same one
 4950                *context_menu = None;
 4951                cx.notify();
 4952                return;
 4953            } else {
 4954                // Otherwise, clear it and start a new one
 4955                *context_menu = None;
 4956                cx.notify();
 4957            }
 4958        }
 4959        drop(context_menu);
 4960
 4961        let deployed_from_indicator = action.deployed_from_indicator;
 4962        let mut task = self.code_actions_task.take();
 4963        let action = action.clone();
 4964
 4965        cx.spawn_in(window, async move |editor, cx| {
 4966            while let Some(prev_task) = task {
 4967                prev_task.await.log_err();
 4968                task = editor.update(cx, |this, _| this.code_actions_task.take())?;
 4969            }
 4970
 4971            let context_menu_task = editor.update_in(cx, |editor, window, cx| {
 4972                if !editor.focus_handle.is_focused(window) {
 4973                    return Some(Task::ready(Ok(())));
 4974                }
 4975                let debugger_flag = cx.has_flag::<Debugger>();
 4976                let code_actions_task = editor.prepare_code_actions_task(&action, window, cx);
 4977                Some(cx.spawn_in(window, async move |editor, cx| {
 4978                    if let Some((buffer, code_action_contents)) = code_actions_task.await {
 4979                        let spawn_straight_away =
 4980                            code_action_contents.tasks.as_ref().map_or(false, |tasks| {
 4981                                tasks
 4982                                    .templates
 4983                                    .iter()
 4984                                    .filter(|task| {
 4985                                        if matches!(task.1.task_type(), task::TaskType::Debug(_)) {
 4986                                            debugger_flag
 4987                                        } else {
 4988                                            true
 4989                                        }
 4990                                    })
 4991                                    .count()
 4992                                    == 1
 4993                            }) && code_action_contents
 4994                                .actions
 4995                                .as_ref()
 4996                                .map_or(true, |actions| actions.is_empty());
 4997                        if let Ok(task) = editor.update_in(cx, |editor, window, cx| {
 4998                            *editor.context_menu.borrow_mut() =
 4999                                Some(CodeContextMenu::CodeActions(CodeActionsMenu {
 5000                                    buffer,
 5001                                    actions: code_action_contents,
 5002                                    selected_item: Default::default(),
 5003                                    scroll_handle: UniformListScrollHandle::default(),
 5004                                    deployed_from_indicator,
 5005                                }));
 5006                            if spawn_straight_away {
 5007                                if let Some(task) = editor.confirm_code_action(
 5008                                    &ConfirmCodeAction {
 5009                                        item_ix: Some(0),
 5010                                        from_mouse_context_menu: false,
 5011                                    },
 5012                                    window,
 5013                                    cx,
 5014                                ) {
 5015                                    cx.notify();
 5016                                    return task;
 5017                                }
 5018                            }
 5019                            cx.notify();
 5020                            Task::ready(Ok(()))
 5021                        }) {
 5022                            task.await
 5023                        } else {
 5024                            Ok(())
 5025                        }
 5026                    } else {
 5027                        Ok(())
 5028                    }
 5029                }))
 5030            })?;
 5031            if let Some(task) = context_menu_task {
 5032                task.await?;
 5033            }
 5034
 5035            Ok::<_, anyhow::Error>(())
 5036        })
 5037        .detach_and_log_err(cx);
 5038    }
 5039
 5040    pub fn confirm_code_action(
 5041        &mut self,
 5042        action: &ConfirmCodeAction,
 5043        window: &mut Window,
 5044        cx: &mut Context<Self>,
 5045    ) -> Option<Task<Result<()>>> {
 5046        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
 5047
 5048        let (action, buffer) = if action.from_mouse_context_menu {
 5049            if let Some(menu) = self.mouse_context_menu.take() {
 5050                let code_action = menu.code_action?;
 5051                let index = action.item_ix?;
 5052                let action = code_action.actions.get(index)?;
 5053                (action, code_action.buffer)
 5054            } else {
 5055                return None;
 5056            }
 5057        } else {
 5058            if let CodeContextMenu::CodeActions(menu) = self.hide_context_menu(window, cx)? {
 5059                let action_ix = action.item_ix.unwrap_or(menu.selected_item);
 5060                let action = menu.actions.get(action_ix)?;
 5061                let buffer = menu.buffer;
 5062                (action, buffer)
 5063            } else {
 5064                return None;
 5065            }
 5066        };
 5067
 5068        let title = action.label();
 5069        let workspace = self.workspace()?;
 5070
 5071        match action {
 5072            CodeActionsItem::Task(task_source_kind, resolved_task) => {
 5073                match resolved_task.task_type() {
 5074                    task::TaskType::Script => workspace.update(cx, |workspace, cx| {
 5075                        workspace::tasks::schedule_resolved_task(
 5076                            workspace,
 5077                            task_source_kind,
 5078                            resolved_task,
 5079                            false,
 5080                            cx,
 5081                        );
 5082
 5083                        Some(Task::ready(Ok(())))
 5084                    }),
 5085                    task::TaskType::Debug(debug_args) => {
 5086                        if debug_args.locator.is_some() {
 5087                            workspace.update(cx, |workspace, cx| {
 5088                                workspace::tasks::schedule_resolved_task(
 5089                                    workspace,
 5090                                    task_source_kind,
 5091                                    resolved_task,
 5092                                    false,
 5093                                    cx,
 5094                                );
 5095                            });
 5096
 5097                            return Some(Task::ready(Ok(())));
 5098                        }
 5099
 5100                        if let Some(project) = self.project.as_ref() {
 5101                            project
 5102                                .update(cx, |project, cx| {
 5103                                    project.start_debug_session(
 5104                                        resolved_task.resolved_debug_adapter_config().unwrap(),
 5105                                        cx,
 5106                                    )
 5107                                })
 5108                                .detach_and_log_err(cx);
 5109                            Some(Task::ready(Ok(())))
 5110                        } else {
 5111                            Some(Task::ready(Ok(())))
 5112                        }
 5113                    }
 5114                }
 5115            }
 5116            CodeActionsItem::CodeAction {
 5117                excerpt_id,
 5118                action,
 5119                provider,
 5120            } => {
 5121                let apply_code_action =
 5122                    provider.apply_code_action(buffer, action, excerpt_id, true, window, cx);
 5123                let workspace = workspace.downgrade();
 5124                Some(cx.spawn_in(window, async move |editor, cx| {
 5125                    let project_transaction = apply_code_action.await?;
 5126                    Self::open_project_transaction(
 5127                        &editor,
 5128                        workspace,
 5129                        project_transaction,
 5130                        title,
 5131                        cx,
 5132                    )
 5133                    .await
 5134                }))
 5135            }
 5136        }
 5137    }
 5138
 5139    pub async fn open_project_transaction(
 5140        this: &WeakEntity<Editor>,
 5141        workspace: WeakEntity<Workspace>,
 5142        transaction: ProjectTransaction,
 5143        title: String,
 5144        cx: &mut AsyncWindowContext,
 5145    ) -> Result<()> {
 5146        let mut entries = transaction.0.into_iter().collect::<Vec<_>>();
 5147        cx.update(|_, cx| {
 5148            entries.sort_unstable_by_key(|(buffer, _)| {
 5149                buffer.read(cx).file().map(|f| f.path().clone())
 5150            });
 5151        })?;
 5152
 5153        // If the project transaction's edits are all contained within this editor, then
 5154        // avoid opening a new editor to display them.
 5155
 5156        if let Some((buffer, transaction)) = entries.first() {
 5157            if entries.len() == 1 {
 5158                let excerpt = this.update(cx, |editor, cx| {
 5159                    editor
 5160                        .buffer()
 5161                        .read(cx)
 5162                        .excerpt_containing(editor.selections.newest_anchor().head(), cx)
 5163                })?;
 5164                if let Some((_, excerpted_buffer, excerpt_range)) = excerpt {
 5165                    if excerpted_buffer == *buffer {
 5166                        let all_edits_within_excerpt = buffer.read_with(cx, |buffer, _| {
 5167                            let excerpt_range = excerpt_range.to_offset(buffer);
 5168                            buffer
 5169                                .edited_ranges_for_transaction::<usize>(transaction)
 5170                                .all(|range| {
 5171                                    excerpt_range.start <= range.start
 5172                                        && excerpt_range.end >= range.end
 5173                                })
 5174                        })?;
 5175
 5176                        if all_edits_within_excerpt {
 5177                            return Ok(());
 5178                        }
 5179                    }
 5180                }
 5181            }
 5182        } else {
 5183            return Ok(());
 5184        }
 5185
 5186        let mut ranges_to_highlight = Vec::new();
 5187        let excerpt_buffer = cx.new(|cx| {
 5188            let mut multibuffer = MultiBuffer::new(Capability::ReadWrite).with_title(title);
 5189            for (buffer_handle, transaction) in &entries {
 5190                let edited_ranges = buffer_handle
 5191                    .read(cx)
 5192                    .edited_ranges_for_transaction::<Point>(transaction)
 5193                    .collect::<Vec<_>>();
 5194                let (ranges, _) = multibuffer.set_excerpts_for_path(
 5195                    PathKey::for_buffer(buffer_handle, cx),
 5196                    buffer_handle.clone(),
 5197                    edited_ranges,
 5198                    DEFAULT_MULTIBUFFER_CONTEXT,
 5199                    cx,
 5200                );
 5201
 5202                ranges_to_highlight.extend(ranges);
 5203            }
 5204            multibuffer.push_transaction(entries.iter().map(|(b, t)| (b, t)), cx);
 5205            multibuffer
 5206        })?;
 5207
 5208        workspace.update_in(cx, |workspace, window, cx| {
 5209            let project = workspace.project().clone();
 5210            let editor =
 5211                cx.new(|cx| Editor::for_multibuffer(excerpt_buffer, Some(project), window, cx));
 5212            workspace.add_item_to_active_pane(Box::new(editor.clone()), None, true, window, cx);
 5213            editor.update(cx, |editor, cx| {
 5214                editor.highlight_background::<Self>(
 5215                    &ranges_to_highlight,
 5216                    |theme| theme.editor_highlighted_line_background,
 5217                    cx,
 5218                );
 5219            });
 5220        })?;
 5221
 5222        Ok(())
 5223    }
 5224
 5225    pub fn clear_code_action_providers(&mut self) {
 5226        self.code_action_providers.clear();
 5227        self.available_code_actions.take();
 5228    }
 5229
 5230    pub fn add_code_action_provider(
 5231        &mut self,
 5232        provider: Rc<dyn CodeActionProvider>,
 5233        window: &mut Window,
 5234        cx: &mut Context<Self>,
 5235    ) {
 5236        if self
 5237            .code_action_providers
 5238            .iter()
 5239            .any(|existing_provider| existing_provider.id() == provider.id())
 5240        {
 5241            return;
 5242        }
 5243
 5244        self.code_action_providers.push(provider);
 5245        self.refresh_code_actions(window, cx);
 5246    }
 5247
 5248    pub fn remove_code_action_provider(
 5249        &mut self,
 5250        id: Arc<str>,
 5251        window: &mut Window,
 5252        cx: &mut Context<Self>,
 5253    ) {
 5254        self.code_action_providers
 5255            .retain(|provider| provider.id() != id);
 5256        self.refresh_code_actions(window, cx);
 5257    }
 5258
 5259    fn refresh_code_actions(&mut self, window: &mut Window, cx: &mut Context<Self>) -> Option<()> {
 5260        let newest_selection = self.selections.newest_anchor().clone();
 5261        let newest_selection_adjusted = self.selections.newest_adjusted(cx).clone();
 5262        let buffer = self.buffer.read(cx);
 5263        if newest_selection.head().diff_base_anchor.is_some() {
 5264            return None;
 5265        }
 5266        let (start_buffer, start) =
 5267            buffer.text_anchor_for_position(newest_selection_adjusted.start, cx)?;
 5268        let (end_buffer, end) =
 5269            buffer.text_anchor_for_position(newest_selection_adjusted.end, cx)?;
 5270        if start_buffer != end_buffer {
 5271            return None;
 5272        }
 5273
 5274        self.code_actions_task = Some(cx.spawn_in(window, async move |this, cx| {
 5275            cx.background_executor()
 5276                .timer(CODE_ACTIONS_DEBOUNCE_TIMEOUT)
 5277                .await;
 5278
 5279            let (providers, tasks) = this.update_in(cx, |this, window, cx| {
 5280                let providers = this.code_action_providers.clone();
 5281                let tasks = this
 5282                    .code_action_providers
 5283                    .iter()
 5284                    .map(|provider| provider.code_actions(&start_buffer, start..end, window, cx))
 5285                    .collect::<Vec<_>>();
 5286                (providers, tasks)
 5287            })?;
 5288
 5289            let mut actions = Vec::new();
 5290            for (provider, provider_actions) in
 5291                providers.into_iter().zip(future::join_all(tasks).await)
 5292            {
 5293                if let Some(provider_actions) = provider_actions.log_err() {
 5294                    actions.extend(provider_actions.into_iter().map(|action| {
 5295                        AvailableCodeAction {
 5296                            excerpt_id: newest_selection.start.excerpt_id,
 5297                            action,
 5298                            provider: provider.clone(),
 5299                        }
 5300                    }));
 5301                }
 5302            }
 5303
 5304            this.update(cx, |this, cx| {
 5305                this.available_code_actions = if actions.is_empty() {
 5306                    None
 5307                } else {
 5308                    Some((
 5309                        Location {
 5310                            buffer: start_buffer,
 5311                            range: start..end,
 5312                        },
 5313                        actions.into(),
 5314                    ))
 5315                };
 5316                cx.notify();
 5317            })
 5318        }));
 5319        None
 5320    }
 5321
 5322    fn start_inline_blame_timer(&mut self, window: &mut Window, cx: &mut Context<Self>) {
 5323        if let Some(delay) = ProjectSettings::get_global(cx).git.inline_blame_delay() {
 5324            self.show_git_blame_inline = false;
 5325
 5326            self.show_git_blame_inline_delay_task =
 5327                Some(cx.spawn_in(window, async move |this, cx| {
 5328                    cx.background_executor().timer(delay).await;
 5329
 5330                    this.update(cx, |this, cx| {
 5331                        this.show_git_blame_inline = true;
 5332                        cx.notify();
 5333                    })
 5334                    .log_err();
 5335                }));
 5336        }
 5337    }
 5338
 5339    fn refresh_document_highlights(&mut self, cx: &mut Context<Self>) -> Option<()> {
 5340        if self.pending_rename.is_some() {
 5341            return None;
 5342        }
 5343
 5344        let provider = self.semantics_provider.clone()?;
 5345        let buffer = self.buffer.read(cx);
 5346        let newest_selection = self.selections.newest_anchor().clone();
 5347        let cursor_position = newest_selection.head();
 5348        let (cursor_buffer, cursor_buffer_position) =
 5349            buffer.text_anchor_for_position(cursor_position, cx)?;
 5350        let (tail_buffer, _) = buffer.text_anchor_for_position(newest_selection.tail(), cx)?;
 5351        if cursor_buffer != tail_buffer {
 5352            return None;
 5353        }
 5354        let debounce = EditorSettings::get_global(cx).lsp_highlight_debounce;
 5355        self.document_highlights_task = Some(cx.spawn(async move |this, cx| {
 5356            cx.background_executor()
 5357                .timer(Duration::from_millis(debounce))
 5358                .await;
 5359
 5360            let highlights = if let Some(highlights) = cx
 5361                .update(|cx| {
 5362                    provider.document_highlights(&cursor_buffer, cursor_buffer_position, cx)
 5363                })
 5364                .ok()
 5365                .flatten()
 5366            {
 5367                highlights.await.log_err()
 5368            } else {
 5369                None
 5370            };
 5371
 5372            if let Some(highlights) = highlights {
 5373                this.update(cx, |this, cx| {
 5374                    if this.pending_rename.is_some() {
 5375                        return;
 5376                    }
 5377
 5378                    let buffer_id = cursor_position.buffer_id;
 5379                    let buffer = this.buffer.read(cx);
 5380                    if !buffer
 5381                        .text_anchor_for_position(cursor_position, cx)
 5382                        .map_or(false, |(buffer, _)| buffer == cursor_buffer)
 5383                    {
 5384                        return;
 5385                    }
 5386
 5387                    let cursor_buffer_snapshot = cursor_buffer.read(cx);
 5388                    let mut write_ranges = Vec::new();
 5389                    let mut read_ranges = Vec::new();
 5390                    for highlight in highlights {
 5391                        for (excerpt_id, excerpt_range) in
 5392                            buffer.excerpts_for_buffer(cursor_buffer.read(cx).remote_id(), cx)
 5393                        {
 5394                            let start = highlight
 5395                                .range
 5396                                .start
 5397                                .max(&excerpt_range.context.start, cursor_buffer_snapshot);
 5398                            let end = highlight
 5399                                .range
 5400                                .end
 5401                                .min(&excerpt_range.context.end, cursor_buffer_snapshot);
 5402                            if start.cmp(&end, cursor_buffer_snapshot).is_ge() {
 5403                                continue;
 5404                            }
 5405
 5406                            let range = Anchor {
 5407                                buffer_id,
 5408                                excerpt_id,
 5409                                text_anchor: start,
 5410                                diff_base_anchor: None,
 5411                            }..Anchor {
 5412                                buffer_id,
 5413                                excerpt_id,
 5414                                text_anchor: end,
 5415                                diff_base_anchor: None,
 5416                            };
 5417                            if highlight.kind == lsp::DocumentHighlightKind::WRITE {
 5418                                write_ranges.push(range);
 5419                            } else {
 5420                                read_ranges.push(range);
 5421                            }
 5422                        }
 5423                    }
 5424
 5425                    this.highlight_background::<DocumentHighlightRead>(
 5426                        &read_ranges,
 5427                        |theme| theme.editor_document_highlight_read_background,
 5428                        cx,
 5429                    );
 5430                    this.highlight_background::<DocumentHighlightWrite>(
 5431                        &write_ranges,
 5432                        |theme| theme.editor_document_highlight_write_background,
 5433                        cx,
 5434                    );
 5435                    cx.notify();
 5436                })
 5437                .log_err();
 5438            }
 5439        }));
 5440        None
 5441    }
 5442
 5443    pub fn refresh_selected_text_highlights(
 5444        &mut self,
 5445        window: &mut Window,
 5446        cx: &mut Context<Editor>,
 5447    ) {
 5448        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 5449            return;
 5450        }
 5451        self.selection_highlight_task.take();
 5452        if !EditorSettings::get_global(cx).selection_highlight {
 5453            self.clear_background_highlights::<SelectedTextHighlight>(cx);
 5454            return;
 5455        }
 5456        if self.selections.count() != 1 || self.selections.line_mode {
 5457            self.clear_background_highlights::<SelectedTextHighlight>(cx);
 5458            return;
 5459        }
 5460        let selection = self.selections.newest::<Point>(cx);
 5461        if selection.is_empty() || selection.start.row != selection.end.row {
 5462            self.clear_background_highlights::<SelectedTextHighlight>(cx);
 5463            return;
 5464        }
 5465        let debounce = EditorSettings::get_global(cx).selection_highlight_debounce;
 5466        self.selection_highlight_task = Some(cx.spawn_in(window, async move |editor, cx| {
 5467            cx.background_executor()
 5468                .timer(Duration::from_millis(debounce))
 5469                .await;
 5470            let Some(Some(matches_task)) = editor
 5471                .update_in(cx, |editor, _, cx| {
 5472                    if editor.selections.count() != 1 || editor.selections.line_mode {
 5473                        editor.clear_background_highlights::<SelectedTextHighlight>(cx);
 5474                        return None;
 5475                    }
 5476                    let selection = editor.selections.newest::<Point>(cx);
 5477                    if selection.is_empty() || selection.start.row != selection.end.row {
 5478                        editor.clear_background_highlights::<SelectedTextHighlight>(cx);
 5479                        return None;
 5480                    }
 5481                    let buffer = editor.buffer().read(cx).snapshot(cx);
 5482                    let query = buffer.text_for_range(selection.range()).collect::<String>();
 5483                    if query.trim().is_empty() {
 5484                        editor.clear_background_highlights::<SelectedTextHighlight>(cx);
 5485                        return None;
 5486                    }
 5487                    Some(cx.background_spawn(async move {
 5488                        let mut ranges = Vec::new();
 5489                        let selection_anchors = selection.range().to_anchors(&buffer);
 5490                        for range in [buffer.anchor_before(0)..buffer.anchor_after(buffer.len())] {
 5491                            for (search_buffer, search_range, excerpt_id) in
 5492                                buffer.range_to_buffer_ranges(range)
 5493                            {
 5494                                ranges.extend(
 5495                                    project::search::SearchQuery::text(
 5496                                        query.clone(),
 5497                                        false,
 5498                                        false,
 5499                                        false,
 5500                                        Default::default(),
 5501                                        Default::default(),
 5502                                        None,
 5503                                    )
 5504                                    .unwrap()
 5505                                    .search(search_buffer, Some(search_range.clone()))
 5506                                    .await
 5507                                    .into_iter()
 5508                                    .filter_map(
 5509                                        |match_range| {
 5510                                            let start = search_buffer.anchor_after(
 5511                                                search_range.start + match_range.start,
 5512                                            );
 5513                                            let end = search_buffer.anchor_before(
 5514                                                search_range.start + match_range.end,
 5515                                            );
 5516                                            let range = Anchor::range_in_buffer(
 5517                                                excerpt_id,
 5518                                                search_buffer.remote_id(),
 5519                                                start..end,
 5520                                            );
 5521                                            (range != selection_anchors).then_some(range)
 5522                                        },
 5523                                    ),
 5524                                );
 5525                            }
 5526                        }
 5527                        ranges
 5528                    }))
 5529                })
 5530                .log_err()
 5531            else {
 5532                return;
 5533            };
 5534            let matches = matches_task.await;
 5535            editor
 5536                .update_in(cx, |editor, _, cx| {
 5537                    editor.clear_background_highlights::<SelectedTextHighlight>(cx);
 5538                    if !matches.is_empty() {
 5539                        editor.highlight_background::<SelectedTextHighlight>(
 5540                            &matches,
 5541                            |theme| theme.editor_document_highlight_bracket_background,
 5542                            cx,
 5543                        )
 5544                    }
 5545                })
 5546                .log_err();
 5547        }));
 5548    }
 5549
 5550    pub fn refresh_inline_completion(
 5551        &mut self,
 5552        debounce: bool,
 5553        user_requested: bool,
 5554        window: &mut Window,
 5555        cx: &mut Context<Self>,
 5556    ) -> Option<()> {
 5557        let provider = self.edit_prediction_provider()?;
 5558        let cursor = self.selections.newest_anchor().head();
 5559        let (buffer, cursor_buffer_position) =
 5560            self.buffer.read(cx).text_anchor_for_position(cursor, cx)?;
 5561
 5562        if !self.edit_predictions_enabled_in_buffer(&buffer, cursor_buffer_position, cx) {
 5563            self.discard_inline_completion(false, cx);
 5564            return None;
 5565        }
 5566
 5567        if !user_requested
 5568            && (!self.should_show_edit_predictions()
 5569                || !self.is_focused(window)
 5570                || buffer.read(cx).is_empty())
 5571        {
 5572            self.discard_inline_completion(false, cx);
 5573            return None;
 5574        }
 5575
 5576        self.update_visible_inline_completion(window, cx);
 5577        provider.refresh(
 5578            self.project.clone(),
 5579            buffer,
 5580            cursor_buffer_position,
 5581            debounce,
 5582            cx,
 5583        );
 5584        Some(())
 5585    }
 5586
 5587    fn show_edit_predictions_in_menu(&self) -> bool {
 5588        match self.edit_prediction_settings {
 5589            EditPredictionSettings::Disabled => false,
 5590            EditPredictionSettings::Enabled { show_in_menu, .. } => show_in_menu,
 5591        }
 5592    }
 5593
 5594    pub fn edit_predictions_enabled(&self) -> bool {
 5595        match self.edit_prediction_settings {
 5596            EditPredictionSettings::Disabled => false,
 5597            EditPredictionSettings::Enabled { .. } => true,
 5598        }
 5599    }
 5600
 5601    fn edit_prediction_requires_modifier(&self) -> bool {
 5602        match self.edit_prediction_settings {
 5603            EditPredictionSettings::Disabled => false,
 5604            EditPredictionSettings::Enabled {
 5605                preview_requires_modifier,
 5606                ..
 5607            } => preview_requires_modifier,
 5608        }
 5609    }
 5610
 5611    pub fn update_edit_prediction_settings(&mut self, cx: &mut Context<Self>) {
 5612        if self.edit_prediction_provider.is_none() {
 5613            self.edit_prediction_settings = EditPredictionSettings::Disabled;
 5614        } else {
 5615            let selection = self.selections.newest_anchor();
 5616            let cursor = selection.head();
 5617
 5618            if let Some((buffer, cursor_buffer_position)) =
 5619                self.buffer.read(cx).text_anchor_for_position(cursor, cx)
 5620            {
 5621                self.edit_prediction_settings =
 5622                    self.edit_prediction_settings_at_position(&buffer, cursor_buffer_position, cx);
 5623            }
 5624        }
 5625    }
 5626
 5627    fn edit_prediction_settings_at_position(
 5628        &self,
 5629        buffer: &Entity<Buffer>,
 5630        buffer_position: language::Anchor,
 5631        cx: &App,
 5632    ) -> EditPredictionSettings {
 5633        if !self.mode.is_full()
 5634            || !self.show_inline_completions_override.unwrap_or(true)
 5635            || self.inline_completions_disabled_in_scope(buffer, buffer_position, cx)
 5636        {
 5637            return EditPredictionSettings::Disabled;
 5638        }
 5639
 5640        let buffer = buffer.read(cx);
 5641
 5642        let file = buffer.file();
 5643
 5644        if !language_settings(buffer.language().map(|l| l.name()), file, cx).show_edit_predictions {
 5645            return EditPredictionSettings::Disabled;
 5646        };
 5647
 5648        let by_provider = matches!(
 5649            self.menu_inline_completions_policy,
 5650            MenuInlineCompletionsPolicy::ByProvider
 5651        );
 5652
 5653        let show_in_menu = by_provider
 5654            && self
 5655                .edit_prediction_provider
 5656                .as_ref()
 5657                .map_or(false, |provider| {
 5658                    provider.provider.show_completions_in_menu()
 5659                });
 5660
 5661        let preview_requires_modifier =
 5662            all_language_settings(file, cx).edit_predictions_mode() == EditPredictionsMode::Subtle;
 5663
 5664        EditPredictionSettings::Enabled {
 5665            show_in_menu,
 5666            preview_requires_modifier,
 5667        }
 5668    }
 5669
 5670    fn should_show_edit_predictions(&self) -> bool {
 5671        self.snippet_stack.is_empty() && self.edit_predictions_enabled()
 5672    }
 5673
 5674    pub fn edit_prediction_preview_is_active(&self) -> bool {
 5675        matches!(
 5676            self.edit_prediction_preview,
 5677            EditPredictionPreview::Active { .. }
 5678        )
 5679    }
 5680
 5681    pub fn edit_predictions_enabled_at_cursor(&self, cx: &App) -> bool {
 5682        let cursor = self.selections.newest_anchor().head();
 5683        if let Some((buffer, cursor_position)) =
 5684            self.buffer.read(cx).text_anchor_for_position(cursor, cx)
 5685        {
 5686            self.edit_predictions_enabled_in_buffer(&buffer, cursor_position, cx)
 5687        } else {
 5688            false
 5689        }
 5690    }
 5691
 5692    fn edit_predictions_enabled_in_buffer(
 5693        &self,
 5694        buffer: &Entity<Buffer>,
 5695        buffer_position: language::Anchor,
 5696        cx: &App,
 5697    ) -> bool {
 5698        maybe!({
 5699            if self.read_only(cx) {
 5700                return Some(false);
 5701            }
 5702            let provider = self.edit_prediction_provider()?;
 5703            if !provider.is_enabled(&buffer, buffer_position, cx) {
 5704                return Some(false);
 5705            }
 5706            let buffer = buffer.read(cx);
 5707            let Some(file) = buffer.file() else {
 5708                return Some(true);
 5709            };
 5710            let settings = all_language_settings(Some(file), cx);
 5711            Some(settings.edit_predictions_enabled_for_file(file, cx))
 5712        })
 5713        .unwrap_or(false)
 5714    }
 5715
 5716    fn cycle_inline_completion(
 5717        &mut self,
 5718        direction: Direction,
 5719        window: &mut Window,
 5720        cx: &mut Context<Self>,
 5721    ) -> Option<()> {
 5722        let provider = self.edit_prediction_provider()?;
 5723        let cursor = self.selections.newest_anchor().head();
 5724        let (buffer, cursor_buffer_position) =
 5725            self.buffer.read(cx).text_anchor_for_position(cursor, cx)?;
 5726        if self.inline_completions_hidden_for_vim_mode || !self.should_show_edit_predictions() {
 5727            return None;
 5728        }
 5729
 5730        provider.cycle(buffer, cursor_buffer_position, direction, cx);
 5731        self.update_visible_inline_completion(window, cx);
 5732
 5733        Some(())
 5734    }
 5735
 5736    pub fn show_inline_completion(
 5737        &mut self,
 5738        _: &ShowEditPrediction,
 5739        window: &mut Window,
 5740        cx: &mut Context<Self>,
 5741    ) {
 5742        if !self.has_active_inline_completion() {
 5743            self.refresh_inline_completion(false, true, window, cx);
 5744            return;
 5745        }
 5746
 5747        self.update_visible_inline_completion(window, cx);
 5748    }
 5749
 5750    pub fn display_cursor_names(
 5751        &mut self,
 5752        _: &DisplayCursorNames,
 5753        window: &mut Window,
 5754        cx: &mut Context<Self>,
 5755    ) {
 5756        self.show_cursor_names(window, cx);
 5757    }
 5758
 5759    fn show_cursor_names(&mut self, window: &mut Window, cx: &mut Context<Self>) {
 5760        self.show_cursor_names = true;
 5761        cx.notify();
 5762        cx.spawn_in(window, async move |this, cx| {
 5763            cx.background_executor().timer(CURSORS_VISIBLE_FOR).await;
 5764            this.update(cx, |this, cx| {
 5765                this.show_cursor_names = false;
 5766                cx.notify()
 5767            })
 5768            .ok()
 5769        })
 5770        .detach();
 5771    }
 5772
 5773    pub fn next_edit_prediction(
 5774        &mut self,
 5775        _: &NextEditPrediction,
 5776        window: &mut Window,
 5777        cx: &mut Context<Self>,
 5778    ) {
 5779        if self.has_active_inline_completion() {
 5780            self.cycle_inline_completion(Direction::Next, window, cx);
 5781        } else {
 5782            let is_copilot_disabled = self
 5783                .refresh_inline_completion(false, true, window, cx)
 5784                .is_none();
 5785            if is_copilot_disabled {
 5786                cx.propagate();
 5787            }
 5788        }
 5789    }
 5790
 5791    pub fn previous_edit_prediction(
 5792        &mut self,
 5793        _: &PreviousEditPrediction,
 5794        window: &mut Window,
 5795        cx: &mut Context<Self>,
 5796    ) {
 5797        if self.has_active_inline_completion() {
 5798            self.cycle_inline_completion(Direction::Prev, window, cx);
 5799        } else {
 5800            let is_copilot_disabled = self
 5801                .refresh_inline_completion(false, true, window, cx)
 5802                .is_none();
 5803            if is_copilot_disabled {
 5804                cx.propagate();
 5805            }
 5806        }
 5807    }
 5808
 5809    pub fn accept_edit_prediction(
 5810        &mut self,
 5811        _: &AcceptEditPrediction,
 5812        window: &mut Window,
 5813        cx: &mut Context<Self>,
 5814    ) {
 5815        if self.show_edit_predictions_in_menu() {
 5816            self.hide_context_menu(window, cx);
 5817        }
 5818
 5819        let Some(active_inline_completion) = self.active_inline_completion.as_ref() else {
 5820            return;
 5821        };
 5822
 5823        self.report_inline_completion_event(
 5824            active_inline_completion.completion_id.clone(),
 5825            true,
 5826            cx,
 5827        );
 5828
 5829        match &active_inline_completion.completion {
 5830            InlineCompletion::Move { target, .. } => {
 5831                let target = *target;
 5832
 5833                if let Some(position_map) = &self.last_position_map {
 5834                    if position_map
 5835                        .visible_row_range
 5836                        .contains(&target.to_display_point(&position_map.snapshot).row())
 5837                        || !self.edit_prediction_requires_modifier()
 5838                    {
 5839                        self.unfold_ranges(&[target..target], true, false, cx);
 5840                        // Note that this is also done in vim's handler of the Tab action.
 5841                        self.change_selections(
 5842                            Some(Autoscroll::newest()),
 5843                            window,
 5844                            cx,
 5845                            |selections| {
 5846                                selections.select_anchor_ranges([target..target]);
 5847                            },
 5848                        );
 5849                        self.clear_row_highlights::<EditPredictionPreview>();
 5850
 5851                        self.edit_prediction_preview
 5852                            .set_previous_scroll_position(None);
 5853                    } else {
 5854                        self.edit_prediction_preview
 5855                            .set_previous_scroll_position(Some(
 5856                                position_map.snapshot.scroll_anchor,
 5857                            ));
 5858
 5859                        self.highlight_rows::<EditPredictionPreview>(
 5860                            target..target,
 5861                            cx.theme().colors().editor_highlighted_line_background,
 5862                            true,
 5863                            cx,
 5864                        );
 5865                        self.request_autoscroll(Autoscroll::fit(), cx);
 5866                    }
 5867                }
 5868            }
 5869            InlineCompletion::Edit { edits, .. } => {
 5870                if let Some(provider) = self.edit_prediction_provider() {
 5871                    provider.accept(cx);
 5872                }
 5873
 5874                let snapshot = self.buffer.read(cx).snapshot(cx);
 5875                let last_edit_end = edits.last().unwrap().0.end.bias_right(&snapshot);
 5876
 5877                self.buffer.update(cx, |buffer, cx| {
 5878                    buffer.edit(edits.iter().cloned(), None, cx)
 5879                });
 5880
 5881                self.change_selections(None, window, cx, |s| {
 5882                    s.select_anchor_ranges([last_edit_end..last_edit_end])
 5883                });
 5884
 5885                self.update_visible_inline_completion(window, cx);
 5886                if self.active_inline_completion.is_none() {
 5887                    self.refresh_inline_completion(true, true, window, cx);
 5888                }
 5889
 5890                cx.notify();
 5891            }
 5892        }
 5893
 5894        self.edit_prediction_requires_modifier_in_indent_conflict = false;
 5895    }
 5896
 5897    pub fn accept_partial_inline_completion(
 5898        &mut self,
 5899        _: &AcceptPartialEditPrediction,
 5900        window: &mut Window,
 5901        cx: &mut Context<Self>,
 5902    ) {
 5903        let Some(active_inline_completion) = self.active_inline_completion.as_ref() else {
 5904            return;
 5905        };
 5906        if self.selections.count() != 1 {
 5907            return;
 5908        }
 5909
 5910        self.report_inline_completion_event(
 5911            active_inline_completion.completion_id.clone(),
 5912            true,
 5913            cx,
 5914        );
 5915
 5916        match &active_inline_completion.completion {
 5917            InlineCompletion::Move { target, .. } => {
 5918                let target = *target;
 5919                self.change_selections(Some(Autoscroll::newest()), window, cx, |selections| {
 5920                    selections.select_anchor_ranges([target..target]);
 5921                });
 5922            }
 5923            InlineCompletion::Edit { edits, .. } => {
 5924                // Find an insertion that starts at the cursor position.
 5925                let snapshot = self.buffer.read(cx).snapshot(cx);
 5926                let cursor_offset = self.selections.newest::<usize>(cx).head();
 5927                let insertion = edits.iter().find_map(|(range, text)| {
 5928                    let range = range.to_offset(&snapshot);
 5929                    if range.is_empty() && range.start == cursor_offset {
 5930                        Some(text)
 5931                    } else {
 5932                        None
 5933                    }
 5934                });
 5935
 5936                if let Some(text) = insertion {
 5937                    let mut partial_completion = text
 5938                        .chars()
 5939                        .by_ref()
 5940                        .take_while(|c| c.is_alphabetic())
 5941                        .collect::<String>();
 5942                    if partial_completion.is_empty() {
 5943                        partial_completion = text
 5944                            .chars()
 5945                            .by_ref()
 5946                            .take_while(|c| c.is_whitespace() || !c.is_alphabetic())
 5947                            .collect::<String>();
 5948                    }
 5949
 5950                    cx.emit(EditorEvent::InputHandled {
 5951                        utf16_range_to_replace: None,
 5952                        text: partial_completion.clone().into(),
 5953                    });
 5954
 5955                    self.insert_with_autoindent_mode(&partial_completion, None, window, cx);
 5956
 5957                    self.refresh_inline_completion(true, true, window, cx);
 5958                    cx.notify();
 5959                } else {
 5960                    self.accept_edit_prediction(&Default::default(), window, cx);
 5961                }
 5962            }
 5963        }
 5964    }
 5965
 5966    fn discard_inline_completion(
 5967        &mut self,
 5968        should_report_inline_completion_event: bool,
 5969        cx: &mut Context<Self>,
 5970    ) -> bool {
 5971        if should_report_inline_completion_event {
 5972            let completion_id = self
 5973                .active_inline_completion
 5974                .as_ref()
 5975                .and_then(|active_completion| active_completion.completion_id.clone());
 5976
 5977            self.report_inline_completion_event(completion_id, false, cx);
 5978        }
 5979
 5980        if let Some(provider) = self.edit_prediction_provider() {
 5981            provider.discard(cx);
 5982        }
 5983
 5984        self.take_active_inline_completion(cx)
 5985    }
 5986
 5987    fn report_inline_completion_event(&self, id: Option<SharedString>, accepted: bool, cx: &App) {
 5988        let Some(provider) = self.edit_prediction_provider() else {
 5989            return;
 5990        };
 5991
 5992        let Some((_, buffer, _)) = self
 5993            .buffer
 5994            .read(cx)
 5995            .excerpt_containing(self.selections.newest_anchor().head(), cx)
 5996        else {
 5997            return;
 5998        };
 5999
 6000        let extension = buffer
 6001            .read(cx)
 6002            .file()
 6003            .and_then(|file| Some(file.path().extension()?.to_string_lossy().to_string()));
 6004
 6005        let event_type = match accepted {
 6006            true => "Edit Prediction Accepted",
 6007            false => "Edit Prediction Discarded",
 6008        };
 6009        telemetry::event!(
 6010            event_type,
 6011            provider = provider.name(),
 6012            prediction_id = id,
 6013            suggestion_accepted = accepted,
 6014            file_extension = extension,
 6015        );
 6016    }
 6017
 6018    pub fn has_active_inline_completion(&self) -> bool {
 6019        self.active_inline_completion.is_some()
 6020    }
 6021
 6022    fn take_active_inline_completion(&mut self, cx: &mut Context<Self>) -> bool {
 6023        let Some(active_inline_completion) = self.active_inline_completion.take() else {
 6024            return false;
 6025        };
 6026
 6027        self.splice_inlays(&active_inline_completion.inlay_ids, Default::default(), cx);
 6028        self.clear_highlights::<InlineCompletionHighlight>(cx);
 6029        self.stale_inline_completion_in_menu = Some(active_inline_completion);
 6030        true
 6031    }
 6032
 6033    /// Returns true when we're displaying the edit prediction popover below the cursor
 6034    /// like we are not previewing and the LSP autocomplete menu is visible
 6035    /// or we are in `when_holding_modifier` mode.
 6036    pub fn edit_prediction_visible_in_cursor_popover(&self, has_completion: bool) -> bool {
 6037        if self.edit_prediction_preview_is_active()
 6038            || !self.show_edit_predictions_in_menu()
 6039            || !self.edit_predictions_enabled()
 6040        {
 6041            return false;
 6042        }
 6043
 6044        if self.has_visible_completions_menu() {
 6045            return true;
 6046        }
 6047
 6048        has_completion && self.edit_prediction_requires_modifier()
 6049    }
 6050
 6051    fn handle_modifiers_changed(
 6052        &mut self,
 6053        modifiers: Modifiers,
 6054        position_map: &PositionMap,
 6055        window: &mut Window,
 6056        cx: &mut Context<Self>,
 6057    ) {
 6058        if self.show_edit_predictions_in_menu() {
 6059            self.update_edit_prediction_preview(&modifiers, window, cx);
 6060        }
 6061
 6062        self.update_selection_mode(&modifiers, position_map, window, cx);
 6063
 6064        let mouse_position = window.mouse_position();
 6065        if !position_map.text_hitbox.is_hovered(window) {
 6066            return;
 6067        }
 6068
 6069        self.update_hovered_link(
 6070            position_map.point_for_position(mouse_position),
 6071            &position_map.snapshot,
 6072            modifiers,
 6073            window,
 6074            cx,
 6075        )
 6076    }
 6077
 6078    fn update_selection_mode(
 6079        &mut self,
 6080        modifiers: &Modifiers,
 6081        position_map: &PositionMap,
 6082        window: &mut Window,
 6083        cx: &mut Context<Self>,
 6084    ) {
 6085        if modifiers != &COLUMNAR_SELECTION_MODIFIERS || self.selections.pending.is_none() {
 6086            return;
 6087        }
 6088
 6089        let mouse_position = window.mouse_position();
 6090        let point_for_position = position_map.point_for_position(mouse_position);
 6091        let position = point_for_position.previous_valid;
 6092
 6093        self.select(
 6094            SelectPhase::BeginColumnar {
 6095                position,
 6096                reset: false,
 6097                goal_column: point_for_position.exact_unclipped.column(),
 6098            },
 6099            window,
 6100            cx,
 6101        );
 6102    }
 6103
 6104    fn update_edit_prediction_preview(
 6105        &mut self,
 6106        modifiers: &Modifiers,
 6107        window: &mut Window,
 6108        cx: &mut Context<Self>,
 6109    ) {
 6110        let accept_keybind = self.accept_edit_prediction_keybind(window, cx);
 6111        let Some(accept_keystroke) = accept_keybind.keystroke() else {
 6112            return;
 6113        };
 6114
 6115        if &accept_keystroke.modifiers == modifiers && accept_keystroke.modifiers.modified() {
 6116            if matches!(
 6117                self.edit_prediction_preview,
 6118                EditPredictionPreview::Inactive { .. }
 6119            ) {
 6120                self.edit_prediction_preview = EditPredictionPreview::Active {
 6121                    previous_scroll_position: None,
 6122                    since: Instant::now(),
 6123                };
 6124
 6125                self.update_visible_inline_completion(window, cx);
 6126                cx.notify();
 6127            }
 6128        } else if let EditPredictionPreview::Active {
 6129            previous_scroll_position,
 6130            since,
 6131        } = self.edit_prediction_preview
 6132        {
 6133            if let (Some(previous_scroll_position), Some(position_map)) =
 6134                (previous_scroll_position, self.last_position_map.as_ref())
 6135            {
 6136                self.set_scroll_position(
 6137                    previous_scroll_position
 6138                        .scroll_position(&position_map.snapshot.display_snapshot),
 6139                    window,
 6140                    cx,
 6141                );
 6142            }
 6143
 6144            self.edit_prediction_preview = EditPredictionPreview::Inactive {
 6145                released_too_fast: since.elapsed() < Duration::from_millis(200),
 6146            };
 6147            self.clear_row_highlights::<EditPredictionPreview>();
 6148            self.update_visible_inline_completion(window, cx);
 6149            cx.notify();
 6150        }
 6151    }
 6152
 6153    fn update_visible_inline_completion(
 6154        &mut self,
 6155        _window: &mut Window,
 6156        cx: &mut Context<Self>,
 6157    ) -> Option<()> {
 6158        let selection = self.selections.newest_anchor();
 6159        let cursor = selection.head();
 6160        let multibuffer = self.buffer.read(cx).snapshot(cx);
 6161        let offset_selection = selection.map(|endpoint| endpoint.to_offset(&multibuffer));
 6162        let excerpt_id = cursor.excerpt_id;
 6163
 6164        let show_in_menu = self.show_edit_predictions_in_menu();
 6165        let completions_menu_has_precedence = !show_in_menu
 6166            && (self.context_menu.borrow().is_some()
 6167                || (!self.completion_tasks.is_empty() && !self.has_active_inline_completion()));
 6168
 6169        if completions_menu_has_precedence
 6170            || !offset_selection.is_empty()
 6171            || self
 6172                .active_inline_completion
 6173                .as_ref()
 6174                .map_or(false, |completion| {
 6175                    let invalidation_range = completion.invalidation_range.to_offset(&multibuffer);
 6176                    let invalidation_range = invalidation_range.start..=invalidation_range.end;
 6177                    !invalidation_range.contains(&offset_selection.head())
 6178                })
 6179        {
 6180            self.discard_inline_completion(false, cx);
 6181            return None;
 6182        }
 6183
 6184        self.take_active_inline_completion(cx);
 6185        let Some(provider) = self.edit_prediction_provider() else {
 6186            self.edit_prediction_settings = EditPredictionSettings::Disabled;
 6187            return None;
 6188        };
 6189
 6190        let (buffer, cursor_buffer_position) =
 6191            self.buffer.read(cx).text_anchor_for_position(cursor, cx)?;
 6192
 6193        self.edit_prediction_settings =
 6194            self.edit_prediction_settings_at_position(&buffer, cursor_buffer_position, cx);
 6195
 6196        self.edit_prediction_indent_conflict = multibuffer.is_line_whitespace_upto(cursor);
 6197
 6198        if self.edit_prediction_indent_conflict {
 6199            let cursor_point = cursor.to_point(&multibuffer);
 6200
 6201            let indents = multibuffer.suggested_indents(cursor_point.row..cursor_point.row + 1, cx);
 6202
 6203            if let Some((_, indent)) = indents.iter().next() {
 6204                if indent.len == cursor_point.column {
 6205                    self.edit_prediction_indent_conflict = false;
 6206                }
 6207            }
 6208        }
 6209
 6210        let inline_completion = provider.suggest(&buffer, cursor_buffer_position, cx)?;
 6211        let edits = inline_completion
 6212            .edits
 6213            .into_iter()
 6214            .flat_map(|(range, new_text)| {
 6215                let start = multibuffer.anchor_in_excerpt(excerpt_id, range.start)?;
 6216                let end = multibuffer.anchor_in_excerpt(excerpt_id, range.end)?;
 6217                Some((start..end, new_text))
 6218            })
 6219            .collect::<Vec<_>>();
 6220        if edits.is_empty() {
 6221            return None;
 6222        }
 6223
 6224        let first_edit_start = edits.first().unwrap().0.start;
 6225        let first_edit_start_point = first_edit_start.to_point(&multibuffer);
 6226        let edit_start_row = first_edit_start_point.row.saturating_sub(2);
 6227
 6228        let last_edit_end = edits.last().unwrap().0.end;
 6229        let last_edit_end_point = last_edit_end.to_point(&multibuffer);
 6230        let edit_end_row = cmp::min(multibuffer.max_point().row, last_edit_end_point.row + 2);
 6231
 6232        let cursor_row = cursor.to_point(&multibuffer).row;
 6233
 6234        let snapshot = multibuffer.buffer_for_excerpt(excerpt_id).cloned()?;
 6235
 6236        let mut inlay_ids = Vec::new();
 6237        let invalidation_row_range;
 6238        let move_invalidation_row_range = if cursor_row < edit_start_row {
 6239            Some(cursor_row..edit_end_row)
 6240        } else if cursor_row > edit_end_row {
 6241            Some(edit_start_row..cursor_row)
 6242        } else {
 6243            None
 6244        };
 6245        let is_move =
 6246            move_invalidation_row_range.is_some() || self.inline_completions_hidden_for_vim_mode;
 6247        let completion = if is_move {
 6248            invalidation_row_range =
 6249                move_invalidation_row_range.unwrap_or(edit_start_row..edit_end_row);
 6250            let target = first_edit_start;
 6251            InlineCompletion::Move { target, snapshot }
 6252        } else {
 6253            let show_completions_in_buffer = !self.edit_prediction_visible_in_cursor_popover(true)
 6254                && !self.inline_completions_hidden_for_vim_mode;
 6255
 6256            if show_completions_in_buffer {
 6257                if edits
 6258                    .iter()
 6259                    .all(|(range, _)| range.to_offset(&multibuffer).is_empty())
 6260                {
 6261                    let mut inlays = Vec::new();
 6262                    for (range, new_text) in &edits {
 6263                        let inlay = Inlay::inline_completion(
 6264                            post_inc(&mut self.next_inlay_id),
 6265                            range.start,
 6266                            new_text.as_str(),
 6267                        );
 6268                        inlay_ids.push(inlay.id);
 6269                        inlays.push(inlay);
 6270                    }
 6271
 6272                    self.splice_inlays(&[], inlays, cx);
 6273                } else {
 6274                    let background_color = cx.theme().status().deleted_background;
 6275                    self.highlight_text::<InlineCompletionHighlight>(
 6276                        edits.iter().map(|(range, _)| range.clone()).collect(),
 6277                        HighlightStyle {
 6278                            background_color: Some(background_color),
 6279                            ..Default::default()
 6280                        },
 6281                        cx,
 6282                    );
 6283                }
 6284            }
 6285
 6286            invalidation_row_range = edit_start_row..edit_end_row;
 6287
 6288            let display_mode = if all_edits_insertions_or_deletions(&edits, &multibuffer) {
 6289                if provider.show_tab_accept_marker() {
 6290                    EditDisplayMode::TabAccept
 6291                } else {
 6292                    EditDisplayMode::Inline
 6293                }
 6294            } else {
 6295                EditDisplayMode::DiffPopover
 6296            };
 6297
 6298            InlineCompletion::Edit {
 6299                edits,
 6300                edit_preview: inline_completion.edit_preview,
 6301                display_mode,
 6302                snapshot,
 6303            }
 6304        };
 6305
 6306        let invalidation_range = multibuffer
 6307            .anchor_before(Point::new(invalidation_row_range.start, 0))
 6308            ..multibuffer.anchor_after(Point::new(
 6309                invalidation_row_range.end,
 6310                multibuffer.line_len(MultiBufferRow(invalidation_row_range.end)),
 6311            ));
 6312
 6313        self.stale_inline_completion_in_menu = None;
 6314        self.active_inline_completion = Some(InlineCompletionState {
 6315            inlay_ids,
 6316            completion,
 6317            completion_id: inline_completion.id,
 6318            invalidation_range,
 6319        });
 6320
 6321        cx.notify();
 6322
 6323        Some(())
 6324    }
 6325
 6326    pub fn edit_prediction_provider(&self) -> Option<Arc<dyn InlineCompletionProviderHandle>> {
 6327        Some(self.edit_prediction_provider.as_ref()?.provider.clone())
 6328    }
 6329
 6330    fn render_code_actions_indicator(
 6331        &self,
 6332        _style: &EditorStyle,
 6333        row: DisplayRow,
 6334        is_active: bool,
 6335        breakpoint: Option<&(Anchor, Breakpoint)>,
 6336        cx: &mut Context<Self>,
 6337    ) -> Option<IconButton> {
 6338        let color = Color::Muted;
 6339        let position = breakpoint.as_ref().map(|(anchor, _)| *anchor);
 6340        let show_tooltip = !self.context_menu_visible();
 6341
 6342        if self.available_code_actions.is_some() {
 6343            Some(
 6344                IconButton::new("code_actions_indicator", ui::IconName::Bolt)
 6345                    .shape(ui::IconButtonShape::Square)
 6346                    .icon_size(IconSize::XSmall)
 6347                    .icon_color(color)
 6348                    .toggle_state(is_active)
 6349                    .when(show_tooltip, |this| {
 6350                        this.tooltip({
 6351                            let focus_handle = self.focus_handle.clone();
 6352                            move |window, cx| {
 6353                                Tooltip::for_action_in(
 6354                                    "Toggle Code Actions",
 6355                                    &ToggleCodeActions {
 6356                                        deployed_from_indicator: None,
 6357                                    },
 6358                                    &focus_handle,
 6359                                    window,
 6360                                    cx,
 6361                                )
 6362                            }
 6363                        })
 6364                    })
 6365                    .on_click(cx.listener(move |editor, _e, window, cx| {
 6366                        window.focus(&editor.focus_handle(cx));
 6367                        editor.toggle_code_actions(
 6368                            &ToggleCodeActions {
 6369                                deployed_from_indicator: Some(row),
 6370                            },
 6371                            window,
 6372                            cx,
 6373                        );
 6374                    }))
 6375                    .on_right_click(cx.listener(move |editor, event: &ClickEvent, window, cx| {
 6376                        editor.set_breakpoint_context_menu(
 6377                            row,
 6378                            position,
 6379                            event.down.position,
 6380                            window,
 6381                            cx,
 6382                        );
 6383                    })),
 6384            )
 6385        } else {
 6386            None
 6387        }
 6388    }
 6389
 6390    fn clear_tasks(&mut self) {
 6391        self.tasks.clear()
 6392    }
 6393
 6394    fn insert_tasks(&mut self, key: (BufferId, BufferRow), value: RunnableTasks) {
 6395        if self.tasks.insert(key, value).is_some() {
 6396            // This case should hopefully be rare, but just in case...
 6397            log::error!(
 6398                "multiple different run targets found on a single line, only the last target will be rendered"
 6399            )
 6400        }
 6401    }
 6402
 6403    /// Get all display points of breakpoints that will be rendered within editor
 6404    ///
 6405    /// This function is used to handle overlaps between breakpoints and Code action/runner symbol.
 6406    /// It's also used to set the color of line numbers with breakpoints to the breakpoint color.
 6407    /// TODO debugger: Use this function to color toggle symbols that house nested breakpoints
 6408    fn active_breakpoints(
 6409        &self,
 6410        range: Range<DisplayRow>,
 6411        window: &mut Window,
 6412        cx: &mut Context<Self>,
 6413    ) -> HashMap<DisplayRow, (Anchor, Breakpoint)> {
 6414        let mut breakpoint_display_points = HashMap::default();
 6415
 6416        let Some(breakpoint_store) = self.breakpoint_store.clone() else {
 6417            return breakpoint_display_points;
 6418        };
 6419
 6420        let snapshot = self.snapshot(window, cx);
 6421
 6422        let multi_buffer_snapshot = &snapshot.display_snapshot.buffer_snapshot;
 6423        let Some(project) = self.project.as_ref() else {
 6424            return breakpoint_display_points;
 6425        };
 6426
 6427        let range = snapshot.display_point_to_point(DisplayPoint::new(range.start, 0), Bias::Left)
 6428            ..snapshot.display_point_to_point(DisplayPoint::new(range.end, 0), Bias::Right);
 6429
 6430        for (buffer_snapshot, range, excerpt_id) in
 6431            multi_buffer_snapshot.range_to_buffer_ranges(range)
 6432        {
 6433            let Some(buffer) = project.read_with(cx, |this, cx| {
 6434                this.buffer_for_id(buffer_snapshot.remote_id(), cx)
 6435            }) else {
 6436                continue;
 6437            };
 6438            let breakpoints = breakpoint_store.read(cx).breakpoints(
 6439                &buffer,
 6440                Some(
 6441                    buffer_snapshot.anchor_before(range.start)
 6442                        ..buffer_snapshot.anchor_after(range.end),
 6443                ),
 6444                buffer_snapshot,
 6445                cx,
 6446            );
 6447            for (anchor, breakpoint) in breakpoints {
 6448                let multi_buffer_anchor =
 6449                    Anchor::in_buffer(excerpt_id, buffer_snapshot.remote_id(), *anchor);
 6450                let position = multi_buffer_anchor
 6451                    .to_point(&multi_buffer_snapshot)
 6452                    .to_display_point(&snapshot);
 6453
 6454                breakpoint_display_points
 6455                    .insert(position.row(), (multi_buffer_anchor, breakpoint.clone()));
 6456            }
 6457        }
 6458
 6459        breakpoint_display_points
 6460    }
 6461
 6462    fn breakpoint_context_menu(
 6463        &self,
 6464        anchor: Anchor,
 6465        window: &mut Window,
 6466        cx: &mut Context<Self>,
 6467    ) -> Entity<ui::ContextMenu> {
 6468        let weak_editor = cx.weak_entity();
 6469        let focus_handle = self.focus_handle(cx);
 6470
 6471        let row = self
 6472            .buffer
 6473            .read(cx)
 6474            .snapshot(cx)
 6475            .summary_for_anchor::<Point>(&anchor)
 6476            .row;
 6477
 6478        let breakpoint = self
 6479            .breakpoint_at_row(row, window, cx)
 6480            .map(|(anchor, bp)| (anchor, Arc::from(bp)));
 6481
 6482        let log_breakpoint_msg = if breakpoint.as_ref().is_some_and(|bp| bp.1.message.is_some()) {
 6483            "Edit Log Breakpoint"
 6484        } else {
 6485            "Set Log Breakpoint"
 6486        };
 6487
 6488        let condition_breakpoint_msg = if breakpoint
 6489            .as_ref()
 6490            .is_some_and(|bp| bp.1.condition.is_some())
 6491        {
 6492            "Edit Condition Breakpoint"
 6493        } else {
 6494            "Set Condition Breakpoint"
 6495        };
 6496
 6497        let hit_condition_breakpoint_msg = if breakpoint
 6498            .as_ref()
 6499            .is_some_and(|bp| bp.1.hit_condition.is_some())
 6500        {
 6501            "Edit Hit Condition Breakpoint"
 6502        } else {
 6503            "Set Hit Condition Breakpoint"
 6504        };
 6505
 6506        let set_breakpoint_msg = if breakpoint.as_ref().is_some() {
 6507            "Unset Breakpoint"
 6508        } else {
 6509            "Set Breakpoint"
 6510        };
 6511
 6512        let run_to_cursor = command_palette_hooks::CommandPaletteFilter::try_global(cx)
 6513            .map_or(false, |filter| !filter.is_hidden(&DebuggerRunToCursor));
 6514
 6515        let toggle_state_msg = breakpoint.as_ref().map_or(None, |bp| match bp.1.state {
 6516            BreakpointState::Enabled => Some("Disable"),
 6517            BreakpointState::Disabled => Some("Enable"),
 6518        });
 6519
 6520        let (anchor, breakpoint) =
 6521            breakpoint.unwrap_or_else(|| (anchor, Arc::new(Breakpoint::new_standard())));
 6522
 6523        ui::ContextMenu::build(window, cx, |menu, _, _cx| {
 6524            menu.on_blur_subscription(Subscription::new(|| {}))
 6525                .context(focus_handle)
 6526                .when(run_to_cursor, |this| {
 6527                    let weak_editor = weak_editor.clone();
 6528                    this.entry("Run to cursor", None, move |window, cx| {
 6529                        weak_editor
 6530                            .update(cx, |editor, cx| {
 6531                                editor.change_selections(None, window, cx, |s| {
 6532                                    s.select_ranges([Point::new(row, 0)..Point::new(row, 0)])
 6533                                });
 6534                            })
 6535                            .ok();
 6536
 6537                        window.dispatch_action(Box::new(DebuggerRunToCursor), cx);
 6538                    })
 6539                    .separator()
 6540                })
 6541                .when_some(toggle_state_msg, |this, msg| {
 6542                    this.entry(msg, None, {
 6543                        let weak_editor = weak_editor.clone();
 6544                        let breakpoint = breakpoint.clone();
 6545                        move |_window, cx| {
 6546                            weak_editor
 6547                                .update(cx, |this, cx| {
 6548                                    this.edit_breakpoint_at_anchor(
 6549                                        anchor,
 6550                                        breakpoint.as_ref().clone(),
 6551                                        BreakpointEditAction::InvertState,
 6552                                        cx,
 6553                                    );
 6554                                })
 6555                                .log_err();
 6556                        }
 6557                    })
 6558                })
 6559                .entry(set_breakpoint_msg, None, {
 6560                    let weak_editor = weak_editor.clone();
 6561                    let breakpoint = breakpoint.clone();
 6562                    move |_window, cx| {
 6563                        weak_editor
 6564                            .update(cx, |this, cx| {
 6565                                this.edit_breakpoint_at_anchor(
 6566                                    anchor,
 6567                                    breakpoint.as_ref().clone(),
 6568                                    BreakpointEditAction::Toggle,
 6569                                    cx,
 6570                                );
 6571                            })
 6572                            .log_err();
 6573                    }
 6574                })
 6575                .entry(log_breakpoint_msg, None, {
 6576                    let breakpoint = breakpoint.clone();
 6577                    let weak_editor = weak_editor.clone();
 6578                    move |window, cx| {
 6579                        weak_editor
 6580                            .update(cx, |this, cx| {
 6581                                this.add_edit_breakpoint_block(
 6582                                    anchor,
 6583                                    breakpoint.as_ref(),
 6584                                    BreakpointPromptEditAction::Log,
 6585                                    window,
 6586                                    cx,
 6587                                );
 6588                            })
 6589                            .log_err();
 6590                    }
 6591                })
 6592                .entry(condition_breakpoint_msg, None, {
 6593                    let breakpoint = breakpoint.clone();
 6594                    let weak_editor = weak_editor.clone();
 6595                    move |window, cx| {
 6596                        weak_editor
 6597                            .update(cx, |this, cx| {
 6598                                this.add_edit_breakpoint_block(
 6599                                    anchor,
 6600                                    breakpoint.as_ref(),
 6601                                    BreakpointPromptEditAction::Condition,
 6602                                    window,
 6603                                    cx,
 6604                                );
 6605                            })
 6606                            .log_err();
 6607                    }
 6608                })
 6609                .entry(hit_condition_breakpoint_msg, None, move |window, cx| {
 6610                    weak_editor
 6611                        .update(cx, |this, cx| {
 6612                            this.add_edit_breakpoint_block(
 6613                                anchor,
 6614                                breakpoint.as_ref(),
 6615                                BreakpointPromptEditAction::HitCondition,
 6616                                window,
 6617                                cx,
 6618                            );
 6619                        })
 6620                        .log_err();
 6621                })
 6622        })
 6623    }
 6624
 6625    fn render_breakpoint(
 6626        &self,
 6627        position: Anchor,
 6628        row: DisplayRow,
 6629        breakpoint: &Breakpoint,
 6630        cx: &mut Context<Self>,
 6631    ) -> IconButton {
 6632        let (color, icon) = {
 6633            let icon = match (&breakpoint.message.is_some(), breakpoint.is_disabled()) {
 6634                (false, false) => ui::IconName::DebugBreakpoint,
 6635                (true, false) => ui::IconName::DebugLogBreakpoint,
 6636                (false, true) => ui::IconName::DebugDisabledBreakpoint,
 6637                (true, true) => ui::IconName::DebugDisabledLogBreakpoint,
 6638            };
 6639
 6640            let color = if self
 6641                .gutter_breakpoint_indicator
 6642                .0
 6643                .is_some_and(|(point, is_visible)| is_visible && point.row() == row)
 6644            {
 6645                Color::Hint
 6646            } else {
 6647                Color::Debugger
 6648            };
 6649
 6650            (color, icon)
 6651        };
 6652
 6653        let breakpoint = Arc::from(breakpoint.clone());
 6654
 6655        IconButton::new(("breakpoint_indicator", row.0 as usize), icon)
 6656            .icon_size(IconSize::XSmall)
 6657            .size(ui::ButtonSize::None)
 6658            .icon_color(color)
 6659            .style(ButtonStyle::Transparent)
 6660            .on_click(cx.listener({
 6661                let breakpoint = breakpoint.clone();
 6662
 6663                move |editor, event: &ClickEvent, window, cx| {
 6664                    let edit_action = if event.modifiers().platform || breakpoint.is_disabled() {
 6665                        BreakpointEditAction::InvertState
 6666                    } else {
 6667                        BreakpointEditAction::Toggle
 6668                    };
 6669
 6670                    window.focus(&editor.focus_handle(cx));
 6671                    editor.edit_breakpoint_at_anchor(
 6672                        position,
 6673                        breakpoint.as_ref().clone(),
 6674                        edit_action,
 6675                        cx,
 6676                    );
 6677                }
 6678            }))
 6679            .on_right_click(cx.listener(move |editor, event: &ClickEvent, window, cx| {
 6680                editor.set_breakpoint_context_menu(
 6681                    row,
 6682                    Some(position),
 6683                    event.down.position,
 6684                    window,
 6685                    cx,
 6686                );
 6687            }))
 6688    }
 6689
 6690    fn build_tasks_context(
 6691        project: &Entity<Project>,
 6692        buffer: &Entity<Buffer>,
 6693        buffer_row: u32,
 6694        tasks: &Arc<RunnableTasks>,
 6695        cx: &mut Context<Self>,
 6696    ) -> Task<Option<task::TaskContext>> {
 6697        let position = Point::new(buffer_row, tasks.column);
 6698        let range_start = buffer.read(cx).anchor_at(position, Bias::Right);
 6699        let location = Location {
 6700            buffer: buffer.clone(),
 6701            range: range_start..range_start,
 6702        };
 6703        // Fill in the environmental variables from the tree-sitter captures
 6704        let mut captured_task_variables = TaskVariables::default();
 6705        for (capture_name, value) in tasks.extra_variables.clone() {
 6706            captured_task_variables.insert(
 6707                task::VariableName::Custom(capture_name.into()),
 6708                value.clone(),
 6709            );
 6710        }
 6711        project.update(cx, |project, cx| {
 6712            project.task_store().update(cx, |task_store, cx| {
 6713                task_store.task_context_for_location(captured_task_variables, location, cx)
 6714            })
 6715        })
 6716    }
 6717
 6718    pub fn spawn_nearest_task(
 6719        &mut self,
 6720        action: &SpawnNearestTask,
 6721        window: &mut Window,
 6722        cx: &mut Context<Self>,
 6723    ) {
 6724        let Some((workspace, _)) = self.workspace.clone() else {
 6725            return;
 6726        };
 6727        let Some(project) = self.project.clone() else {
 6728            return;
 6729        };
 6730
 6731        // Try to find a closest, enclosing node using tree-sitter that has a
 6732        // task
 6733        let Some((buffer, buffer_row, tasks)) = self
 6734            .find_enclosing_node_task(cx)
 6735            // Or find the task that's closest in row-distance.
 6736            .or_else(|| self.find_closest_task(cx))
 6737        else {
 6738            return;
 6739        };
 6740
 6741        let reveal_strategy = action.reveal;
 6742        let task_context = Self::build_tasks_context(&project, &buffer, buffer_row, &tasks, cx);
 6743        cx.spawn_in(window, async move |_, cx| {
 6744            let context = task_context.await?;
 6745            let (task_source_kind, mut resolved_task) = tasks.resolve(&context).next()?;
 6746
 6747            let resolved = resolved_task.resolved.as_mut()?;
 6748            resolved.reveal = reveal_strategy;
 6749
 6750            workspace
 6751                .update(cx, |workspace, cx| {
 6752                    workspace::tasks::schedule_resolved_task(
 6753                        workspace,
 6754                        task_source_kind,
 6755                        resolved_task,
 6756                        false,
 6757                        cx,
 6758                    );
 6759                })
 6760                .ok()
 6761        })
 6762        .detach();
 6763    }
 6764
 6765    fn find_closest_task(
 6766        &mut self,
 6767        cx: &mut Context<Self>,
 6768    ) -> Option<(Entity<Buffer>, u32, Arc<RunnableTasks>)> {
 6769        let cursor_row = self.selections.newest_adjusted(cx).head().row;
 6770
 6771        let ((buffer_id, row), tasks) = self
 6772            .tasks
 6773            .iter()
 6774            .min_by_key(|((_, row), _)| cursor_row.abs_diff(*row))?;
 6775
 6776        let buffer = self.buffer.read(cx).buffer(*buffer_id)?;
 6777        let tasks = Arc::new(tasks.to_owned());
 6778        Some((buffer, *row, tasks))
 6779    }
 6780
 6781    fn find_enclosing_node_task(
 6782        &mut self,
 6783        cx: &mut Context<Self>,
 6784    ) -> Option<(Entity<Buffer>, u32, Arc<RunnableTasks>)> {
 6785        let snapshot = self.buffer.read(cx).snapshot(cx);
 6786        let offset = self.selections.newest::<usize>(cx).head();
 6787        let excerpt = snapshot.excerpt_containing(offset..offset)?;
 6788        let buffer_id = excerpt.buffer().remote_id();
 6789
 6790        let layer = excerpt.buffer().syntax_layer_at(offset)?;
 6791        let mut cursor = layer.node().walk();
 6792
 6793        while cursor.goto_first_child_for_byte(offset).is_some() {
 6794            if cursor.node().end_byte() == offset {
 6795                cursor.goto_next_sibling();
 6796            }
 6797        }
 6798
 6799        // Ascend to the smallest ancestor that contains the range and has a task.
 6800        loop {
 6801            let node = cursor.node();
 6802            let node_range = node.byte_range();
 6803            let symbol_start_row = excerpt.buffer().offset_to_point(node.start_byte()).row;
 6804
 6805            // Check if this node contains our offset
 6806            if node_range.start <= offset && node_range.end >= offset {
 6807                // If it contains offset, check for task
 6808                if let Some(tasks) = self.tasks.get(&(buffer_id, symbol_start_row)) {
 6809                    let buffer = self.buffer.read(cx).buffer(buffer_id)?;
 6810                    return Some((buffer, symbol_start_row, Arc::new(tasks.to_owned())));
 6811                }
 6812            }
 6813
 6814            if !cursor.goto_parent() {
 6815                break;
 6816            }
 6817        }
 6818        None
 6819    }
 6820
 6821    fn render_run_indicator(
 6822        &self,
 6823        _style: &EditorStyle,
 6824        is_active: bool,
 6825        row: DisplayRow,
 6826        breakpoint: Option<(Anchor, Breakpoint)>,
 6827        cx: &mut Context<Self>,
 6828    ) -> IconButton {
 6829        let color = Color::Muted;
 6830        let position = breakpoint.as_ref().map(|(anchor, _)| *anchor);
 6831
 6832        IconButton::new(("run_indicator", row.0 as usize), ui::IconName::Play)
 6833            .shape(ui::IconButtonShape::Square)
 6834            .icon_size(IconSize::XSmall)
 6835            .icon_color(color)
 6836            .toggle_state(is_active)
 6837            .on_click(cx.listener(move |editor, _e, window, cx| {
 6838                window.focus(&editor.focus_handle(cx));
 6839                editor.toggle_code_actions(
 6840                    &ToggleCodeActions {
 6841                        deployed_from_indicator: Some(row),
 6842                    },
 6843                    window,
 6844                    cx,
 6845                );
 6846            }))
 6847            .on_right_click(cx.listener(move |editor, event: &ClickEvent, window, cx| {
 6848                editor.set_breakpoint_context_menu(row, position, event.down.position, window, cx);
 6849            }))
 6850    }
 6851
 6852    pub fn context_menu_visible(&self) -> bool {
 6853        !self.edit_prediction_preview_is_active()
 6854            && self
 6855                .context_menu
 6856                .borrow()
 6857                .as_ref()
 6858                .map_or(false, |menu| menu.visible())
 6859    }
 6860
 6861    fn context_menu_origin(&self) -> Option<ContextMenuOrigin> {
 6862        self.context_menu
 6863            .borrow()
 6864            .as_ref()
 6865            .map(|menu| menu.origin())
 6866    }
 6867
 6868    pub fn set_context_menu_options(&mut self, options: ContextMenuOptions) {
 6869        self.context_menu_options = Some(options);
 6870    }
 6871
 6872    const EDIT_PREDICTION_POPOVER_PADDING_X: Pixels = Pixels(24.);
 6873    const EDIT_PREDICTION_POPOVER_PADDING_Y: Pixels = Pixels(2.);
 6874
 6875    fn render_edit_prediction_popover(
 6876        &mut self,
 6877        text_bounds: &Bounds<Pixels>,
 6878        content_origin: gpui::Point<Pixels>,
 6879        editor_snapshot: &EditorSnapshot,
 6880        visible_row_range: Range<DisplayRow>,
 6881        scroll_top: f32,
 6882        scroll_bottom: f32,
 6883        line_layouts: &[LineWithInvisibles],
 6884        line_height: Pixels,
 6885        scroll_pixel_position: gpui::Point<Pixels>,
 6886        newest_selection_head: Option<DisplayPoint>,
 6887        editor_width: Pixels,
 6888        style: &EditorStyle,
 6889        window: &mut Window,
 6890        cx: &mut App,
 6891    ) -> Option<(AnyElement, gpui::Point<Pixels>)> {
 6892        let active_inline_completion = self.active_inline_completion.as_ref()?;
 6893
 6894        if self.edit_prediction_visible_in_cursor_popover(true) {
 6895            return None;
 6896        }
 6897
 6898        match &active_inline_completion.completion {
 6899            InlineCompletion::Move { target, .. } => {
 6900                let target_display_point = target.to_display_point(editor_snapshot);
 6901
 6902                if self.edit_prediction_requires_modifier() {
 6903                    if !self.edit_prediction_preview_is_active() {
 6904                        return None;
 6905                    }
 6906
 6907                    self.render_edit_prediction_modifier_jump_popover(
 6908                        text_bounds,
 6909                        content_origin,
 6910                        visible_row_range,
 6911                        line_layouts,
 6912                        line_height,
 6913                        scroll_pixel_position,
 6914                        newest_selection_head,
 6915                        target_display_point,
 6916                        window,
 6917                        cx,
 6918                    )
 6919                } else {
 6920                    self.render_edit_prediction_eager_jump_popover(
 6921                        text_bounds,
 6922                        content_origin,
 6923                        editor_snapshot,
 6924                        visible_row_range,
 6925                        scroll_top,
 6926                        scroll_bottom,
 6927                        line_height,
 6928                        scroll_pixel_position,
 6929                        target_display_point,
 6930                        editor_width,
 6931                        window,
 6932                        cx,
 6933                    )
 6934                }
 6935            }
 6936            InlineCompletion::Edit {
 6937                display_mode: EditDisplayMode::Inline,
 6938                ..
 6939            } => None,
 6940            InlineCompletion::Edit {
 6941                display_mode: EditDisplayMode::TabAccept,
 6942                edits,
 6943                ..
 6944            } => {
 6945                let range = &edits.first()?.0;
 6946                let target_display_point = range.end.to_display_point(editor_snapshot);
 6947
 6948                self.render_edit_prediction_end_of_line_popover(
 6949                    "Accept",
 6950                    editor_snapshot,
 6951                    visible_row_range,
 6952                    target_display_point,
 6953                    line_height,
 6954                    scroll_pixel_position,
 6955                    content_origin,
 6956                    editor_width,
 6957                    window,
 6958                    cx,
 6959                )
 6960            }
 6961            InlineCompletion::Edit {
 6962                edits,
 6963                edit_preview,
 6964                display_mode: EditDisplayMode::DiffPopover,
 6965                snapshot,
 6966            } => self.render_edit_prediction_diff_popover(
 6967                text_bounds,
 6968                content_origin,
 6969                editor_snapshot,
 6970                visible_row_range,
 6971                line_layouts,
 6972                line_height,
 6973                scroll_pixel_position,
 6974                newest_selection_head,
 6975                editor_width,
 6976                style,
 6977                edits,
 6978                edit_preview,
 6979                snapshot,
 6980                window,
 6981                cx,
 6982            ),
 6983        }
 6984    }
 6985
 6986    fn render_edit_prediction_modifier_jump_popover(
 6987        &mut self,
 6988        text_bounds: &Bounds<Pixels>,
 6989        content_origin: gpui::Point<Pixels>,
 6990        visible_row_range: Range<DisplayRow>,
 6991        line_layouts: &[LineWithInvisibles],
 6992        line_height: Pixels,
 6993        scroll_pixel_position: gpui::Point<Pixels>,
 6994        newest_selection_head: Option<DisplayPoint>,
 6995        target_display_point: DisplayPoint,
 6996        window: &mut Window,
 6997        cx: &mut App,
 6998    ) -> Option<(AnyElement, gpui::Point<Pixels>)> {
 6999        let scrolled_content_origin =
 7000            content_origin - gpui::Point::new(scroll_pixel_position.x, Pixels(0.0));
 7001
 7002        const SCROLL_PADDING_Y: Pixels = px(12.);
 7003
 7004        if target_display_point.row() < visible_row_range.start {
 7005            return self.render_edit_prediction_scroll_popover(
 7006                |_| SCROLL_PADDING_Y,
 7007                IconName::ArrowUp,
 7008                visible_row_range,
 7009                line_layouts,
 7010                newest_selection_head,
 7011                scrolled_content_origin,
 7012                window,
 7013                cx,
 7014            );
 7015        } else if target_display_point.row() >= visible_row_range.end {
 7016            return self.render_edit_prediction_scroll_popover(
 7017                |size| text_bounds.size.height - size.height - SCROLL_PADDING_Y,
 7018                IconName::ArrowDown,
 7019                visible_row_range,
 7020                line_layouts,
 7021                newest_selection_head,
 7022                scrolled_content_origin,
 7023                window,
 7024                cx,
 7025            );
 7026        }
 7027
 7028        const POLE_WIDTH: Pixels = px(2.);
 7029
 7030        let line_layout =
 7031            line_layouts.get(target_display_point.row().minus(visible_row_range.start) as usize)?;
 7032        let target_column = target_display_point.column() as usize;
 7033
 7034        let target_x = line_layout.x_for_index(target_column);
 7035        let target_y =
 7036            (target_display_point.row().as_f32() * line_height) - scroll_pixel_position.y;
 7037
 7038        let flag_on_right = target_x < text_bounds.size.width / 2.;
 7039
 7040        let mut border_color = Self::edit_prediction_callout_popover_border_color(cx);
 7041        border_color.l += 0.001;
 7042
 7043        let mut element = v_flex()
 7044            .items_end()
 7045            .when(flag_on_right, |el| el.items_start())
 7046            .child(if flag_on_right {
 7047                self.render_edit_prediction_line_popover("Jump", None, window, cx)?
 7048                    .rounded_bl(px(0.))
 7049                    .rounded_tl(px(0.))
 7050                    .border_l_2()
 7051                    .border_color(border_color)
 7052            } else {
 7053                self.render_edit_prediction_line_popover("Jump", None, window, cx)?
 7054                    .rounded_br(px(0.))
 7055                    .rounded_tr(px(0.))
 7056                    .border_r_2()
 7057                    .border_color(border_color)
 7058            })
 7059            .child(div().w(POLE_WIDTH).bg(border_color).h(line_height))
 7060            .into_any();
 7061
 7062        let size = element.layout_as_root(AvailableSpace::min_size(), window, cx);
 7063
 7064        let mut origin = scrolled_content_origin + point(target_x, target_y)
 7065            - point(
 7066                if flag_on_right {
 7067                    POLE_WIDTH
 7068                } else {
 7069                    size.width - POLE_WIDTH
 7070                },
 7071                size.height - line_height,
 7072            );
 7073
 7074        origin.x = origin.x.max(content_origin.x);
 7075
 7076        element.prepaint_at(origin, window, cx);
 7077
 7078        Some((element, origin))
 7079    }
 7080
 7081    fn render_edit_prediction_scroll_popover(
 7082        &mut self,
 7083        to_y: impl Fn(Size<Pixels>) -> Pixels,
 7084        scroll_icon: IconName,
 7085        visible_row_range: Range<DisplayRow>,
 7086        line_layouts: &[LineWithInvisibles],
 7087        newest_selection_head: Option<DisplayPoint>,
 7088        scrolled_content_origin: gpui::Point<Pixels>,
 7089        window: &mut Window,
 7090        cx: &mut App,
 7091    ) -> Option<(AnyElement, gpui::Point<Pixels>)> {
 7092        let mut element = self
 7093            .render_edit_prediction_line_popover("Scroll", Some(scroll_icon), window, cx)?
 7094            .into_any();
 7095
 7096        let size = element.layout_as_root(AvailableSpace::min_size(), window, cx);
 7097
 7098        let cursor = newest_selection_head?;
 7099        let cursor_row_layout =
 7100            line_layouts.get(cursor.row().minus(visible_row_range.start) as usize)?;
 7101        let cursor_column = cursor.column() as usize;
 7102
 7103        let cursor_character_x = cursor_row_layout.x_for_index(cursor_column);
 7104
 7105        let origin = scrolled_content_origin + point(cursor_character_x, to_y(size));
 7106
 7107        element.prepaint_at(origin, window, cx);
 7108        Some((element, origin))
 7109    }
 7110
 7111    fn render_edit_prediction_eager_jump_popover(
 7112        &mut self,
 7113        text_bounds: &Bounds<Pixels>,
 7114        content_origin: gpui::Point<Pixels>,
 7115        editor_snapshot: &EditorSnapshot,
 7116        visible_row_range: Range<DisplayRow>,
 7117        scroll_top: f32,
 7118        scroll_bottom: f32,
 7119        line_height: Pixels,
 7120        scroll_pixel_position: gpui::Point<Pixels>,
 7121        target_display_point: DisplayPoint,
 7122        editor_width: Pixels,
 7123        window: &mut Window,
 7124        cx: &mut App,
 7125    ) -> Option<(AnyElement, gpui::Point<Pixels>)> {
 7126        if target_display_point.row().as_f32() < scroll_top {
 7127            let mut element = self
 7128                .render_edit_prediction_line_popover(
 7129                    "Jump to Edit",
 7130                    Some(IconName::ArrowUp),
 7131                    window,
 7132                    cx,
 7133                )?
 7134                .into_any();
 7135
 7136            let size = element.layout_as_root(AvailableSpace::min_size(), window, cx);
 7137            let offset = point(
 7138                (text_bounds.size.width - size.width) / 2.,
 7139                Self::EDIT_PREDICTION_POPOVER_PADDING_Y,
 7140            );
 7141
 7142            let origin = text_bounds.origin + offset;
 7143            element.prepaint_at(origin, window, cx);
 7144            Some((element, origin))
 7145        } else if (target_display_point.row().as_f32() + 1.) > scroll_bottom {
 7146            let mut element = self
 7147                .render_edit_prediction_line_popover(
 7148                    "Jump to Edit",
 7149                    Some(IconName::ArrowDown),
 7150                    window,
 7151                    cx,
 7152                )?
 7153                .into_any();
 7154
 7155            let size = element.layout_as_root(AvailableSpace::min_size(), window, cx);
 7156            let offset = point(
 7157                (text_bounds.size.width - size.width) / 2.,
 7158                text_bounds.size.height - size.height - Self::EDIT_PREDICTION_POPOVER_PADDING_Y,
 7159            );
 7160
 7161            let origin = text_bounds.origin + offset;
 7162            element.prepaint_at(origin, window, cx);
 7163            Some((element, origin))
 7164        } else {
 7165            self.render_edit_prediction_end_of_line_popover(
 7166                "Jump to Edit",
 7167                editor_snapshot,
 7168                visible_row_range,
 7169                target_display_point,
 7170                line_height,
 7171                scroll_pixel_position,
 7172                content_origin,
 7173                editor_width,
 7174                window,
 7175                cx,
 7176            )
 7177        }
 7178    }
 7179
 7180    fn render_edit_prediction_end_of_line_popover(
 7181        self: &mut Editor,
 7182        label: &'static str,
 7183        editor_snapshot: &EditorSnapshot,
 7184        visible_row_range: Range<DisplayRow>,
 7185        target_display_point: DisplayPoint,
 7186        line_height: Pixels,
 7187        scroll_pixel_position: gpui::Point<Pixels>,
 7188        content_origin: gpui::Point<Pixels>,
 7189        editor_width: Pixels,
 7190        window: &mut Window,
 7191        cx: &mut App,
 7192    ) -> Option<(AnyElement, gpui::Point<Pixels>)> {
 7193        let target_line_end = DisplayPoint::new(
 7194            target_display_point.row(),
 7195            editor_snapshot.line_len(target_display_point.row()),
 7196        );
 7197
 7198        let mut element = self
 7199            .render_edit_prediction_line_popover(label, None, window, cx)?
 7200            .into_any();
 7201
 7202        let size = element.layout_as_root(AvailableSpace::min_size(), window, cx);
 7203
 7204        let line_origin = self.display_to_pixel_point(target_line_end, editor_snapshot, window)?;
 7205
 7206        let start_point = content_origin - point(scroll_pixel_position.x, Pixels::ZERO);
 7207        let mut origin = start_point
 7208            + line_origin
 7209            + point(Self::EDIT_PREDICTION_POPOVER_PADDING_X, Pixels::ZERO);
 7210        origin.x = origin.x.max(content_origin.x);
 7211
 7212        let max_x = content_origin.x + editor_width - size.width;
 7213
 7214        if origin.x > max_x {
 7215            let offset = line_height + Self::EDIT_PREDICTION_POPOVER_PADDING_Y;
 7216
 7217            let icon = if visible_row_range.contains(&(target_display_point.row() + 2)) {
 7218                origin.y += offset;
 7219                IconName::ArrowUp
 7220            } else {
 7221                origin.y -= offset;
 7222                IconName::ArrowDown
 7223            };
 7224
 7225            element = self
 7226                .render_edit_prediction_line_popover(label, Some(icon), window, cx)?
 7227                .into_any();
 7228
 7229            let size = element.layout_as_root(AvailableSpace::min_size(), window, cx);
 7230
 7231            origin.x = content_origin.x + editor_width - size.width - px(2.);
 7232        }
 7233
 7234        element.prepaint_at(origin, window, cx);
 7235        Some((element, origin))
 7236    }
 7237
 7238    fn render_edit_prediction_diff_popover(
 7239        self: &Editor,
 7240        text_bounds: &Bounds<Pixels>,
 7241        content_origin: gpui::Point<Pixels>,
 7242        editor_snapshot: &EditorSnapshot,
 7243        visible_row_range: Range<DisplayRow>,
 7244        line_layouts: &[LineWithInvisibles],
 7245        line_height: Pixels,
 7246        scroll_pixel_position: gpui::Point<Pixels>,
 7247        newest_selection_head: Option<DisplayPoint>,
 7248        editor_width: Pixels,
 7249        style: &EditorStyle,
 7250        edits: &Vec<(Range<Anchor>, String)>,
 7251        edit_preview: &Option<language::EditPreview>,
 7252        snapshot: &language::BufferSnapshot,
 7253        window: &mut Window,
 7254        cx: &mut App,
 7255    ) -> Option<(AnyElement, gpui::Point<Pixels>)> {
 7256        let edit_start = edits
 7257            .first()
 7258            .unwrap()
 7259            .0
 7260            .start
 7261            .to_display_point(editor_snapshot);
 7262        let edit_end = edits
 7263            .last()
 7264            .unwrap()
 7265            .0
 7266            .end
 7267            .to_display_point(editor_snapshot);
 7268
 7269        let is_visible = visible_row_range.contains(&edit_start.row())
 7270            || visible_row_range.contains(&edit_end.row());
 7271        if !is_visible {
 7272            return None;
 7273        }
 7274
 7275        let highlighted_edits =
 7276            crate::inline_completion_edit_text(&snapshot, edits, edit_preview.as_ref()?, false, cx);
 7277
 7278        let styled_text = highlighted_edits.to_styled_text(&style.text);
 7279        let line_count = highlighted_edits.text.lines().count();
 7280
 7281        const BORDER_WIDTH: Pixels = px(1.);
 7282
 7283        let keybind = self.render_edit_prediction_accept_keybind(window, cx);
 7284        let has_keybind = keybind.is_some();
 7285
 7286        let mut element = h_flex()
 7287            .items_start()
 7288            .child(
 7289                h_flex()
 7290                    .bg(cx.theme().colors().editor_background)
 7291                    .border(BORDER_WIDTH)
 7292                    .shadow_sm()
 7293                    .border_color(cx.theme().colors().border)
 7294                    .rounded_l_lg()
 7295                    .when(line_count > 1, |el| el.rounded_br_lg())
 7296                    .pr_1()
 7297                    .child(styled_text),
 7298            )
 7299            .child(
 7300                h_flex()
 7301                    .h(line_height + BORDER_WIDTH * 2.)
 7302                    .px_1p5()
 7303                    .gap_1()
 7304                    // Workaround: For some reason, there's a gap if we don't do this
 7305                    .ml(-BORDER_WIDTH)
 7306                    .shadow(smallvec![gpui::BoxShadow {
 7307                        color: gpui::black().opacity(0.05),
 7308                        offset: point(px(1.), px(1.)),
 7309                        blur_radius: px(2.),
 7310                        spread_radius: px(0.),
 7311                    }])
 7312                    .bg(Editor::edit_prediction_line_popover_bg_color(cx))
 7313                    .border(BORDER_WIDTH)
 7314                    .border_color(cx.theme().colors().border)
 7315                    .rounded_r_lg()
 7316                    .id("edit_prediction_diff_popover_keybind")
 7317                    .when(!has_keybind, |el| {
 7318                        let status_colors = cx.theme().status();
 7319
 7320                        el.bg(status_colors.error_background)
 7321                            .border_color(status_colors.error.opacity(0.6))
 7322                            .child(Icon::new(IconName::Info).color(Color::Error))
 7323                            .cursor_default()
 7324                            .hoverable_tooltip(move |_window, cx| {
 7325                                cx.new(|_| MissingEditPredictionKeybindingTooltip).into()
 7326                            })
 7327                    })
 7328                    .children(keybind),
 7329            )
 7330            .into_any();
 7331
 7332        let longest_row =
 7333            editor_snapshot.longest_row_in_range(edit_start.row()..edit_end.row() + 1);
 7334        let longest_line_width = if visible_row_range.contains(&longest_row) {
 7335            line_layouts[(longest_row.0 - visible_row_range.start.0) as usize].width
 7336        } else {
 7337            layout_line(
 7338                longest_row,
 7339                editor_snapshot,
 7340                style,
 7341                editor_width,
 7342                |_| false,
 7343                window,
 7344                cx,
 7345            )
 7346            .width
 7347        };
 7348
 7349        let viewport_bounds =
 7350            Bounds::new(Default::default(), window.viewport_size()).extend(Edges {
 7351                right: -EditorElement::SCROLLBAR_WIDTH,
 7352                ..Default::default()
 7353            });
 7354
 7355        let x_after_longest =
 7356            text_bounds.origin.x + longest_line_width + Self::EDIT_PREDICTION_POPOVER_PADDING_X
 7357                - scroll_pixel_position.x;
 7358
 7359        let element_bounds = element.layout_as_root(AvailableSpace::min_size(), window, cx);
 7360
 7361        // Fully visible if it can be displayed within the window (allow overlapping other
 7362        // panes). However, this is only allowed if the popover starts within text_bounds.
 7363        let can_position_to_the_right = x_after_longest < text_bounds.right()
 7364            && x_after_longest + element_bounds.width < viewport_bounds.right();
 7365
 7366        let mut origin = if can_position_to_the_right {
 7367            point(
 7368                x_after_longest,
 7369                text_bounds.origin.y + edit_start.row().as_f32() * line_height
 7370                    - scroll_pixel_position.y,
 7371            )
 7372        } else {
 7373            let cursor_row = newest_selection_head.map(|head| head.row());
 7374            let above_edit = edit_start
 7375                .row()
 7376                .0
 7377                .checked_sub(line_count as u32)
 7378                .map(DisplayRow);
 7379            let below_edit = Some(edit_end.row() + 1);
 7380            let above_cursor =
 7381                cursor_row.and_then(|row| row.0.checked_sub(line_count as u32).map(DisplayRow));
 7382            let below_cursor = cursor_row.map(|cursor_row| cursor_row + 1);
 7383
 7384            // Place the edit popover adjacent to the edit if there is a location
 7385            // available that is onscreen and does not obscure the cursor. Otherwise,
 7386            // place it adjacent to the cursor.
 7387            let row_target = [above_edit, below_edit, above_cursor, below_cursor]
 7388                .into_iter()
 7389                .flatten()
 7390                .find(|&start_row| {
 7391                    let end_row = start_row + line_count as u32;
 7392                    visible_row_range.contains(&start_row)
 7393                        && visible_row_range.contains(&end_row)
 7394                        && cursor_row.map_or(true, |cursor_row| {
 7395                            !((start_row..end_row).contains(&cursor_row))
 7396                        })
 7397                })?;
 7398
 7399            content_origin
 7400                + point(
 7401                    -scroll_pixel_position.x,
 7402                    row_target.as_f32() * line_height - scroll_pixel_position.y,
 7403                )
 7404        };
 7405
 7406        origin.x -= BORDER_WIDTH;
 7407
 7408        window.defer_draw(element, origin, 1);
 7409
 7410        // Do not return an element, since it will already be drawn due to defer_draw.
 7411        None
 7412    }
 7413
 7414    fn edit_prediction_cursor_popover_height(&self) -> Pixels {
 7415        px(30.)
 7416    }
 7417
 7418    fn current_user_player_color(&self, cx: &mut App) -> PlayerColor {
 7419        if self.read_only(cx) {
 7420            cx.theme().players().read_only()
 7421        } else {
 7422            self.style.as_ref().unwrap().local_player
 7423        }
 7424    }
 7425
 7426    fn render_edit_prediction_accept_keybind(
 7427        &self,
 7428        window: &mut Window,
 7429        cx: &App,
 7430    ) -> Option<AnyElement> {
 7431        let accept_binding = self.accept_edit_prediction_keybind(window, cx);
 7432        let accept_keystroke = accept_binding.keystroke()?;
 7433
 7434        let is_platform_style_mac = PlatformStyle::platform() == PlatformStyle::Mac;
 7435
 7436        let modifiers_color = if accept_keystroke.modifiers == window.modifiers() {
 7437            Color::Accent
 7438        } else {
 7439            Color::Muted
 7440        };
 7441
 7442        h_flex()
 7443            .px_0p5()
 7444            .when(is_platform_style_mac, |parent| parent.gap_0p5())
 7445            .font(theme::ThemeSettings::get_global(cx).buffer_font.clone())
 7446            .text_size(TextSize::XSmall.rems(cx))
 7447            .child(h_flex().children(ui::render_modifiers(
 7448                &accept_keystroke.modifiers,
 7449                PlatformStyle::platform(),
 7450                Some(modifiers_color),
 7451                Some(IconSize::XSmall.rems().into()),
 7452                true,
 7453            )))
 7454            .when(is_platform_style_mac, |parent| {
 7455                parent.child(accept_keystroke.key.clone())
 7456            })
 7457            .when(!is_platform_style_mac, |parent| {
 7458                parent.child(
 7459                    Key::new(
 7460                        util::capitalize(&accept_keystroke.key),
 7461                        Some(Color::Default),
 7462                    )
 7463                    .size(Some(IconSize::XSmall.rems().into())),
 7464                )
 7465            })
 7466            .into_any()
 7467            .into()
 7468    }
 7469
 7470    fn render_edit_prediction_line_popover(
 7471        &self,
 7472        label: impl Into<SharedString>,
 7473        icon: Option<IconName>,
 7474        window: &mut Window,
 7475        cx: &App,
 7476    ) -> Option<Stateful<Div>> {
 7477        let padding_right = if icon.is_some() { px(4.) } else { px(8.) };
 7478
 7479        let keybind = self.render_edit_prediction_accept_keybind(window, cx);
 7480        let has_keybind = keybind.is_some();
 7481
 7482        let result = h_flex()
 7483            .id("ep-line-popover")
 7484            .py_0p5()
 7485            .pl_1()
 7486            .pr(padding_right)
 7487            .gap_1()
 7488            .rounded_md()
 7489            .border_1()
 7490            .bg(Self::edit_prediction_line_popover_bg_color(cx))
 7491            .border_color(Self::edit_prediction_callout_popover_border_color(cx))
 7492            .shadow_sm()
 7493            .when(!has_keybind, |el| {
 7494                let status_colors = cx.theme().status();
 7495
 7496                el.bg(status_colors.error_background)
 7497                    .border_color(status_colors.error.opacity(0.6))
 7498                    .pl_2()
 7499                    .child(Icon::new(IconName::ZedPredictError).color(Color::Error))
 7500                    .cursor_default()
 7501                    .hoverable_tooltip(move |_window, cx| {
 7502                        cx.new(|_| MissingEditPredictionKeybindingTooltip).into()
 7503                    })
 7504            })
 7505            .children(keybind)
 7506            .child(
 7507                Label::new(label)
 7508                    .size(LabelSize::Small)
 7509                    .when(!has_keybind, |el| {
 7510                        el.color(cx.theme().status().error.into()).strikethrough()
 7511                    }),
 7512            )
 7513            .when(!has_keybind, |el| {
 7514                el.child(
 7515                    h_flex().ml_1().child(
 7516                        Icon::new(IconName::Info)
 7517                            .size(IconSize::Small)
 7518                            .color(cx.theme().status().error.into()),
 7519                    ),
 7520                )
 7521            })
 7522            .when_some(icon, |element, icon| {
 7523                element.child(
 7524                    div()
 7525                        .mt(px(1.5))
 7526                        .child(Icon::new(icon).size(IconSize::Small)),
 7527                )
 7528            });
 7529
 7530        Some(result)
 7531    }
 7532
 7533    fn edit_prediction_line_popover_bg_color(cx: &App) -> Hsla {
 7534        let accent_color = cx.theme().colors().text_accent;
 7535        let editor_bg_color = cx.theme().colors().editor_background;
 7536        editor_bg_color.blend(accent_color.opacity(0.1))
 7537    }
 7538
 7539    fn edit_prediction_callout_popover_border_color(cx: &App) -> Hsla {
 7540        let accent_color = cx.theme().colors().text_accent;
 7541        let editor_bg_color = cx.theme().colors().editor_background;
 7542        editor_bg_color.blend(accent_color.opacity(0.6))
 7543    }
 7544
 7545    fn render_edit_prediction_cursor_popover(
 7546        &self,
 7547        min_width: Pixels,
 7548        max_width: Pixels,
 7549        cursor_point: Point,
 7550        style: &EditorStyle,
 7551        accept_keystroke: Option<&gpui::Keystroke>,
 7552        _window: &Window,
 7553        cx: &mut Context<Editor>,
 7554    ) -> Option<AnyElement> {
 7555        let provider = self.edit_prediction_provider.as_ref()?;
 7556
 7557        if provider.provider.needs_terms_acceptance(cx) {
 7558            return Some(
 7559                h_flex()
 7560                    .min_w(min_width)
 7561                    .flex_1()
 7562                    .px_2()
 7563                    .py_1()
 7564                    .gap_3()
 7565                    .elevation_2(cx)
 7566                    .hover(|style| style.bg(cx.theme().colors().element_hover))
 7567                    .id("accept-terms")
 7568                    .cursor_pointer()
 7569                    .on_mouse_down(MouseButton::Left, |_, window, _| window.prevent_default())
 7570                    .on_click(cx.listener(|this, _event, window, cx| {
 7571                        cx.stop_propagation();
 7572                        this.report_editor_event("Edit Prediction Provider ToS Clicked", None, cx);
 7573                        window.dispatch_action(
 7574                            zed_actions::OpenZedPredictOnboarding.boxed_clone(),
 7575                            cx,
 7576                        );
 7577                    }))
 7578                    .child(
 7579                        h_flex()
 7580                            .flex_1()
 7581                            .gap_2()
 7582                            .child(Icon::new(IconName::ZedPredict))
 7583                            .child(Label::new("Accept Terms of Service"))
 7584                            .child(div().w_full())
 7585                            .child(
 7586                                Icon::new(IconName::ArrowUpRight)
 7587                                    .color(Color::Muted)
 7588                                    .size(IconSize::Small),
 7589                            )
 7590                            .into_any_element(),
 7591                    )
 7592                    .into_any(),
 7593            );
 7594        }
 7595
 7596        let is_refreshing = provider.provider.is_refreshing(cx);
 7597
 7598        fn pending_completion_container() -> Div {
 7599            h_flex()
 7600                .h_full()
 7601                .flex_1()
 7602                .gap_2()
 7603                .child(Icon::new(IconName::ZedPredict))
 7604        }
 7605
 7606        let completion = match &self.active_inline_completion {
 7607            Some(prediction) => {
 7608                if !self.has_visible_completions_menu() {
 7609                    const RADIUS: Pixels = px(6.);
 7610                    const BORDER_WIDTH: Pixels = px(1.);
 7611
 7612                    return Some(
 7613                        h_flex()
 7614                            .elevation_2(cx)
 7615                            .border(BORDER_WIDTH)
 7616                            .border_color(cx.theme().colors().border)
 7617                            .when(accept_keystroke.is_none(), |el| {
 7618                                el.border_color(cx.theme().status().error)
 7619                            })
 7620                            .rounded(RADIUS)
 7621                            .rounded_tl(px(0.))
 7622                            .overflow_hidden()
 7623                            .child(div().px_1p5().child(match &prediction.completion {
 7624                                InlineCompletion::Move { target, snapshot } => {
 7625                                    use text::ToPoint as _;
 7626                                    if target.text_anchor.to_point(&snapshot).row > cursor_point.row
 7627                                    {
 7628                                        Icon::new(IconName::ZedPredictDown)
 7629                                    } else {
 7630                                        Icon::new(IconName::ZedPredictUp)
 7631                                    }
 7632                                }
 7633                                InlineCompletion::Edit { .. } => Icon::new(IconName::ZedPredict),
 7634                            }))
 7635                            .child(
 7636                                h_flex()
 7637                                    .gap_1()
 7638                                    .py_1()
 7639                                    .px_2()
 7640                                    .rounded_r(RADIUS - BORDER_WIDTH)
 7641                                    .border_l_1()
 7642                                    .border_color(cx.theme().colors().border)
 7643                                    .bg(Self::edit_prediction_line_popover_bg_color(cx))
 7644                                    .when(self.edit_prediction_preview.released_too_fast(), |el| {
 7645                                        el.child(
 7646                                            Label::new("Hold")
 7647                                                .size(LabelSize::Small)
 7648                                                .when(accept_keystroke.is_none(), |el| {
 7649                                                    el.strikethrough()
 7650                                                })
 7651                                                .line_height_style(LineHeightStyle::UiLabel),
 7652                                        )
 7653                                    })
 7654                                    .id("edit_prediction_cursor_popover_keybind")
 7655                                    .when(accept_keystroke.is_none(), |el| {
 7656                                        let status_colors = cx.theme().status();
 7657
 7658                                        el.bg(status_colors.error_background)
 7659                                            .border_color(status_colors.error.opacity(0.6))
 7660                                            .child(Icon::new(IconName::Info).color(Color::Error))
 7661                                            .cursor_default()
 7662                                            .hoverable_tooltip(move |_window, cx| {
 7663                                                cx.new(|_| MissingEditPredictionKeybindingTooltip)
 7664                                                    .into()
 7665                                            })
 7666                                    })
 7667                                    .when_some(
 7668                                        accept_keystroke.as_ref(),
 7669                                        |el, accept_keystroke| {
 7670                                            el.child(h_flex().children(ui::render_modifiers(
 7671                                                &accept_keystroke.modifiers,
 7672                                                PlatformStyle::platform(),
 7673                                                Some(Color::Default),
 7674                                                Some(IconSize::XSmall.rems().into()),
 7675                                                false,
 7676                                            )))
 7677                                        },
 7678                                    ),
 7679                            )
 7680                            .into_any(),
 7681                    );
 7682                }
 7683
 7684                self.render_edit_prediction_cursor_popover_preview(
 7685                    prediction,
 7686                    cursor_point,
 7687                    style,
 7688                    cx,
 7689                )?
 7690            }
 7691
 7692            None if is_refreshing => match &self.stale_inline_completion_in_menu {
 7693                Some(stale_completion) => self.render_edit_prediction_cursor_popover_preview(
 7694                    stale_completion,
 7695                    cursor_point,
 7696                    style,
 7697                    cx,
 7698                )?,
 7699
 7700                None => {
 7701                    pending_completion_container().child(Label::new("...").size(LabelSize::Small))
 7702                }
 7703            },
 7704
 7705            None => pending_completion_container().child(Label::new("No Prediction")),
 7706        };
 7707
 7708        let completion = if is_refreshing {
 7709            completion
 7710                .with_animation(
 7711                    "loading-completion",
 7712                    Animation::new(Duration::from_secs(2))
 7713                        .repeat()
 7714                        .with_easing(pulsating_between(0.4, 0.8)),
 7715                    |label, delta| label.opacity(delta),
 7716                )
 7717                .into_any_element()
 7718        } else {
 7719            completion.into_any_element()
 7720        };
 7721
 7722        let has_completion = self.active_inline_completion.is_some();
 7723
 7724        let is_platform_style_mac = PlatformStyle::platform() == PlatformStyle::Mac;
 7725        Some(
 7726            h_flex()
 7727                .min_w(min_width)
 7728                .max_w(max_width)
 7729                .flex_1()
 7730                .elevation_2(cx)
 7731                .border_color(cx.theme().colors().border)
 7732                .child(
 7733                    div()
 7734                        .flex_1()
 7735                        .py_1()
 7736                        .px_2()
 7737                        .overflow_hidden()
 7738                        .child(completion),
 7739                )
 7740                .when_some(accept_keystroke, |el, accept_keystroke| {
 7741                    if !accept_keystroke.modifiers.modified() {
 7742                        return el;
 7743                    }
 7744
 7745                    el.child(
 7746                        h_flex()
 7747                            .h_full()
 7748                            .border_l_1()
 7749                            .rounded_r_lg()
 7750                            .border_color(cx.theme().colors().border)
 7751                            .bg(Self::edit_prediction_line_popover_bg_color(cx))
 7752                            .gap_1()
 7753                            .py_1()
 7754                            .px_2()
 7755                            .child(
 7756                                h_flex()
 7757                                    .font(theme::ThemeSettings::get_global(cx).buffer_font.clone())
 7758                                    .when(is_platform_style_mac, |parent| parent.gap_1())
 7759                                    .child(h_flex().children(ui::render_modifiers(
 7760                                        &accept_keystroke.modifiers,
 7761                                        PlatformStyle::platform(),
 7762                                        Some(if !has_completion {
 7763                                            Color::Muted
 7764                                        } else {
 7765                                            Color::Default
 7766                                        }),
 7767                                        None,
 7768                                        false,
 7769                                    ))),
 7770                            )
 7771                            .child(Label::new("Preview").into_any_element())
 7772                            .opacity(if has_completion { 1.0 } else { 0.4 }),
 7773                    )
 7774                })
 7775                .into_any(),
 7776        )
 7777    }
 7778
 7779    fn render_edit_prediction_cursor_popover_preview(
 7780        &self,
 7781        completion: &InlineCompletionState,
 7782        cursor_point: Point,
 7783        style: &EditorStyle,
 7784        cx: &mut Context<Editor>,
 7785    ) -> Option<Div> {
 7786        use text::ToPoint as _;
 7787
 7788        fn render_relative_row_jump(
 7789            prefix: impl Into<String>,
 7790            current_row: u32,
 7791            target_row: u32,
 7792        ) -> Div {
 7793            let (row_diff, arrow) = if target_row < current_row {
 7794                (current_row - target_row, IconName::ArrowUp)
 7795            } else {
 7796                (target_row - current_row, IconName::ArrowDown)
 7797            };
 7798
 7799            h_flex()
 7800                .child(
 7801                    Label::new(format!("{}{}", prefix.into(), row_diff))
 7802                        .color(Color::Muted)
 7803                        .size(LabelSize::Small),
 7804                )
 7805                .child(Icon::new(arrow).color(Color::Muted).size(IconSize::Small))
 7806        }
 7807
 7808        match &completion.completion {
 7809            InlineCompletion::Move {
 7810                target, snapshot, ..
 7811            } => Some(
 7812                h_flex()
 7813                    .px_2()
 7814                    .gap_2()
 7815                    .flex_1()
 7816                    .child(
 7817                        if target.text_anchor.to_point(&snapshot).row > cursor_point.row {
 7818                            Icon::new(IconName::ZedPredictDown)
 7819                        } else {
 7820                            Icon::new(IconName::ZedPredictUp)
 7821                        },
 7822                    )
 7823                    .child(Label::new("Jump to Edit")),
 7824            ),
 7825
 7826            InlineCompletion::Edit {
 7827                edits,
 7828                edit_preview,
 7829                snapshot,
 7830                display_mode: _,
 7831            } => {
 7832                let first_edit_row = edits.first()?.0.start.text_anchor.to_point(&snapshot).row;
 7833
 7834                let (highlighted_edits, has_more_lines) = crate::inline_completion_edit_text(
 7835                    &snapshot,
 7836                    &edits,
 7837                    edit_preview.as_ref()?,
 7838                    true,
 7839                    cx,
 7840                )
 7841                .first_line_preview();
 7842
 7843                let styled_text = gpui::StyledText::new(highlighted_edits.text)
 7844                    .with_default_highlights(&style.text, highlighted_edits.highlights);
 7845
 7846                let preview = h_flex()
 7847                    .gap_1()
 7848                    .min_w_16()
 7849                    .child(styled_text)
 7850                    .when(has_more_lines, |parent| parent.child(""));
 7851
 7852                let left = if first_edit_row != cursor_point.row {
 7853                    render_relative_row_jump("", cursor_point.row, first_edit_row)
 7854                        .into_any_element()
 7855                } else {
 7856                    Icon::new(IconName::ZedPredict).into_any_element()
 7857                };
 7858
 7859                Some(
 7860                    h_flex()
 7861                        .h_full()
 7862                        .flex_1()
 7863                        .gap_2()
 7864                        .pr_1()
 7865                        .overflow_x_hidden()
 7866                        .font(theme::ThemeSettings::get_global(cx).buffer_font.clone())
 7867                        .child(left)
 7868                        .child(preview),
 7869                )
 7870            }
 7871        }
 7872    }
 7873
 7874    fn render_context_menu(
 7875        &self,
 7876        style: &EditorStyle,
 7877        max_height_in_lines: u32,
 7878        window: &mut Window,
 7879        cx: &mut Context<Editor>,
 7880    ) -> Option<AnyElement> {
 7881        let menu = self.context_menu.borrow();
 7882        let menu = menu.as_ref()?;
 7883        if !menu.visible() {
 7884            return None;
 7885        };
 7886        Some(menu.render(style, max_height_in_lines, window, cx))
 7887    }
 7888
 7889    fn render_context_menu_aside(
 7890        &mut self,
 7891        max_size: Size<Pixels>,
 7892        window: &mut Window,
 7893        cx: &mut Context<Editor>,
 7894    ) -> Option<AnyElement> {
 7895        self.context_menu.borrow_mut().as_mut().and_then(|menu| {
 7896            if menu.visible() {
 7897                menu.render_aside(self, max_size, window, cx)
 7898            } else {
 7899                None
 7900            }
 7901        })
 7902    }
 7903
 7904    fn hide_context_menu(
 7905        &mut self,
 7906        window: &mut Window,
 7907        cx: &mut Context<Self>,
 7908    ) -> Option<CodeContextMenu> {
 7909        cx.notify();
 7910        self.completion_tasks.clear();
 7911        let context_menu = self.context_menu.borrow_mut().take();
 7912        self.stale_inline_completion_in_menu.take();
 7913        self.update_visible_inline_completion(window, cx);
 7914        context_menu
 7915    }
 7916
 7917    fn show_snippet_choices(
 7918        &mut self,
 7919        choices: &Vec<String>,
 7920        selection: Range<Anchor>,
 7921        cx: &mut Context<Self>,
 7922    ) {
 7923        if selection.start.buffer_id.is_none() {
 7924            return;
 7925        }
 7926        let buffer_id = selection.start.buffer_id.unwrap();
 7927        let buffer = self.buffer().read(cx).buffer(buffer_id);
 7928        let id = post_inc(&mut self.next_completion_id);
 7929
 7930        if let Some(buffer) = buffer {
 7931            *self.context_menu.borrow_mut() = Some(CodeContextMenu::Completions(
 7932                CompletionsMenu::new_snippet_choices(id, true, choices, selection, buffer),
 7933            ));
 7934        }
 7935    }
 7936
 7937    pub fn insert_snippet(
 7938        &mut self,
 7939        insertion_ranges: &[Range<usize>],
 7940        snippet: Snippet,
 7941        window: &mut Window,
 7942        cx: &mut Context<Self>,
 7943    ) -> Result<()> {
 7944        struct Tabstop<T> {
 7945            is_end_tabstop: bool,
 7946            ranges: Vec<Range<T>>,
 7947            choices: Option<Vec<String>>,
 7948        }
 7949
 7950        let tabstops = self.buffer.update(cx, |buffer, cx| {
 7951            let snippet_text: Arc<str> = snippet.text.clone().into();
 7952            let edits = insertion_ranges
 7953                .iter()
 7954                .cloned()
 7955                .map(|range| (range, snippet_text.clone()));
 7956            buffer.edit(edits, Some(AutoindentMode::EachLine), cx);
 7957
 7958            let snapshot = &*buffer.read(cx);
 7959            let snippet = &snippet;
 7960            snippet
 7961                .tabstops
 7962                .iter()
 7963                .map(|tabstop| {
 7964                    let is_end_tabstop = tabstop.ranges.first().map_or(false, |tabstop| {
 7965                        tabstop.is_empty() && tabstop.start == snippet.text.len() as isize
 7966                    });
 7967                    let mut tabstop_ranges = tabstop
 7968                        .ranges
 7969                        .iter()
 7970                        .flat_map(|tabstop_range| {
 7971                            let mut delta = 0_isize;
 7972                            insertion_ranges.iter().map(move |insertion_range| {
 7973                                let insertion_start = insertion_range.start as isize + delta;
 7974                                delta +=
 7975                                    snippet.text.len() as isize - insertion_range.len() as isize;
 7976
 7977                                let start = ((insertion_start + tabstop_range.start) as usize)
 7978                                    .min(snapshot.len());
 7979                                let end = ((insertion_start + tabstop_range.end) as usize)
 7980                                    .min(snapshot.len());
 7981                                snapshot.anchor_before(start)..snapshot.anchor_after(end)
 7982                            })
 7983                        })
 7984                        .collect::<Vec<_>>();
 7985                    tabstop_ranges.sort_unstable_by(|a, b| a.start.cmp(&b.start, snapshot));
 7986
 7987                    Tabstop {
 7988                        is_end_tabstop,
 7989                        ranges: tabstop_ranges,
 7990                        choices: tabstop.choices.clone(),
 7991                    }
 7992                })
 7993                .collect::<Vec<_>>()
 7994        });
 7995        if let Some(tabstop) = tabstops.first() {
 7996            self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 7997                s.select_ranges(tabstop.ranges.iter().cloned());
 7998            });
 7999
 8000            if let Some(choices) = &tabstop.choices {
 8001                if let Some(selection) = tabstop.ranges.first() {
 8002                    self.show_snippet_choices(choices, selection.clone(), cx)
 8003                }
 8004            }
 8005
 8006            // If we're already at the last tabstop and it's at the end of the snippet,
 8007            // we're done, we don't need to keep the state around.
 8008            if !tabstop.is_end_tabstop {
 8009                let choices = tabstops
 8010                    .iter()
 8011                    .map(|tabstop| tabstop.choices.clone())
 8012                    .collect();
 8013
 8014                let ranges = tabstops
 8015                    .into_iter()
 8016                    .map(|tabstop| tabstop.ranges)
 8017                    .collect::<Vec<_>>();
 8018
 8019                self.snippet_stack.push(SnippetState {
 8020                    active_index: 0,
 8021                    ranges,
 8022                    choices,
 8023                });
 8024            }
 8025
 8026            // Check whether the just-entered snippet ends with an auto-closable bracket.
 8027            if self.autoclose_regions.is_empty() {
 8028                let snapshot = self.buffer.read(cx).snapshot(cx);
 8029                for selection in &mut self.selections.all::<Point>(cx) {
 8030                    let selection_head = selection.head();
 8031                    let Some(scope) = snapshot.language_scope_at(selection_head) else {
 8032                        continue;
 8033                    };
 8034
 8035                    let mut bracket_pair = None;
 8036                    let next_chars = snapshot.chars_at(selection_head).collect::<String>();
 8037                    let prev_chars = snapshot
 8038                        .reversed_chars_at(selection_head)
 8039                        .collect::<String>();
 8040                    for (pair, enabled) in scope.brackets() {
 8041                        if enabled
 8042                            && pair.close
 8043                            && prev_chars.starts_with(pair.start.as_str())
 8044                            && next_chars.starts_with(pair.end.as_str())
 8045                        {
 8046                            bracket_pair = Some(pair.clone());
 8047                            break;
 8048                        }
 8049                    }
 8050                    if let Some(pair) = bracket_pair {
 8051                        let snapshot_settings = snapshot.language_settings_at(selection_head, cx);
 8052                        let autoclose_enabled =
 8053                            self.use_autoclose && snapshot_settings.use_autoclose;
 8054                        if autoclose_enabled {
 8055                            let start = snapshot.anchor_after(selection_head);
 8056                            let end = snapshot.anchor_after(selection_head);
 8057                            self.autoclose_regions.push(AutocloseRegion {
 8058                                selection_id: selection.id,
 8059                                range: start..end,
 8060                                pair,
 8061                            });
 8062                        }
 8063                    }
 8064                }
 8065            }
 8066        }
 8067        Ok(())
 8068    }
 8069
 8070    pub fn move_to_next_snippet_tabstop(
 8071        &mut self,
 8072        window: &mut Window,
 8073        cx: &mut Context<Self>,
 8074    ) -> bool {
 8075        self.move_to_snippet_tabstop(Bias::Right, window, cx)
 8076    }
 8077
 8078    pub fn move_to_prev_snippet_tabstop(
 8079        &mut self,
 8080        window: &mut Window,
 8081        cx: &mut Context<Self>,
 8082    ) -> bool {
 8083        self.move_to_snippet_tabstop(Bias::Left, window, cx)
 8084    }
 8085
 8086    pub fn move_to_snippet_tabstop(
 8087        &mut self,
 8088        bias: Bias,
 8089        window: &mut Window,
 8090        cx: &mut Context<Self>,
 8091    ) -> bool {
 8092        if let Some(mut snippet) = self.snippet_stack.pop() {
 8093            match bias {
 8094                Bias::Left => {
 8095                    if snippet.active_index > 0 {
 8096                        snippet.active_index -= 1;
 8097                    } else {
 8098                        self.snippet_stack.push(snippet);
 8099                        return false;
 8100                    }
 8101                }
 8102                Bias::Right => {
 8103                    if snippet.active_index + 1 < snippet.ranges.len() {
 8104                        snippet.active_index += 1;
 8105                    } else {
 8106                        self.snippet_stack.push(snippet);
 8107                        return false;
 8108                    }
 8109                }
 8110            }
 8111            if let Some(current_ranges) = snippet.ranges.get(snippet.active_index) {
 8112                self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8113                    s.select_anchor_ranges(current_ranges.iter().cloned())
 8114                });
 8115
 8116                if let Some(choices) = &snippet.choices[snippet.active_index] {
 8117                    if let Some(selection) = current_ranges.first() {
 8118                        self.show_snippet_choices(&choices, selection.clone(), cx);
 8119                    }
 8120                }
 8121
 8122                // If snippet state is not at the last tabstop, push it back on the stack
 8123                if snippet.active_index + 1 < snippet.ranges.len() {
 8124                    self.snippet_stack.push(snippet);
 8125                }
 8126                return true;
 8127            }
 8128        }
 8129
 8130        false
 8131    }
 8132
 8133    pub fn clear(&mut self, window: &mut Window, cx: &mut Context<Self>) {
 8134        self.transact(window, cx, |this, window, cx| {
 8135            this.select_all(&SelectAll, window, cx);
 8136            this.insert("", window, cx);
 8137        });
 8138    }
 8139
 8140    pub fn backspace(&mut self, _: &Backspace, window: &mut Window, cx: &mut Context<Self>) {
 8141        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
 8142        self.transact(window, cx, |this, window, cx| {
 8143            this.select_autoclose_pair(window, cx);
 8144            let mut linked_ranges = HashMap::<_, Vec<_>>::default();
 8145            if !this.linked_edit_ranges.is_empty() {
 8146                let selections = this.selections.all::<MultiBufferPoint>(cx);
 8147                let snapshot = this.buffer.read(cx).snapshot(cx);
 8148
 8149                for selection in selections.iter() {
 8150                    let selection_start = snapshot.anchor_before(selection.start).text_anchor;
 8151                    let selection_end = snapshot.anchor_after(selection.end).text_anchor;
 8152                    if selection_start.buffer_id != selection_end.buffer_id {
 8153                        continue;
 8154                    }
 8155                    if let Some(ranges) =
 8156                        this.linked_editing_ranges_for(selection_start..selection_end, cx)
 8157                    {
 8158                        for (buffer, entries) in ranges {
 8159                            linked_ranges.entry(buffer).or_default().extend(entries);
 8160                        }
 8161                    }
 8162                }
 8163            }
 8164
 8165            let mut selections = this.selections.all::<MultiBufferPoint>(cx);
 8166            let display_map = this.display_map.update(cx, |map, cx| map.snapshot(cx));
 8167            for selection in &mut selections {
 8168                if selection.is_empty() {
 8169                    let old_head = selection.head();
 8170                    let mut new_head =
 8171                        movement::left(&display_map, old_head.to_display_point(&display_map))
 8172                            .to_point(&display_map);
 8173                    if let Some((buffer, line_buffer_range)) = display_map
 8174                        .buffer_snapshot
 8175                        .buffer_line_for_row(MultiBufferRow(old_head.row))
 8176                    {
 8177                        let indent_size = buffer.indent_size_for_line(line_buffer_range.start.row);
 8178                        let indent_len = match indent_size.kind {
 8179                            IndentKind::Space => {
 8180                                buffer.settings_at(line_buffer_range.start, cx).tab_size
 8181                            }
 8182                            IndentKind::Tab => NonZeroU32::new(1).unwrap(),
 8183                        };
 8184                        if old_head.column <= indent_size.len && old_head.column > 0 {
 8185                            let indent_len = indent_len.get();
 8186                            new_head = cmp::min(
 8187                                new_head,
 8188                                MultiBufferPoint::new(
 8189                                    old_head.row,
 8190                                    ((old_head.column - 1) / indent_len) * indent_len,
 8191                                ),
 8192                            );
 8193                        }
 8194                    }
 8195
 8196                    selection.set_head(new_head, SelectionGoal::None);
 8197                }
 8198            }
 8199
 8200            this.signature_help_state.set_backspace_pressed(true);
 8201            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8202                s.select(selections)
 8203            });
 8204            this.insert("", window, cx);
 8205            let empty_str: Arc<str> = Arc::from("");
 8206            for (buffer, edits) in linked_ranges {
 8207                let snapshot = buffer.read(cx).snapshot();
 8208                use text::ToPoint as TP;
 8209
 8210                let edits = edits
 8211                    .into_iter()
 8212                    .map(|range| {
 8213                        let end_point = TP::to_point(&range.end, &snapshot);
 8214                        let mut start_point = TP::to_point(&range.start, &snapshot);
 8215
 8216                        if end_point == start_point {
 8217                            let offset = text::ToOffset::to_offset(&range.start, &snapshot)
 8218                                .saturating_sub(1);
 8219                            start_point =
 8220                                snapshot.clip_point(TP::to_point(&offset, &snapshot), Bias::Left);
 8221                        };
 8222
 8223                        (start_point..end_point, empty_str.clone())
 8224                    })
 8225                    .sorted_by_key(|(range, _)| range.start)
 8226                    .collect::<Vec<_>>();
 8227                buffer.update(cx, |this, cx| {
 8228                    this.edit(edits, None, cx);
 8229                })
 8230            }
 8231            this.refresh_inline_completion(true, false, window, cx);
 8232            linked_editing_ranges::refresh_linked_ranges(this, window, cx);
 8233        });
 8234    }
 8235
 8236    pub fn delete(&mut self, _: &Delete, window: &mut Window, cx: &mut Context<Self>) {
 8237        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
 8238        self.transact(window, cx, |this, window, cx| {
 8239            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8240                s.move_with(|map, selection| {
 8241                    if selection.is_empty() {
 8242                        let cursor = movement::right(map, selection.head());
 8243                        selection.end = cursor;
 8244                        selection.reversed = true;
 8245                        selection.goal = SelectionGoal::None;
 8246                    }
 8247                })
 8248            });
 8249            this.insert("", window, cx);
 8250            this.refresh_inline_completion(true, false, window, cx);
 8251        });
 8252    }
 8253
 8254    pub fn backtab(&mut self, _: &Backtab, window: &mut Window, cx: &mut Context<Self>) {
 8255        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
 8256        if self.move_to_prev_snippet_tabstop(window, cx) {
 8257            return;
 8258        }
 8259        self.outdent(&Outdent, window, cx);
 8260    }
 8261
 8262    pub fn tab(&mut self, _: &Tab, window: &mut Window, cx: &mut Context<Self>) {
 8263        if self.move_to_next_snippet_tabstop(window, cx) {
 8264            self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
 8265            return;
 8266        }
 8267        if self.read_only(cx) {
 8268            return;
 8269        }
 8270        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
 8271        let mut selections = self.selections.all_adjusted(cx);
 8272        let buffer = self.buffer.read(cx);
 8273        let snapshot = buffer.snapshot(cx);
 8274        let rows_iter = selections.iter().map(|s| s.head().row);
 8275        let suggested_indents = snapshot.suggested_indents(rows_iter, cx);
 8276
 8277        let mut edits = Vec::new();
 8278        let mut prev_edited_row = 0;
 8279        let mut row_delta = 0;
 8280        for selection in &mut selections {
 8281            if selection.start.row != prev_edited_row {
 8282                row_delta = 0;
 8283            }
 8284            prev_edited_row = selection.end.row;
 8285
 8286            // If the selection is non-empty, then increase the indentation of the selected lines.
 8287            if !selection.is_empty() {
 8288                row_delta =
 8289                    Self::indent_selection(buffer, &snapshot, selection, &mut edits, row_delta, cx);
 8290                continue;
 8291            }
 8292
 8293            // If the selection is empty and the cursor is in the leading whitespace before the
 8294            // suggested indentation, then auto-indent the line.
 8295            let cursor = selection.head();
 8296            let current_indent = snapshot.indent_size_for_line(MultiBufferRow(cursor.row));
 8297            if let Some(suggested_indent) =
 8298                suggested_indents.get(&MultiBufferRow(cursor.row)).copied()
 8299            {
 8300                if cursor.column < suggested_indent.len
 8301                    && cursor.column <= current_indent.len
 8302                    && current_indent.len <= suggested_indent.len
 8303                {
 8304                    selection.start = Point::new(cursor.row, suggested_indent.len);
 8305                    selection.end = selection.start;
 8306                    if row_delta == 0 {
 8307                        edits.extend(Buffer::edit_for_indent_size_adjustment(
 8308                            cursor.row,
 8309                            current_indent,
 8310                            suggested_indent,
 8311                        ));
 8312                        row_delta = suggested_indent.len - current_indent.len;
 8313                    }
 8314                    continue;
 8315                }
 8316            }
 8317
 8318            // Otherwise, insert a hard or soft tab.
 8319            let settings = buffer.language_settings_at(cursor, cx);
 8320            let tab_size = if settings.hard_tabs {
 8321                IndentSize::tab()
 8322            } else {
 8323                let tab_size = settings.tab_size.get();
 8324                let indent_remainder = snapshot
 8325                    .text_for_range(Point::new(cursor.row, 0)..cursor)
 8326                    .flat_map(str::chars)
 8327                    .fold(row_delta % tab_size, |counter: u32, c| {
 8328                        if c == '\t' {
 8329                            0
 8330                        } else {
 8331                            (counter + 1) % tab_size
 8332                        }
 8333                    });
 8334
 8335                let chars_to_next_tab_stop = tab_size - indent_remainder;
 8336                IndentSize::spaces(chars_to_next_tab_stop)
 8337            };
 8338            selection.start = Point::new(cursor.row, cursor.column + row_delta + tab_size.len);
 8339            selection.end = selection.start;
 8340            edits.push((cursor..cursor, tab_size.chars().collect::<String>()));
 8341            row_delta += tab_size.len;
 8342        }
 8343
 8344        self.transact(window, cx, |this, window, cx| {
 8345            this.buffer.update(cx, |b, cx| b.edit(edits, None, cx));
 8346            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8347                s.select(selections)
 8348            });
 8349            this.refresh_inline_completion(true, false, window, cx);
 8350        });
 8351    }
 8352
 8353    pub fn indent(&mut self, _: &Indent, window: &mut Window, cx: &mut Context<Self>) {
 8354        if self.read_only(cx) {
 8355            return;
 8356        }
 8357        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
 8358        let mut selections = self.selections.all::<Point>(cx);
 8359        let mut prev_edited_row = 0;
 8360        let mut row_delta = 0;
 8361        let mut edits = Vec::new();
 8362        let buffer = self.buffer.read(cx);
 8363        let snapshot = buffer.snapshot(cx);
 8364        for selection in &mut selections {
 8365            if selection.start.row != prev_edited_row {
 8366                row_delta = 0;
 8367            }
 8368            prev_edited_row = selection.end.row;
 8369
 8370            row_delta =
 8371                Self::indent_selection(buffer, &snapshot, selection, &mut edits, row_delta, cx);
 8372        }
 8373
 8374        self.transact(window, cx, |this, window, cx| {
 8375            this.buffer.update(cx, |b, cx| b.edit(edits, None, cx));
 8376            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8377                s.select(selections)
 8378            });
 8379        });
 8380    }
 8381
 8382    fn indent_selection(
 8383        buffer: &MultiBuffer,
 8384        snapshot: &MultiBufferSnapshot,
 8385        selection: &mut Selection<Point>,
 8386        edits: &mut Vec<(Range<Point>, String)>,
 8387        delta_for_start_row: u32,
 8388        cx: &App,
 8389    ) -> u32 {
 8390        let settings = buffer.language_settings_at(selection.start, cx);
 8391        let tab_size = settings.tab_size.get();
 8392        let indent_kind = if settings.hard_tabs {
 8393            IndentKind::Tab
 8394        } else {
 8395            IndentKind::Space
 8396        };
 8397        let mut start_row = selection.start.row;
 8398        let mut end_row = selection.end.row + 1;
 8399
 8400        // If a selection ends at the beginning of a line, don't indent
 8401        // that last line.
 8402        if selection.end.column == 0 && selection.end.row > selection.start.row {
 8403            end_row -= 1;
 8404        }
 8405
 8406        // Avoid re-indenting a row that has already been indented by a
 8407        // previous selection, but still update this selection's column
 8408        // to reflect that indentation.
 8409        if delta_for_start_row > 0 {
 8410            start_row += 1;
 8411            selection.start.column += delta_for_start_row;
 8412            if selection.end.row == selection.start.row {
 8413                selection.end.column += delta_for_start_row;
 8414            }
 8415        }
 8416
 8417        let mut delta_for_end_row = 0;
 8418        let has_multiple_rows = start_row + 1 != end_row;
 8419        for row in start_row..end_row {
 8420            let current_indent = snapshot.indent_size_for_line(MultiBufferRow(row));
 8421            let indent_delta = match (current_indent.kind, indent_kind) {
 8422                (IndentKind::Space, IndentKind::Space) => {
 8423                    let columns_to_next_tab_stop = tab_size - (current_indent.len % tab_size);
 8424                    IndentSize::spaces(columns_to_next_tab_stop)
 8425                }
 8426                (IndentKind::Tab, IndentKind::Space) => IndentSize::spaces(tab_size),
 8427                (_, IndentKind::Tab) => IndentSize::tab(),
 8428            };
 8429
 8430            let start = if has_multiple_rows || current_indent.len < selection.start.column {
 8431                0
 8432            } else {
 8433                selection.start.column
 8434            };
 8435            let row_start = Point::new(row, start);
 8436            edits.push((
 8437                row_start..row_start,
 8438                indent_delta.chars().collect::<String>(),
 8439            ));
 8440
 8441            // Update this selection's endpoints to reflect the indentation.
 8442            if row == selection.start.row {
 8443                selection.start.column += indent_delta.len;
 8444            }
 8445            if row == selection.end.row {
 8446                selection.end.column += indent_delta.len;
 8447                delta_for_end_row = indent_delta.len;
 8448            }
 8449        }
 8450
 8451        if selection.start.row == selection.end.row {
 8452            delta_for_start_row + delta_for_end_row
 8453        } else {
 8454            delta_for_end_row
 8455        }
 8456    }
 8457
 8458    pub fn outdent(&mut self, _: &Outdent, window: &mut Window, cx: &mut Context<Self>) {
 8459        if self.read_only(cx) {
 8460            return;
 8461        }
 8462        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
 8463        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 8464        let selections = self.selections.all::<Point>(cx);
 8465        let mut deletion_ranges = Vec::new();
 8466        let mut last_outdent = None;
 8467        {
 8468            let buffer = self.buffer.read(cx);
 8469            let snapshot = buffer.snapshot(cx);
 8470            for selection in &selections {
 8471                let settings = buffer.language_settings_at(selection.start, cx);
 8472                let tab_size = settings.tab_size.get();
 8473                let mut rows = selection.spanned_rows(false, &display_map);
 8474
 8475                // Avoid re-outdenting a row that has already been outdented by a
 8476                // previous selection.
 8477                if let Some(last_row) = last_outdent {
 8478                    if last_row == rows.start {
 8479                        rows.start = rows.start.next_row();
 8480                    }
 8481                }
 8482                let has_multiple_rows = rows.len() > 1;
 8483                for row in rows.iter_rows() {
 8484                    let indent_size = snapshot.indent_size_for_line(row);
 8485                    if indent_size.len > 0 {
 8486                        let deletion_len = match indent_size.kind {
 8487                            IndentKind::Space => {
 8488                                let columns_to_prev_tab_stop = indent_size.len % tab_size;
 8489                                if columns_to_prev_tab_stop == 0 {
 8490                                    tab_size
 8491                                } else {
 8492                                    columns_to_prev_tab_stop
 8493                                }
 8494                            }
 8495                            IndentKind::Tab => 1,
 8496                        };
 8497                        let start = if has_multiple_rows
 8498                            || deletion_len > selection.start.column
 8499                            || indent_size.len < selection.start.column
 8500                        {
 8501                            0
 8502                        } else {
 8503                            selection.start.column - deletion_len
 8504                        };
 8505                        deletion_ranges.push(
 8506                            Point::new(row.0, start)..Point::new(row.0, start + deletion_len),
 8507                        );
 8508                        last_outdent = Some(row);
 8509                    }
 8510                }
 8511            }
 8512        }
 8513
 8514        self.transact(window, cx, |this, window, cx| {
 8515            this.buffer.update(cx, |buffer, cx| {
 8516                let empty_str: Arc<str> = Arc::default();
 8517                buffer.edit(
 8518                    deletion_ranges
 8519                        .into_iter()
 8520                        .map(|range| (range, empty_str.clone())),
 8521                    None,
 8522                    cx,
 8523                );
 8524            });
 8525            let selections = this.selections.all::<usize>(cx);
 8526            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8527                s.select(selections)
 8528            });
 8529        });
 8530    }
 8531
 8532    pub fn autoindent(&mut self, _: &AutoIndent, window: &mut Window, cx: &mut Context<Self>) {
 8533        if self.read_only(cx) {
 8534            return;
 8535        }
 8536        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
 8537        let selections = self
 8538            .selections
 8539            .all::<usize>(cx)
 8540            .into_iter()
 8541            .map(|s| s.range());
 8542
 8543        self.transact(window, cx, |this, window, cx| {
 8544            this.buffer.update(cx, |buffer, cx| {
 8545                buffer.autoindent_ranges(selections, cx);
 8546            });
 8547            let selections = this.selections.all::<usize>(cx);
 8548            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8549                s.select(selections)
 8550            });
 8551        });
 8552    }
 8553
 8554    pub fn delete_line(&mut self, _: &DeleteLine, window: &mut Window, cx: &mut Context<Self>) {
 8555        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
 8556        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 8557        let selections = self.selections.all::<Point>(cx);
 8558
 8559        let mut new_cursors = Vec::new();
 8560        let mut edit_ranges = Vec::new();
 8561        let mut selections = selections.iter().peekable();
 8562        while let Some(selection) = selections.next() {
 8563            let mut rows = selection.spanned_rows(false, &display_map);
 8564            let goal_display_column = selection.head().to_display_point(&display_map).column();
 8565
 8566            // Accumulate contiguous regions of rows that we want to delete.
 8567            while let Some(next_selection) = selections.peek() {
 8568                let next_rows = next_selection.spanned_rows(false, &display_map);
 8569                if next_rows.start <= rows.end {
 8570                    rows.end = next_rows.end;
 8571                    selections.next().unwrap();
 8572                } else {
 8573                    break;
 8574                }
 8575            }
 8576
 8577            let buffer = &display_map.buffer_snapshot;
 8578            let mut edit_start = Point::new(rows.start.0, 0).to_offset(buffer);
 8579            let edit_end;
 8580            let cursor_buffer_row;
 8581            if buffer.max_point().row >= rows.end.0 {
 8582                // If there's a line after the range, delete the \n from the end of the row range
 8583                // and position the cursor on the next line.
 8584                edit_end = Point::new(rows.end.0, 0).to_offset(buffer);
 8585                cursor_buffer_row = rows.end;
 8586            } else {
 8587                // If there isn't a line after the range, delete the \n from the line before the
 8588                // start of the row range and position the cursor there.
 8589                edit_start = edit_start.saturating_sub(1);
 8590                edit_end = buffer.len();
 8591                cursor_buffer_row = rows.start.previous_row();
 8592            }
 8593
 8594            let mut cursor = Point::new(cursor_buffer_row.0, 0).to_display_point(&display_map);
 8595            *cursor.column_mut() =
 8596                cmp::min(goal_display_column, display_map.line_len(cursor.row()));
 8597
 8598            new_cursors.push((
 8599                selection.id,
 8600                buffer.anchor_after(cursor.to_point(&display_map)),
 8601            ));
 8602            edit_ranges.push(edit_start..edit_end);
 8603        }
 8604
 8605        self.transact(window, cx, |this, window, cx| {
 8606            let buffer = this.buffer.update(cx, |buffer, cx| {
 8607                let empty_str: Arc<str> = Arc::default();
 8608                buffer.edit(
 8609                    edit_ranges
 8610                        .into_iter()
 8611                        .map(|range| (range, empty_str.clone())),
 8612                    None,
 8613                    cx,
 8614                );
 8615                buffer.snapshot(cx)
 8616            });
 8617            let new_selections = new_cursors
 8618                .into_iter()
 8619                .map(|(id, cursor)| {
 8620                    let cursor = cursor.to_point(&buffer);
 8621                    Selection {
 8622                        id,
 8623                        start: cursor,
 8624                        end: cursor,
 8625                        reversed: false,
 8626                        goal: SelectionGoal::None,
 8627                    }
 8628                })
 8629                .collect();
 8630
 8631            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8632                s.select(new_selections);
 8633            });
 8634        });
 8635    }
 8636
 8637    pub fn join_lines_impl(
 8638        &mut self,
 8639        insert_whitespace: bool,
 8640        window: &mut Window,
 8641        cx: &mut Context<Self>,
 8642    ) {
 8643        if self.read_only(cx) {
 8644            return;
 8645        }
 8646        let mut row_ranges = Vec::<Range<MultiBufferRow>>::new();
 8647        for selection in self.selections.all::<Point>(cx) {
 8648            let start = MultiBufferRow(selection.start.row);
 8649            // Treat single line selections as if they include the next line. Otherwise this action
 8650            // would do nothing for single line selections individual cursors.
 8651            let end = if selection.start.row == selection.end.row {
 8652                MultiBufferRow(selection.start.row + 1)
 8653            } else {
 8654                MultiBufferRow(selection.end.row)
 8655            };
 8656
 8657            if let Some(last_row_range) = row_ranges.last_mut() {
 8658                if start <= last_row_range.end {
 8659                    last_row_range.end = end;
 8660                    continue;
 8661                }
 8662            }
 8663            row_ranges.push(start..end);
 8664        }
 8665
 8666        let snapshot = self.buffer.read(cx).snapshot(cx);
 8667        let mut cursor_positions = Vec::new();
 8668        for row_range in &row_ranges {
 8669            let anchor = snapshot.anchor_before(Point::new(
 8670                row_range.end.previous_row().0,
 8671                snapshot.line_len(row_range.end.previous_row()),
 8672            ));
 8673            cursor_positions.push(anchor..anchor);
 8674        }
 8675
 8676        self.transact(window, cx, |this, window, cx| {
 8677            for row_range in row_ranges.into_iter().rev() {
 8678                for row in row_range.iter_rows().rev() {
 8679                    let end_of_line = Point::new(row.0, snapshot.line_len(row));
 8680                    let next_line_row = row.next_row();
 8681                    let indent = snapshot.indent_size_for_line(next_line_row);
 8682                    let start_of_next_line = Point::new(next_line_row.0, indent.len);
 8683
 8684                    let replace =
 8685                        if snapshot.line_len(next_line_row) > indent.len && insert_whitespace {
 8686                            " "
 8687                        } else {
 8688                            ""
 8689                        };
 8690
 8691                    this.buffer.update(cx, |buffer, cx| {
 8692                        buffer.edit([(end_of_line..start_of_next_line, replace)], None, cx)
 8693                    });
 8694                }
 8695            }
 8696
 8697            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8698                s.select_anchor_ranges(cursor_positions)
 8699            });
 8700        });
 8701    }
 8702
 8703    pub fn join_lines(&mut self, _: &JoinLines, window: &mut Window, cx: &mut Context<Self>) {
 8704        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
 8705        self.join_lines_impl(true, window, cx);
 8706    }
 8707
 8708    pub fn sort_lines_case_sensitive(
 8709        &mut self,
 8710        _: &SortLinesCaseSensitive,
 8711        window: &mut Window,
 8712        cx: &mut Context<Self>,
 8713    ) {
 8714        self.manipulate_lines(window, cx, |lines| lines.sort())
 8715    }
 8716
 8717    pub fn sort_lines_case_insensitive(
 8718        &mut self,
 8719        _: &SortLinesCaseInsensitive,
 8720        window: &mut Window,
 8721        cx: &mut Context<Self>,
 8722    ) {
 8723        self.manipulate_lines(window, cx, |lines| {
 8724            lines.sort_by_key(|line| line.to_lowercase())
 8725        })
 8726    }
 8727
 8728    pub fn unique_lines_case_insensitive(
 8729        &mut self,
 8730        _: &UniqueLinesCaseInsensitive,
 8731        window: &mut Window,
 8732        cx: &mut Context<Self>,
 8733    ) {
 8734        self.manipulate_lines(window, cx, |lines| {
 8735            let mut seen = HashSet::default();
 8736            lines.retain(|line| seen.insert(line.to_lowercase()));
 8737        })
 8738    }
 8739
 8740    pub fn unique_lines_case_sensitive(
 8741        &mut self,
 8742        _: &UniqueLinesCaseSensitive,
 8743        window: &mut Window,
 8744        cx: &mut Context<Self>,
 8745    ) {
 8746        self.manipulate_lines(window, cx, |lines| {
 8747            let mut seen = HashSet::default();
 8748            lines.retain(|line| seen.insert(*line));
 8749        })
 8750    }
 8751
 8752    pub fn reload_file(&mut self, _: &ReloadFile, window: &mut Window, cx: &mut Context<Self>) {
 8753        let Some(project) = self.project.clone() else {
 8754            return;
 8755        };
 8756        self.reload(project, window, cx)
 8757            .detach_and_notify_err(window, cx);
 8758    }
 8759
 8760    pub fn restore_file(
 8761        &mut self,
 8762        _: &::git::RestoreFile,
 8763        window: &mut Window,
 8764        cx: &mut Context<Self>,
 8765    ) {
 8766        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
 8767        let mut buffer_ids = HashSet::default();
 8768        let snapshot = self.buffer().read(cx).snapshot(cx);
 8769        for selection in self.selections.all::<usize>(cx) {
 8770            buffer_ids.extend(snapshot.buffer_ids_for_range(selection.range()))
 8771        }
 8772
 8773        let buffer = self.buffer().read(cx);
 8774        let ranges = buffer_ids
 8775            .into_iter()
 8776            .flat_map(|buffer_id| buffer.excerpt_ranges_for_buffer(buffer_id, cx))
 8777            .collect::<Vec<_>>();
 8778
 8779        self.restore_hunks_in_ranges(ranges, window, cx);
 8780    }
 8781
 8782    pub fn git_restore(&mut self, _: &Restore, window: &mut Window, cx: &mut Context<Self>) {
 8783        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
 8784        let selections = self
 8785            .selections
 8786            .all(cx)
 8787            .into_iter()
 8788            .map(|s| s.range())
 8789            .collect();
 8790        self.restore_hunks_in_ranges(selections, window, cx);
 8791    }
 8792
 8793    pub fn restore_hunks_in_ranges(
 8794        &mut self,
 8795        ranges: Vec<Range<Point>>,
 8796        window: &mut Window,
 8797        cx: &mut Context<Editor>,
 8798    ) {
 8799        let mut revert_changes = HashMap::default();
 8800        let chunk_by = self
 8801            .snapshot(window, cx)
 8802            .hunks_for_ranges(ranges)
 8803            .into_iter()
 8804            .chunk_by(|hunk| hunk.buffer_id);
 8805        for (buffer_id, hunks) in &chunk_by {
 8806            let hunks = hunks.collect::<Vec<_>>();
 8807            for hunk in &hunks {
 8808                self.prepare_restore_change(&mut revert_changes, hunk, cx);
 8809            }
 8810            self.do_stage_or_unstage(false, buffer_id, hunks.into_iter(), cx);
 8811        }
 8812        drop(chunk_by);
 8813        if !revert_changes.is_empty() {
 8814            self.transact(window, cx, |editor, window, cx| {
 8815                editor.restore(revert_changes, window, cx);
 8816            });
 8817        }
 8818    }
 8819
 8820    pub fn open_active_item_in_terminal(
 8821        &mut self,
 8822        _: &OpenInTerminal,
 8823        window: &mut Window,
 8824        cx: &mut Context<Self>,
 8825    ) {
 8826        if let Some(working_directory) = self.active_excerpt(cx).and_then(|(_, buffer, _)| {
 8827            let project_path = buffer.read(cx).project_path(cx)?;
 8828            let project = self.project.as_ref()?.read(cx);
 8829            let entry = project.entry_for_path(&project_path, cx)?;
 8830            let parent = match &entry.canonical_path {
 8831                Some(canonical_path) => canonical_path.to_path_buf(),
 8832                None => project.absolute_path(&project_path, cx)?,
 8833            }
 8834            .parent()?
 8835            .to_path_buf();
 8836            Some(parent)
 8837        }) {
 8838            window.dispatch_action(OpenTerminal { working_directory }.boxed_clone(), cx);
 8839        }
 8840    }
 8841
 8842    fn set_breakpoint_context_menu(
 8843        &mut self,
 8844        display_row: DisplayRow,
 8845        position: Option<Anchor>,
 8846        clicked_point: gpui::Point<Pixels>,
 8847        window: &mut Window,
 8848        cx: &mut Context<Self>,
 8849    ) {
 8850        if !cx.has_flag::<Debugger>() {
 8851            return;
 8852        }
 8853        let source = self
 8854            .buffer
 8855            .read(cx)
 8856            .snapshot(cx)
 8857            .anchor_before(Point::new(display_row.0, 0u32));
 8858
 8859        let context_menu = self.breakpoint_context_menu(position.unwrap_or(source), window, cx);
 8860
 8861        self.mouse_context_menu = MouseContextMenu::pinned_to_editor(
 8862            self,
 8863            source,
 8864            clicked_point,
 8865            None,
 8866            context_menu,
 8867            window,
 8868            cx,
 8869        );
 8870    }
 8871
 8872    fn add_edit_breakpoint_block(
 8873        &mut self,
 8874        anchor: Anchor,
 8875        breakpoint: &Breakpoint,
 8876        edit_action: BreakpointPromptEditAction,
 8877        window: &mut Window,
 8878        cx: &mut Context<Self>,
 8879    ) {
 8880        let weak_editor = cx.weak_entity();
 8881        let bp_prompt = cx.new(|cx| {
 8882            BreakpointPromptEditor::new(
 8883                weak_editor,
 8884                anchor,
 8885                breakpoint.clone(),
 8886                edit_action,
 8887                window,
 8888                cx,
 8889            )
 8890        });
 8891
 8892        let height = bp_prompt.update(cx, |this, cx| {
 8893            this.prompt
 8894                .update(cx, |prompt, cx| prompt.max_point(cx).row().0 + 1 + 2)
 8895        });
 8896        let cloned_prompt = bp_prompt.clone();
 8897        let blocks = vec![BlockProperties {
 8898            style: BlockStyle::Sticky,
 8899            placement: BlockPlacement::Above(anchor),
 8900            height: Some(height),
 8901            render: Arc::new(move |cx| {
 8902                *cloned_prompt.read(cx).gutter_dimensions.lock() = *cx.gutter_dimensions;
 8903                cloned_prompt.clone().into_any_element()
 8904            }),
 8905            priority: 0,
 8906        }];
 8907
 8908        let focus_handle = bp_prompt.focus_handle(cx);
 8909        window.focus(&focus_handle);
 8910
 8911        let block_ids = self.insert_blocks(blocks, None, cx);
 8912        bp_prompt.update(cx, |prompt, _| {
 8913            prompt.add_block_ids(block_ids);
 8914        });
 8915    }
 8916
 8917    pub(crate) fn breakpoint_at_row(
 8918        &self,
 8919        row: u32,
 8920        window: &mut Window,
 8921        cx: &mut Context<Self>,
 8922    ) -> Option<(Anchor, Breakpoint)> {
 8923        let snapshot = self.snapshot(window, cx);
 8924        let breakpoint_position = snapshot.buffer_snapshot.anchor_before(Point::new(row, 0));
 8925
 8926        self.breakpoint_at_anchor(breakpoint_position, &snapshot, cx)
 8927    }
 8928
 8929    pub(crate) fn breakpoint_at_anchor(
 8930        &self,
 8931        breakpoint_position: Anchor,
 8932        snapshot: &EditorSnapshot,
 8933        cx: &mut Context<Self>,
 8934    ) -> Option<(Anchor, Breakpoint)> {
 8935        let project = self.project.clone()?;
 8936
 8937        let buffer_id = breakpoint_position.buffer_id.or_else(|| {
 8938            snapshot
 8939                .buffer_snapshot
 8940                .buffer_id_for_excerpt(breakpoint_position.excerpt_id)
 8941        })?;
 8942
 8943        let enclosing_excerpt = breakpoint_position.excerpt_id;
 8944        let buffer = project.read_with(cx, |project, cx| project.buffer_for_id(buffer_id, cx))?;
 8945        let buffer_snapshot = buffer.read(cx).snapshot();
 8946
 8947        let row = buffer_snapshot
 8948            .summary_for_anchor::<text::PointUtf16>(&breakpoint_position.text_anchor)
 8949            .row;
 8950
 8951        let line_len = snapshot.buffer_snapshot.line_len(MultiBufferRow(row));
 8952        let anchor_end = snapshot
 8953            .buffer_snapshot
 8954            .anchor_after(Point::new(row, line_len));
 8955
 8956        let bp = self
 8957            .breakpoint_store
 8958            .as_ref()?
 8959            .read_with(cx, |breakpoint_store, cx| {
 8960                breakpoint_store
 8961                    .breakpoints(
 8962                        &buffer,
 8963                        Some(breakpoint_position.text_anchor..anchor_end.text_anchor),
 8964                        &buffer_snapshot,
 8965                        cx,
 8966                    )
 8967                    .next()
 8968                    .and_then(|(anchor, bp)| {
 8969                        let breakpoint_row = buffer_snapshot
 8970                            .summary_for_anchor::<text::PointUtf16>(anchor)
 8971                            .row;
 8972
 8973                        if breakpoint_row == row {
 8974                            snapshot
 8975                                .buffer_snapshot
 8976                                .anchor_in_excerpt(enclosing_excerpt, *anchor)
 8977                                .map(|anchor| (anchor, bp.clone()))
 8978                        } else {
 8979                            None
 8980                        }
 8981                    })
 8982            });
 8983        bp
 8984    }
 8985
 8986    pub fn edit_log_breakpoint(
 8987        &mut self,
 8988        _: &EditLogBreakpoint,
 8989        window: &mut Window,
 8990        cx: &mut Context<Self>,
 8991    ) {
 8992        for (anchor, breakpoint) in self.breakpoints_at_cursors(window, cx) {
 8993            let breakpoint = breakpoint.unwrap_or_else(|| Breakpoint {
 8994                message: None,
 8995                state: BreakpointState::Enabled,
 8996                condition: None,
 8997                hit_condition: None,
 8998            });
 8999
 9000            self.add_edit_breakpoint_block(
 9001                anchor,
 9002                &breakpoint,
 9003                BreakpointPromptEditAction::Log,
 9004                window,
 9005                cx,
 9006            );
 9007        }
 9008    }
 9009
 9010    fn breakpoints_at_cursors(
 9011        &self,
 9012        window: &mut Window,
 9013        cx: &mut Context<Self>,
 9014    ) -> Vec<(Anchor, Option<Breakpoint>)> {
 9015        let snapshot = self.snapshot(window, cx);
 9016        let cursors = self
 9017            .selections
 9018            .disjoint_anchors()
 9019            .into_iter()
 9020            .map(|selection| {
 9021                let cursor_position: Point = selection.head().to_point(&snapshot.buffer_snapshot);
 9022
 9023                let breakpoint_position = self
 9024                    .breakpoint_at_row(cursor_position.row, window, cx)
 9025                    .map(|bp| bp.0)
 9026                    .unwrap_or_else(|| {
 9027                        snapshot
 9028                            .display_snapshot
 9029                            .buffer_snapshot
 9030                            .anchor_after(Point::new(cursor_position.row, 0))
 9031                    });
 9032
 9033                let breakpoint = self
 9034                    .breakpoint_at_anchor(breakpoint_position, &snapshot, cx)
 9035                    .map(|(anchor, breakpoint)| (anchor, Some(breakpoint)));
 9036
 9037                breakpoint.unwrap_or_else(|| (breakpoint_position, None))
 9038            })
 9039            // There might be multiple cursors on the same line; all of them should have the same anchors though as their breakpoints positions, which makes it possible to sort and dedup the list.
 9040            .collect::<HashMap<Anchor, _>>();
 9041
 9042        cursors.into_iter().collect()
 9043    }
 9044
 9045    pub fn enable_breakpoint(
 9046        &mut self,
 9047        _: &crate::actions::EnableBreakpoint,
 9048        window: &mut Window,
 9049        cx: &mut Context<Self>,
 9050    ) {
 9051        for (anchor, breakpoint) in self.breakpoints_at_cursors(window, cx) {
 9052            let Some(breakpoint) = breakpoint.filter(|breakpoint| breakpoint.is_disabled()) else {
 9053                continue;
 9054            };
 9055            self.edit_breakpoint_at_anchor(
 9056                anchor,
 9057                breakpoint,
 9058                BreakpointEditAction::InvertState,
 9059                cx,
 9060            );
 9061        }
 9062    }
 9063
 9064    pub fn disable_breakpoint(
 9065        &mut self,
 9066        _: &crate::actions::DisableBreakpoint,
 9067        window: &mut Window,
 9068        cx: &mut Context<Self>,
 9069    ) {
 9070        for (anchor, breakpoint) in self.breakpoints_at_cursors(window, cx) {
 9071            let Some(breakpoint) = breakpoint.filter(|breakpoint| breakpoint.is_enabled()) else {
 9072                continue;
 9073            };
 9074            self.edit_breakpoint_at_anchor(
 9075                anchor,
 9076                breakpoint,
 9077                BreakpointEditAction::InvertState,
 9078                cx,
 9079            );
 9080        }
 9081    }
 9082
 9083    pub fn toggle_breakpoint(
 9084        &mut self,
 9085        _: &crate::actions::ToggleBreakpoint,
 9086        window: &mut Window,
 9087        cx: &mut Context<Self>,
 9088    ) {
 9089        for (anchor, breakpoint) in self.breakpoints_at_cursors(window, cx) {
 9090            if let Some(breakpoint) = breakpoint {
 9091                self.edit_breakpoint_at_anchor(
 9092                    anchor,
 9093                    breakpoint,
 9094                    BreakpointEditAction::Toggle,
 9095                    cx,
 9096                );
 9097            } else {
 9098                self.edit_breakpoint_at_anchor(
 9099                    anchor,
 9100                    Breakpoint::new_standard(),
 9101                    BreakpointEditAction::Toggle,
 9102                    cx,
 9103                );
 9104            }
 9105        }
 9106    }
 9107
 9108    pub fn edit_breakpoint_at_anchor(
 9109        &mut self,
 9110        breakpoint_position: Anchor,
 9111        breakpoint: Breakpoint,
 9112        edit_action: BreakpointEditAction,
 9113        cx: &mut Context<Self>,
 9114    ) {
 9115        let Some(breakpoint_store) = &self.breakpoint_store else {
 9116            return;
 9117        };
 9118
 9119        let Some(buffer_id) = breakpoint_position.buffer_id.or_else(|| {
 9120            if breakpoint_position == Anchor::min() {
 9121                self.buffer()
 9122                    .read(cx)
 9123                    .excerpt_buffer_ids()
 9124                    .into_iter()
 9125                    .next()
 9126            } else {
 9127                None
 9128            }
 9129        }) else {
 9130            return;
 9131        };
 9132
 9133        let Some(buffer) = self.buffer().read(cx).buffer(buffer_id) else {
 9134            return;
 9135        };
 9136
 9137        breakpoint_store.update(cx, |breakpoint_store, cx| {
 9138            breakpoint_store.toggle_breakpoint(
 9139                buffer,
 9140                (breakpoint_position.text_anchor, breakpoint),
 9141                edit_action,
 9142                cx,
 9143            );
 9144        });
 9145
 9146        cx.notify();
 9147    }
 9148
 9149    #[cfg(any(test, feature = "test-support"))]
 9150    pub fn breakpoint_store(&self) -> Option<Entity<BreakpointStore>> {
 9151        self.breakpoint_store.clone()
 9152    }
 9153
 9154    pub fn prepare_restore_change(
 9155        &self,
 9156        revert_changes: &mut HashMap<BufferId, Vec<(Range<text::Anchor>, Rope)>>,
 9157        hunk: &MultiBufferDiffHunk,
 9158        cx: &mut App,
 9159    ) -> Option<()> {
 9160        if hunk.is_created_file() {
 9161            return None;
 9162        }
 9163        let buffer = self.buffer.read(cx);
 9164        let diff = buffer.diff_for(hunk.buffer_id)?;
 9165        let buffer = buffer.buffer(hunk.buffer_id)?;
 9166        let buffer = buffer.read(cx);
 9167        let original_text = diff
 9168            .read(cx)
 9169            .base_text()
 9170            .as_rope()
 9171            .slice(hunk.diff_base_byte_range.clone());
 9172        let buffer_snapshot = buffer.snapshot();
 9173        let buffer_revert_changes = revert_changes.entry(buffer.remote_id()).or_default();
 9174        if let Err(i) = buffer_revert_changes.binary_search_by(|probe| {
 9175            probe
 9176                .0
 9177                .start
 9178                .cmp(&hunk.buffer_range.start, &buffer_snapshot)
 9179                .then(probe.0.end.cmp(&hunk.buffer_range.end, &buffer_snapshot))
 9180        }) {
 9181            buffer_revert_changes.insert(i, (hunk.buffer_range.clone(), original_text));
 9182            Some(())
 9183        } else {
 9184            None
 9185        }
 9186    }
 9187
 9188    pub fn reverse_lines(&mut self, _: &ReverseLines, window: &mut Window, cx: &mut Context<Self>) {
 9189        self.manipulate_lines(window, cx, |lines| lines.reverse())
 9190    }
 9191
 9192    pub fn shuffle_lines(&mut self, _: &ShuffleLines, window: &mut Window, cx: &mut Context<Self>) {
 9193        self.manipulate_lines(window, cx, |lines| lines.shuffle(&mut thread_rng()))
 9194    }
 9195
 9196    fn manipulate_lines<Fn>(
 9197        &mut self,
 9198        window: &mut Window,
 9199        cx: &mut Context<Self>,
 9200        mut callback: Fn,
 9201    ) where
 9202        Fn: FnMut(&mut Vec<&str>),
 9203    {
 9204        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
 9205
 9206        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 9207        let buffer = self.buffer.read(cx).snapshot(cx);
 9208
 9209        let mut edits = Vec::new();
 9210
 9211        let selections = self.selections.all::<Point>(cx);
 9212        let mut selections = selections.iter().peekable();
 9213        let mut contiguous_row_selections = Vec::new();
 9214        let mut new_selections = Vec::new();
 9215        let mut added_lines = 0;
 9216        let mut removed_lines = 0;
 9217
 9218        while let Some(selection) = selections.next() {
 9219            let (start_row, end_row) = consume_contiguous_rows(
 9220                &mut contiguous_row_selections,
 9221                selection,
 9222                &display_map,
 9223                &mut selections,
 9224            );
 9225
 9226            let start_point = Point::new(start_row.0, 0);
 9227            let end_point = Point::new(
 9228                end_row.previous_row().0,
 9229                buffer.line_len(end_row.previous_row()),
 9230            );
 9231            let text = buffer
 9232                .text_for_range(start_point..end_point)
 9233                .collect::<String>();
 9234
 9235            let mut lines = text.split('\n').collect_vec();
 9236
 9237            let lines_before = lines.len();
 9238            callback(&mut lines);
 9239            let lines_after = lines.len();
 9240
 9241            edits.push((start_point..end_point, lines.join("\n")));
 9242
 9243            // Selections must change based on added and removed line count
 9244            let start_row =
 9245                MultiBufferRow(start_point.row + added_lines as u32 - removed_lines as u32);
 9246            let end_row = MultiBufferRow(start_row.0 + lines_after.saturating_sub(1) as u32);
 9247            new_selections.push(Selection {
 9248                id: selection.id,
 9249                start: start_row,
 9250                end: end_row,
 9251                goal: SelectionGoal::None,
 9252                reversed: selection.reversed,
 9253            });
 9254
 9255            if lines_after > lines_before {
 9256                added_lines += lines_after - lines_before;
 9257            } else if lines_before > lines_after {
 9258                removed_lines += lines_before - lines_after;
 9259            }
 9260        }
 9261
 9262        self.transact(window, cx, |this, window, cx| {
 9263            let buffer = this.buffer.update(cx, |buffer, cx| {
 9264                buffer.edit(edits, None, cx);
 9265                buffer.snapshot(cx)
 9266            });
 9267
 9268            // Recalculate offsets on newly edited buffer
 9269            let new_selections = new_selections
 9270                .iter()
 9271                .map(|s| {
 9272                    let start_point = Point::new(s.start.0, 0);
 9273                    let end_point = Point::new(s.end.0, buffer.line_len(s.end));
 9274                    Selection {
 9275                        id: s.id,
 9276                        start: buffer.point_to_offset(start_point),
 9277                        end: buffer.point_to_offset(end_point),
 9278                        goal: s.goal,
 9279                        reversed: s.reversed,
 9280                    }
 9281                })
 9282                .collect();
 9283
 9284            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9285                s.select(new_selections);
 9286            });
 9287
 9288            this.request_autoscroll(Autoscroll::fit(), cx);
 9289        });
 9290    }
 9291
 9292    pub fn toggle_case(&mut self, _: &ToggleCase, window: &mut Window, cx: &mut Context<Self>) {
 9293        self.manipulate_text(window, cx, |text| {
 9294            let has_upper_case_characters = text.chars().any(|c| c.is_uppercase());
 9295            if has_upper_case_characters {
 9296                text.to_lowercase()
 9297            } else {
 9298                text.to_uppercase()
 9299            }
 9300        })
 9301    }
 9302
 9303    pub fn convert_to_upper_case(
 9304        &mut self,
 9305        _: &ConvertToUpperCase,
 9306        window: &mut Window,
 9307        cx: &mut Context<Self>,
 9308    ) {
 9309        self.manipulate_text(window, cx, |text| text.to_uppercase())
 9310    }
 9311
 9312    pub fn convert_to_lower_case(
 9313        &mut self,
 9314        _: &ConvertToLowerCase,
 9315        window: &mut Window,
 9316        cx: &mut Context<Self>,
 9317    ) {
 9318        self.manipulate_text(window, cx, |text| text.to_lowercase())
 9319    }
 9320
 9321    pub fn convert_to_title_case(
 9322        &mut self,
 9323        _: &ConvertToTitleCase,
 9324        window: &mut Window,
 9325        cx: &mut Context<Self>,
 9326    ) {
 9327        self.manipulate_text(window, cx, |text| {
 9328            text.split('\n')
 9329                .map(|line| line.to_case(Case::Title))
 9330                .join("\n")
 9331        })
 9332    }
 9333
 9334    pub fn convert_to_snake_case(
 9335        &mut self,
 9336        _: &ConvertToSnakeCase,
 9337        window: &mut Window,
 9338        cx: &mut Context<Self>,
 9339    ) {
 9340        self.manipulate_text(window, cx, |text| text.to_case(Case::Snake))
 9341    }
 9342
 9343    pub fn convert_to_kebab_case(
 9344        &mut self,
 9345        _: &ConvertToKebabCase,
 9346        window: &mut Window,
 9347        cx: &mut Context<Self>,
 9348    ) {
 9349        self.manipulate_text(window, cx, |text| text.to_case(Case::Kebab))
 9350    }
 9351
 9352    pub fn convert_to_upper_camel_case(
 9353        &mut self,
 9354        _: &ConvertToUpperCamelCase,
 9355        window: &mut Window,
 9356        cx: &mut Context<Self>,
 9357    ) {
 9358        self.manipulate_text(window, cx, |text| {
 9359            text.split('\n')
 9360                .map(|line| line.to_case(Case::UpperCamel))
 9361                .join("\n")
 9362        })
 9363    }
 9364
 9365    pub fn convert_to_lower_camel_case(
 9366        &mut self,
 9367        _: &ConvertToLowerCamelCase,
 9368        window: &mut Window,
 9369        cx: &mut Context<Self>,
 9370    ) {
 9371        self.manipulate_text(window, cx, |text| text.to_case(Case::Camel))
 9372    }
 9373
 9374    pub fn convert_to_opposite_case(
 9375        &mut self,
 9376        _: &ConvertToOppositeCase,
 9377        window: &mut Window,
 9378        cx: &mut Context<Self>,
 9379    ) {
 9380        self.manipulate_text(window, cx, |text| {
 9381            text.chars()
 9382                .fold(String::with_capacity(text.len()), |mut t, c| {
 9383                    if c.is_uppercase() {
 9384                        t.extend(c.to_lowercase());
 9385                    } else {
 9386                        t.extend(c.to_uppercase());
 9387                    }
 9388                    t
 9389                })
 9390        })
 9391    }
 9392
 9393    pub fn convert_to_rot13(
 9394        &mut self,
 9395        _: &ConvertToRot13,
 9396        window: &mut Window,
 9397        cx: &mut Context<Self>,
 9398    ) {
 9399        self.manipulate_text(window, cx, |text| {
 9400            text.chars()
 9401                .map(|c| match c {
 9402                    'A'..='M' | 'a'..='m' => ((c as u8) + 13) as char,
 9403                    'N'..='Z' | 'n'..='z' => ((c as u8) - 13) as char,
 9404                    _ => c,
 9405                })
 9406                .collect()
 9407        })
 9408    }
 9409
 9410    pub fn convert_to_rot47(
 9411        &mut self,
 9412        _: &ConvertToRot47,
 9413        window: &mut Window,
 9414        cx: &mut Context<Self>,
 9415    ) {
 9416        self.manipulate_text(window, cx, |text| {
 9417            text.chars()
 9418                .map(|c| {
 9419                    let code_point = c as u32;
 9420                    if code_point >= 33 && code_point <= 126 {
 9421                        return char::from_u32(33 + ((code_point + 14) % 94)).unwrap();
 9422                    }
 9423                    c
 9424                })
 9425                .collect()
 9426        })
 9427    }
 9428
 9429    fn manipulate_text<Fn>(&mut self, window: &mut Window, cx: &mut Context<Self>, mut callback: Fn)
 9430    where
 9431        Fn: FnMut(&str) -> String,
 9432    {
 9433        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 9434        let buffer = self.buffer.read(cx).snapshot(cx);
 9435
 9436        let mut new_selections = Vec::new();
 9437        let mut edits = Vec::new();
 9438        let mut selection_adjustment = 0i32;
 9439
 9440        for selection in self.selections.all::<usize>(cx) {
 9441            let selection_is_empty = selection.is_empty();
 9442
 9443            let (start, end) = if selection_is_empty {
 9444                let word_range = movement::surrounding_word(
 9445                    &display_map,
 9446                    selection.start.to_display_point(&display_map),
 9447                );
 9448                let start = word_range.start.to_offset(&display_map, Bias::Left);
 9449                let end = word_range.end.to_offset(&display_map, Bias::Left);
 9450                (start, end)
 9451            } else {
 9452                (selection.start, selection.end)
 9453            };
 9454
 9455            let text = buffer.text_for_range(start..end).collect::<String>();
 9456            let old_length = text.len() as i32;
 9457            let text = callback(&text);
 9458
 9459            new_selections.push(Selection {
 9460                start: (start as i32 - selection_adjustment) as usize,
 9461                end: ((start + text.len()) as i32 - selection_adjustment) as usize,
 9462                goal: SelectionGoal::None,
 9463                ..selection
 9464            });
 9465
 9466            selection_adjustment += old_length - text.len() as i32;
 9467
 9468            edits.push((start..end, text));
 9469        }
 9470
 9471        self.transact(window, cx, |this, window, cx| {
 9472            this.buffer.update(cx, |buffer, cx| {
 9473                buffer.edit(edits, None, cx);
 9474            });
 9475
 9476            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9477                s.select(new_selections);
 9478            });
 9479
 9480            this.request_autoscroll(Autoscroll::fit(), cx);
 9481        });
 9482    }
 9483
 9484    pub fn duplicate(
 9485        &mut self,
 9486        upwards: bool,
 9487        whole_lines: bool,
 9488        window: &mut Window,
 9489        cx: &mut Context<Self>,
 9490    ) {
 9491        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
 9492
 9493        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 9494        let buffer = &display_map.buffer_snapshot;
 9495        let selections = self.selections.all::<Point>(cx);
 9496
 9497        let mut edits = Vec::new();
 9498        let mut selections_iter = selections.iter().peekable();
 9499        while let Some(selection) = selections_iter.next() {
 9500            let mut rows = selection.spanned_rows(false, &display_map);
 9501            // duplicate line-wise
 9502            if whole_lines || selection.start == selection.end {
 9503                // Avoid duplicating the same lines twice.
 9504                while let Some(next_selection) = selections_iter.peek() {
 9505                    let next_rows = next_selection.spanned_rows(false, &display_map);
 9506                    if next_rows.start < rows.end {
 9507                        rows.end = next_rows.end;
 9508                        selections_iter.next().unwrap();
 9509                    } else {
 9510                        break;
 9511                    }
 9512                }
 9513
 9514                // Copy the text from the selected row region and splice it either at the start
 9515                // or end of the region.
 9516                let start = Point::new(rows.start.0, 0);
 9517                let end = Point::new(
 9518                    rows.end.previous_row().0,
 9519                    buffer.line_len(rows.end.previous_row()),
 9520                );
 9521                let text = buffer
 9522                    .text_for_range(start..end)
 9523                    .chain(Some("\n"))
 9524                    .collect::<String>();
 9525                let insert_location = if upwards {
 9526                    Point::new(rows.end.0, 0)
 9527                } else {
 9528                    start
 9529                };
 9530                edits.push((insert_location..insert_location, text));
 9531            } else {
 9532                // duplicate character-wise
 9533                let start = selection.start;
 9534                let end = selection.end;
 9535                let text = buffer.text_for_range(start..end).collect::<String>();
 9536                edits.push((selection.end..selection.end, text));
 9537            }
 9538        }
 9539
 9540        self.transact(window, cx, |this, _, cx| {
 9541            this.buffer.update(cx, |buffer, cx| {
 9542                buffer.edit(edits, None, cx);
 9543            });
 9544
 9545            this.request_autoscroll(Autoscroll::fit(), cx);
 9546        });
 9547    }
 9548
 9549    pub fn duplicate_line_up(
 9550        &mut self,
 9551        _: &DuplicateLineUp,
 9552        window: &mut Window,
 9553        cx: &mut Context<Self>,
 9554    ) {
 9555        self.duplicate(true, true, window, cx);
 9556    }
 9557
 9558    pub fn duplicate_line_down(
 9559        &mut self,
 9560        _: &DuplicateLineDown,
 9561        window: &mut Window,
 9562        cx: &mut Context<Self>,
 9563    ) {
 9564        self.duplicate(false, true, window, cx);
 9565    }
 9566
 9567    pub fn duplicate_selection(
 9568        &mut self,
 9569        _: &DuplicateSelection,
 9570        window: &mut Window,
 9571        cx: &mut Context<Self>,
 9572    ) {
 9573        self.duplicate(false, false, window, cx);
 9574    }
 9575
 9576    pub fn move_line_up(&mut self, _: &MoveLineUp, window: &mut Window, cx: &mut Context<Self>) {
 9577        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
 9578
 9579        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 9580        let buffer = self.buffer.read(cx).snapshot(cx);
 9581
 9582        let mut edits = Vec::new();
 9583        let mut unfold_ranges = Vec::new();
 9584        let mut refold_creases = Vec::new();
 9585
 9586        let selections = self.selections.all::<Point>(cx);
 9587        let mut selections = selections.iter().peekable();
 9588        let mut contiguous_row_selections = Vec::new();
 9589        let mut new_selections = Vec::new();
 9590
 9591        while let Some(selection) = selections.next() {
 9592            // Find all the selections that span a contiguous row range
 9593            let (start_row, end_row) = consume_contiguous_rows(
 9594                &mut contiguous_row_selections,
 9595                selection,
 9596                &display_map,
 9597                &mut selections,
 9598            );
 9599
 9600            // Move the text spanned by the row range to be before the line preceding the row range
 9601            if start_row.0 > 0 {
 9602                let range_to_move = Point::new(
 9603                    start_row.previous_row().0,
 9604                    buffer.line_len(start_row.previous_row()),
 9605                )
 9606                    ..Point::new(
 9607                        end_row.previous_row().0,
 9608                        buffer.line_len(end_row.previous_row()),
 9609                    );
 9610                let insertion_point = display_map
 9611                    .prev_line_boundary(Point::new(start_row.previous_row().0, 0))
 9612                    .0;
 9613
 9614                // Don't move lines across excerpts
 9615                if buffer
 9616                    .excerpt_containing(insertion_point..range_to_move.end)
 9617                    .is_some()
 9618                {
 9619                    let text = buffer
 9620                        .text_for_range(range_to_move.clone())
 9621                        .flat_map(|s| s.chars())
 9622                        .skip(1)
 9623                        .chain(['\n'])
 9624                        .collect::<String>();
 9625
 9626                    edits.push((
 9627                        buffer.anchor_after(range_to_move.start)
 9628                            ..buffer.anchor_before(range_to_move.end),
 9629                        String::new(),
 9630                    ));
 9631                    let insertion_anchor = buffer.anchor_after(insertion_point);
 9632                    edits.push((insertion_anchor..insertion_anchor, text));
 9633
 9634                    let row_delta = range_to_move.start.row - insertion_point.row + 1;
 9635
 9636                    // Move selections up
 9637                    new_selections.extend(contiguous_row_selections.drain(..).map(
 9638                        |mut selection| {
 9639                            selection.start.row -= row_delta;
 9640                            selection.end.row -= row_delta;
 9641                            selection
 9642                        },
 9643                    ));
 9644
 9645                    // Move folds up
 9646                    unfold_ranges.push(range_to_move.clone());
 9647                    for fold in display_map.folds_in_range(
 9648                        buffer.anchor_before(range_to_move.start)
 9649                            ..buffer.anchor_after(range_to_move.end),
 9650                    ) {
 9651                        let mut start = fold.range.start.to_point(&buffer);
 9652                        let mut end = fold.range.end.to_point(&buffer);
 9653                        start.row -= row_delta;
 9654                        end.row -= row_delta;
 9655                        refold_creases.push(Crease::simple(start..end, fold.placeholder.clone()));
 9656                    }
 9657                }
 9658            }
 9659
 9660            // If we didn't move line(s), preserve the existing selections
 9661            new_selections.append(&mut contiguous_row_selections);
 9662        }
 9663
 9664        self.transact(window, cx, |this, window, cx| {
 9665            this.unfold_ranges(&unfold_ranges, true, true, cx);
 9666            this.buffer.update(cx, |buffer, cx| {
 9667                for (range, text) in edits {
 9668                    buffer.edit([(range, text)], None, cx);
 9669                }
 9670            });
 9671            this.fold_creases(refold_creases, true, window, cx);
 9672            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9673                s.select(new_selections);
 9674            })
 9675        });
 9676    }
 9677
 9678    pub fn move_line_down(
 9679        &mut self,
 9680        _: &MoveLineDown,
 9681        window: &mut Window,
 9682        cx: &mut Context<Self>,
 9683    ) {
 9684        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
 9685
 9686        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 9687        let buffer = self.buffer.read(cx).snapshot(cx);
 9688
 9689        let mut edits = Vec::new();
 9690        let mut unfold_ranges = Vec::new();
 9691        let mut refold_creases = Vec::new();
 9692
 9693        let selections = self.selections.all::<Point>(cx);
 9694        let mut selections = selections.iter().peekable();
 9695        let mut contiguous_row_selections = Vec::new();
 9696        let mut new_selections = Vec::new();
 9697
 9698        while let Some(selection) = selections.next() {
 9699            // Find all the selections that span a contiguous row range
 9700            let (start_row, end_row) = consume_contiguous_rows(
 9701                &mut contiguous_row_selections,
 9702                selection,
 9703                &display_map,
 9704                &mut selections,
 9705            );
 9706
 9707            // Move the text spanned by the row range to be after the last line of the row range
 9708            if end_row.0 <= buffer.max_point().row {
 9709                let range_to_move =
 9710                    MultiBufferPoint::new(start_row.0, 0)..MultiBufferPoint::new(end_row.0, 0);
 9711                let insertion_point = display_map
 9712                    .next_line_boundary(MultiBufferPoint::new(end_row.0, 0))
 9713                    .0;
 9714
 9715                // Don't move lines across excerpt boundaries
 9716                if buffer
 9717                    .excerpt_containing(range_to_move.start..insertion_point)
 9718                    .is_some()
 9719                {
 9720                    let mut text = String::from("\n");
 9721                    text.extend(buffer.text_for_range(range_to_move.clone()));
 9722                    text.pop(); // Drop trailing newline
 9723                    edits.push((
 9724                        buffer.anchor_after(range_to_move.start)
 9725                            ..buffer.anchor_before(range_to_move.end),
 9726                        String::new(),
 9727                    ));
 9728                    let insertion_anchor = buffer.anchor_after(insertion_point);
 9729                    edits.push((insertion_anchor..insertion_anchor, text));
 9730
 9731                    let row_delta = insertion_point.row - range_to_move.end.row + 1;
 9732
 9733                    // Move selections down
 9734                    new_selections.extend(contiguous_row_selections.drain(..).map(
 9735                        |mut selection| {
 9736                            selection.start.row += row_delta;
 9737                            selection.end.row += row_delta;
 9738                            selection
 9739                        },
 9740                    ));
 9741
 9742                    // Move folds down
 9743                    unfold_ranges.push(range_to_move.clone());
 9744                    for fold in display_map.folds_in_range(
 9745                        buffer.anchor_before(range_to_move.start)
 9746                            ..buffer.anchor_after(range_to_move.end),
 9747                    ) {
 9748                        let mut start = fold.range.start.to_point(&buffer);
 9749                        let mut end = fold.range.end.to_point(&buffer);
 9750                        start.row += row_delta;
 9751                        end.row += row_delta;
 9752                        refold_creases.push(Crease::simple(start..end, fold.placeholder.clone()));
 9753                    }
 9754                }
 9755            }
 9756
 9757            // If we didn't move line(s), preserve the existing selections
 9758            new_selections.append(&mut contiguous_row_selections);
 9759        }
 9760
 9761        self.transact(window, cx, |this, window, cx| {
 9762            this.unfold_ranges(&unfold_ranges, true, true, cx);
 9763            this.buffer.update(cx, |buffer, cx| {
 9764                for (range, text) in edits {
 9765                    buffer.edit([(range, text)], None, cx);
 9766                }
 9767            });
 9768            this.fold_creases(refold_creases, true, window, cx);
 9769            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9770                s.select(new_selections)
 9771            });
 9772        });
 9773    }
 9774
 9775    pub fn transpose(&mut self, _: &Transpose, window: &mut Window, cx: &mut Context<Self>) {
 9776        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
 9777        let text_layout_details = &self.text_layout_details(window);
 9778        self.transact(window, cx, |this, window, cx| {
 9779            let edits = this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9780                let mut edits: Vec<(Range<usize>, String)> = Default::default();
 9781                s.move_with(|display_map, selection| {
 9782                    if !selection.is_empty() {
 9783                        return;
 9784                    }
 9785
 9786                    let mut head = selection.head();
 9787                    let mut transpose_offset = head.to_offset(display_map, Bias::Right);
 9788                    if head.column() == display_map.line_len(head.row()) {
 9789                        transpose_offset = display_map
 9790                            .buffer_snapshot
 9791                            .clip_offset(transpose_offset.saturating_sub(1), Bias::Left);
 9792                    }
 9793
 9794                    if transpose_offset == 0 {
 9795                        return;
 9796                    }
 9797
 9798                    *head.column_mut() += 1;
 9799                    head = display_map.clip_point(head, Bias::Right);
 9800                    let goal = SelectionGoal::HorizontalPosition(
 9801                        display_map
 9802                            .x_for_display_point(head, text_layout_details)
 9803                            .into(),
 9804                    );
 9805                    selection.collapse_to(head, goal);
 9806
 9807                    let transpose_start = display_map
 9808                        .buffer_snapshot
 9809                        .clip_offset(transpose_offset.saturating_sub(1), Bias::Left);
 9810                    if edits.last().map_or(true, |e| e.0.end <= transpose_start) {
 9811                        let transpose_end = display_map
 9812                            .buffer_snapshot
 9813                            .clip_offset(transpose_offset + 1, Bias::Right);
 9814                        if let Some(ch) =
 9815                            display_map.buffer_snapshot.chars_at(transpose_start).next()
 9816                        {
 9817                            edits.push((transpose_start..transpose_offset, String::new()));
 9818                            edits.push((transpose_end..transpose_end, ch.to_string()));
 9819                        }
 9820                    }
 9821                });
 9822                edits
 9823            });
 9824            this.buffer
 9825                .update(cx, |buffer, cx| buffer.edit(edits, None, cx));
 9826            let selections = this.selections.all::<usize>(cx);
 9827            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9828                s.select(selections);
 9829            });
 9830        });
 9831    }
 9832
 9833    pub fn rewrap(&mut self, _: &Rewrap, _: &mut Window, cx: &mut Context<Self>) {
 9834        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
 9835        self.rewrap_impl(RewrapOptions::default(), cx)
 9836    }
 9837
 9838    pub fn rewrap_impl(&mut self, options: RewrapOptions, cx: &mut Context<Self>) {
 9839        let buffer = self.buffer.read(cx).snapshot(cx);
 9840        let selections = self.selections.all::<Point>(cx);
 9841        let mut selections = selections.iter().peekable();
 9842
 9843        let mut edits = Vec::new();
 9844        let mut rewrapped_row_ranges = Vec::<RangeInclusive<u32>>::new();
 9845
 9846        while let Some(selection) = selections.next() {
 9847            let mut start_row = selection.start.row;
 9848            let mut end_row = selection.end.row;
 9849
 9850            // Skip selections that overlap with a range that has already been rewrapped.
 9851            let selection_range = start_row..end_row;
 9852            if rewrapped_row_ranges
 9853                .iter()
 9854                .any(|range| range.overlaps(&selection_range))
 9855            {
 9856                continue;
 9857            }
 9858
 9859            let tab_size = buffer.language_settings_at(selection.head(), cx).tab_size;
 9860
 9861            // Since not all lines in the selection may be at the same indent
 9862            // level, choose the indent size that is the most common between all
 9863            // of the lines.
 9864            //
 9865            // If there is a tie, we use the deepest indent.
 9866            let (indent_size, indent_end) = {
 9867                let mut indent_size_occurrences = HashMap::default();
 9868                let mut rows_by_indent_size = HashMap::<IndentSize, Vec<u32>>::default();
 9869
 9870                for row in start_row..=end_row {
 9871                    let indent = buffer.indent_size_for_line(MultiBufferRow(row));
 9872                    rows_by_indent_size.entry(indent).or_default().push(row);
 9873                    *indent_size_occurrences.entry(indent).or_insert(0) += 1;
 9874                }
 9875
 9876                let indent_size = indent_size_occurrences
 9877                    .into_iter()
 9878                    .max_by_key(|(indent, count)| (*count, indent.len_with_expanded_tabs(tab_size)))
 9879                    .map(|(indent, _)| indent)
 9880                    .unwrap_or_default();
 9881                let row = rows_by_indent_size[&indent_size][0];
 9882                let indent_end = Point::new(row, indent_size.len);
 9883
 9884                (indent_size, indent_end)
 9885            };
 9886
 9887            let mut line_prefix = indent_size.chars().collect::<String>();
 9888
 9889            let mut inside_comment = false;
 9890            if let Some(comment_prefix) =
 9891                buffer
 9892                    .language_scope_at(selection.head())
 9893                    .and_then(|language| {
 9894                        language
 9895                            .line_comment_prefixes()
 9896                            .iter()
 9897                            .find(|prefix| buffer.contains_str_at(indent_end, prefix))
 9898                            .cloned()
 9899                    })
 9900            {
 9901                line_prefix.push_str(&comment_prefix);
 9902                inside_comment = true;
 9903            }
 9904
 9905            let language_settings = buffer.language_settings_at(selection.head(), cx);
 9906            let allow_rewrap_based_on_language = match language_settings.allow_rewrap {
 9907                RewrapBehavior::InComments => inside_comment,
 9908                RewrapBehavior::InSelections => !selection.is_empty(),
 9909                RewrapBehavior::Anywhere => true,
 9910            };
 9911
 9912            let should_rewrap = options.override_language_settings
 9913                || allow_rewrap_based_on_language
 9914                || self.hard_wrap.is_some();
 9915            if !should_rewrap {
 9916                continue;
 9917            }
 9918
 9919            if selection.is_empty() {
 9920                'expand_upwards: while start_row > 0 {
 9921                    let prev_row = start_row - 1;
 9922                    if buffer.contains_str_at(Point::new(prev_row, 0), &line_prefix)
 9923                        && buffer.line_len(MultiBufferRow(prev_row)) as usize > line_prefix.len()
 9924                    {
 9925                        start_row = prev_row;
 9926                    } else {
 9927                        break 'expand_upwards;
 9928                    }
 9929                }
 9930
 9931                'expand_downwards: while end_row < buffer.max_point().row {
 9932                    let next_row = end_row + 1;
 9933                    if buffer.contains_str_at(Point::new(next_row, 0), &line_prefix)
 9934                        && buffer.line_len(MultiBufferRow(next_row)) as usize > line_prefix.len()
 9935                    {
 9936                        end_row = next_row;
 9937                    } else {
 9938                        break 'expand_downwards;
 9939                    }
 9940                }
 9941            }
 9942
 9943            let start = Point::new(start_row, 0);
 9944            let start_offset = start.to_offset(&buffer);
 9945            let end = Point::new(end_row, buffer.line_len(MultiBufferRow(end_row)));
 9946            let selection_text = buffer.text_for_range(start..end).collect::<String>();
 9947            let Some(lines_without_prefixes) = selection_text
 9948                .lines()
 9949                .map(|line| {
 9950                    line.strip_prefix(&line_prefix)
 9951                        .or_else(|| line.trim_start().strip_prefix(&line_prefix.trim_start()))
 9952                        .ok_or_else(|| {
 9953                            anyhow!("line did not start with prefix {line_prefix:?}: {line:?}")
 9954                        })
 9955                })
 9956                .collect::<Result<Vec<_>, _>>()
 9957                .log_err()
 9958            else {
 9959                continue;
 9960            };
 9961
 9962            let wrap_column = self.hard_wrap.unwrap_or_else(|| {
 9963                buffer
 9964                    .language_settings_at(Point::new(start_row, 0), cx)
 9965                    .preferred_line_length as usize
 9966            });
 9967            let wrapped_text = wrap_with_prefix(
 9968                line_prefix,
 9969                lines_without_prefixes.join("\n"),
 9970                wrap_column,
 9971                tab_size,
 9972                options.preserve_existing_whitespace,
 9973            );
 9974
 9975            // TODO: should always use char-based diff while still supporting cursor behavior that
 9976            // matches vim.
 9977            let mut diff_options = DiffOptions::default();
 9978            if options.override_language_settings {
 9979                diff_options.max_word_diff_len = 0;
 9980                diff_options.max_word_diff_line_count = 0;
 9981            } else {
 9982                diff_options.max_word_diff_len = usize::MAX;
 9983                diff_options.max_word_diff_line_count = usize::MAX;
 9984            }
 9985
 9986            for (old_range, new_text) in
 9987                text_diff_with_options(&selection_text, &wrapped_text, diff_options)
 9988            {
 9989                let edit_start = buffer.anchor_after(start_offset + old_range.start);
 9990                let edit_end = buffer.anchor_after(start_offset + old_range.end);
 9991                edits.push((edit_start..edit_end, new_text));
 9992            }
 9993
 9994            rewrapped_row_ranges.push(start_row..=end_row);
 9995        }
 9996
 9997        self.buffer
 9998            .update(cx, |buffer, cx| buffer.edit(edits, None, cx));
 9999    }
10000
10001    pub fn cut_common(&mut self, window: &mut Window, cx: &mut Context<Self>) -> ClipboardItem {
10002        let mut text = String::new();
10003        let buffer = self.buffer.read(cx).snapshot(cx);
10004        let mut selections = self.selections.all::<Point>(cx);
10005        let mut clipboard_selections = Vec::with_capacity(selections.len());
10006        {
10007            let max_point = buffer.max_point();
10008            let mut is_first = true;
10009            for selection in &mut selections {
10010                let is_entire_line = selection.is_empty() || self.selections.line_mode;
10011                if is_entire_line {
10012                    selection.start = Point::new(selection.start.row, 0);
10013                    if !selection.is_empty() && selection.end.column == 0 {
10014                        selection.end = cmp::min(max_point, selection.end);
10015                    } else {
10016                        selection.end = cmp::min(max_point, Point::new(selection.end.row + 1, 0));
10017                    }
10018                    selection.goal = SelectionGoal::None;
10019                }
10020                if is_first {
10021                    is_first = false;
10022                } else {
10023                    text += "\n";
10024                }
10025                let mut len = 0;
10026                for chunk in buffer.text_for_range(selection.start..selection.end) {
10027                    text.push_str(chunk);
10028                    len += chunk.len();
10029                }
10030                clipboard_selections.push(ClipboardSelection {
10031                    len,
10032                    is_entire_line,
10033                    first_line_indent: buffer
10034                        .indent_size_for_line(MultiBufferRow(selection.start.row))
10035                        .len,
10036                });
10037            }
10038        }
10039
10040        self.transact(window, cx, |this, window, cx| {
10041            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10042                s.select(selections);
10043            });
10044            this.insert("", window, cx);
10045        });
10046        ClipboardItem::new_string_with_json_metadata(text, clipboard_selections)
10047    }
10048
10049    pub fn cut(&mut self, _: &Cut, window: &mut Window, cx: &mut Context<Self>) {
10050        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
10051        let item = self.cut_common(window, cx);
10052        cx.write_to_clipboard(item);
10053    }
10054
10055    pub fn kill_ring_cut(&mut self, _: &KillRingCut, window: &mut Window, cx: &mut Context<Self>) {
10056        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
10057        self.change_selections(None, window, cx, |s| {
10058            s.move_with(|snapshot, sel| {
10059                if sel.is_empty() {
10060                    sel.end = DisplayPoint::new(sel.end.row(), snapshot.line_len(sel.end.row()))
10061                }
10062            });
10063        });
10064        let item = self.cut_common(window, cx);
10065        cx.set_global(KillRing(item))
10066    }
10067
10068    pub fn kill_ring_yank(
10069        &mut self,
10070        _: &KillRingYank,
10071        window: &mut Window,
10072        cx: &mut Context<Self>,
10073    ) {
10074        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
10075        let (text, metadata) = if let Some(KillRing(item)) = cx.try_global() {
10076            if let Some(ClipboardEntry::String(kill_ring)) = item.entries().first() {
10077                (kill_ring.text().to_string(), kill_ring.metadata_json())
10078            } else {
10079                return;
10080            }
10081        } else {
10082            return;
10083        };
10084        self.do_paste(&text, metadata, false, window, cx);
10085    }
10086
10087    pub fn copy_and_trim(&mut self, _: &CopyAndTrim, _: &mut Window, cx: &mut Context<Self>) {
10088        self.do_copy(true, cx);
10089    }
10090
10091    pub fn copy(&mut self, _: &Copy, _: &mut Window, cx: &mut Context<Self>) {
10092        self.do_copy(false, cx);
10093    }
10094
10095    fn do_copy(&self, strip_leading_indents: bool, cx: &mut Context<Self>) {
10096        let selections = self.selections.all::<Point>(cx);
10097        let buffer = self.buffer.read(cx).read(cx);
10098        let mut text = String::new();
10099
10100        let mut clipboard_selections = Vec::with_capacity(selections.len());
10101        {
10102            let max_point = buffer.max_point();
10103            let mut is_first = true;
10104            for selection in &selections {
10105                let mut start = selection.start;
10106                let mut end = selection.end;
10107                let is_entire_line = selection.is_empty() || self.selections.line_mode;
10108                if is_entire_line {
10109                    start = Point::new(start.row, 0);
10110                    end = cmp::min(max_point, Point::new(end.row + 1, 0));
10111                }
10112
10113                let mut trimmed_selections = Vec::new();
10114                if strip_leading_indents && end.row.saturating_sub(start.row) > 0 {
10115                    let row = MultiBufferRow(start.row);
10116                    let first_indent = buffer.indent_size_for_line(row);
10117                    if first_indent.len == 0 || start.column > first_indent.len {
10118                        trimmed_selections.push(start..end);
10119                    } else {
10120                        trimmed_selections.push(
10121                            Point::new(row.0, first_indent.len)
10122                                ..Point::new(row.0, buffer.line_len(row)),
10123                        );
10124                        for row in start.row + 1..=end.row {
10125                            let row_indent_size = buffer.indent_size_for_line(MultiBufferRow(row));
10126                            if row_indent_size.len >= first_indent.len {
10127                                trimmed_selections.push(
10128                                    Point::new(row, first_indent.len)
10129                                        ..Point::new(row, buffer.line_len(MultiBufferRow(row))),
10130                                );
10131                            } else {
10132                                trimmed_selections.clear();
10133                                trimmed_selections.push(start..end);
10134                                break;
10135                            }
10136                        }
10137                    }
10138                } else {
10139                    trimmed_selections.push(start..end);
10140                }
10141
10142                for trimmed_range in trimmed_selections {
10143                    if is_first {
10144                        is_first = false;
10145                    } else {
10146                        text += "\n";
10147                    }
10148                    let mut len = 0;
10149                    for chunk in buffer.text_for_range(trimmed_range.start..trimmed_range.end) {
10150                        text.push_str(chunk);
10151                        len += chunk.len();
10152                    }
10153                    clipboard_selections.push(ClipboardSelection {
10154                        len,
10155                        is_entire_line,
10156                        first_line_indent: buffer
10157                            .indent_size_for_line(MultiBufferRow(trimmed_range.start.row))
10158                            .len,
10159                    });
10160                }
10161            }
10162        }
10163
10164        cx.write_to_clipboard(ClipboardItem::new_string_with_json_metadata(
10165            text,
10166            clipboard_selections,
10167        ));
10168    }
10169
10170    pub fn do_paste(
10171        &mut self,
10172        text: &String,
10173        clipboard_selections: Option<Vec<ClipboardSelection>>,
10174        handle_entire_lines: bool,
10175        window: &mut Window,
10176        cx: &mut Context<Self>,
10177    ) {
10178        if self.read_only(cx) {
10179            return;
10180        }
10181
10182        let clipboard_text = Cow::Borrowed(text);
10183
10184        self.transact(window, cx, |this, window, cx| {
10185            if let Some(mut clipboard_selections) = clipboard_selections {
10186                let old_selections = this.selections.all::<usize>(cx);
10187                let all_selections_were_entire_line =
10188                    clipboard_selections.iter().all(|s| s.is_entire_line);
10189                let first_selection_indent_column =
10190                    clipboard_selections.first().map(|s| s.first_line_indent);
10191                if clipboard_selections.len() != old_selections.len() {
10192                    clipboard_selections.drain(..);
10193                }
10194                let cursor_offset = this.selections.last::<usize>(cx).head();
10195                let mut auto_indent_on_paste = true;
10196
10197                this.buffer.update(cx, |buffer, cx| {
10198                    let snapshot = buffer.read(cx);
10199                    auto_indent_on_paste = snapshot
10200                        .language_settings_at(cursor_offset, cx)
10201                        .auto_indent_on_paste;
10202
10203                    let mut start_offset = 0;
10204                    let mut edits = Vec::new();
10205                    let mut original_indent_columns = Vec::new();
10206                    for (ix, selection) in old_selections.iter().enumerate() {
10207                        let to_insert;
10208                        let entire_line;
10209                        let original_indent_column;
10210                        if let Some(clipboard_selection) = clipboard_selections.get(ix) {
10211                            let end_offset = start_offset + clipboard_selection.len;
10212                            to_insert = &clipboard_text[start_offset..end_offset];
10213                            entire_line = clipboard_selection.is_entire_line;
10214                            start_offset = end_offset + 1;
10215                            original_indent_column = Some(clipboard_selection.first_line_indent);
10216                        } else {
10217                            to_insert = clipboard_text.as_str();
10218                            entire_line = all_selections_were_entire_line;
10219                            original_indent_column = first_selection_indent_column
10220                        }
10221
10222                        // If the corresponding selection was empty when this slice of the
10223                        // clipboard text was written, then the entire line containing the
10224                        // selection was copied. If this selection is also currently empty,
10225                        // then paste the line before the current line of the buffer.
10226                        let range = if selection.is_empty() && handle_entire_lines && entire_line {
10227                            let column = selection.start.to_point(&snapshot).column as usize;
10228                            let line_start = selection.start - column;
10229                            line_start..line_start
10230                        } else {
10231                            selection.range()
10232                        };
10233
10234                        edits.push((range, to_insert));
10235                        original_indent_columns.push(original_indent_column);
10236                    }
10237                    drop(snapshot);
10238
10239                    buffer.edit(
10240                        edits,
10241                        if auto_indent_on_paste {
10242                            Some(AutoindentMode::Block {
10243                                original_indent_columns,
10244                            })
10245                        } else {
10246                            None
10247                        },
10248                        cx,
10249                    );
10250                });
10251
10252                let selections = this.selections.all::<usize>(cx);
10253                this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10254                    s.select(selections)
10255                });
10256            } else {
10257                this.insert(&clipboard_text, window, cx);
10258            }
10259        });
10260    }
10261
10262    pub fn paste(&mut self, _: &Paste, window: &mut Window, cx: &mut Context<Self>) {
10263        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
10264        if let Some(item) = cx.read_from_clipboard() {
10265            let entries = item.entries();
10266
10267            match entries.first() {
10268                // For now, we only support applying metadata if there's one string. In the future, we can incorporate all the selections
10269                // of all the pasted entries.
10270                Some(ClipboardEntry::String(clipboard_string)) if entries.len() == 1 => self
10271                    .do_paste(
10272                        clipboard_string.text(),
10273                        clipboard_string.metadata_json::<Vec<ClipboardSelection>>(),
10274                        true,
10275                        window,
10276                        cx,
10277                    ),
10278                _ => self.do_paste(&item.text().unwrap_or_default(), None, true, window, cx),
10279            }
10280        }
10281    }
10282
10283    pub fn undo(&mut self, _: &Undo, window: &mut Window, cx: &mut Context<Self>) {
10284        if self.read_only(cx) {
10285            return;
10286        }
10287
10288        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
10289
10290        if let Some(transaction_id) = self.buffer.update(cx, |buffer, cx| buffer.undo(cx)) {
10291            if let Some((selections, _)) =
10292                self.selection_history.transaction(transaction_id).cloned()
10293            {
10294                self.change_selections(None, window, cx, |s| {
10295                    s.select_anchors(selections.to_vec());
10296                });
10297            } else {
10298                log::error!(
10299                    "No entry in selection_history found for undo. \
10300                     This may correspond to a bug where undo does not update the selection. \
10301                     If this is occurring, please add details to \
10302                     https://github.com/zed-industries/zed/issues/22692"
10303                );
10304            }
10305            self.request_autoscroll(Autoscroll::fit(), cx);
10306            self.unmark_text(window, cx);
10307            self.refresh_inline_completion(true, false, window, cx);
10308            cx.emit(EditorEvent::Edited { transaction_id });
10309            cx.emit(EditorEvent::TransactionUndone { transaction_id });
10310        }
10311    }
10312
10313    pub fn redo(&mut self, _: &Redo, window: &mut Window, cx: &mut Context<Self>) {
10314        if self.read_only(cx) {
10315            return;
10316        }
10317
10318        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
10319
10320        if let Some(transaction_id) = self.buffer.update(cx, |buffer, cx| buffer.redo(cx)) {
10321            if let Some((_, Some(selections))) =
10322                self.selection_history.transaction(transaction_id).cloned()
10323            {
10324                self.change_selections(None, window, cx, |s| {
10325                    s.select_anchors(selections.to_vec());
10326                });
10327            } else {
10328                log::error!(
10329                    "No entry in selection_history found for redo. \
10330                     This may correspond to a bug where undo does not update the selection. \
10331                     If this is occurring, please add details to \
10332                     https://github.com/zed-industries/zed/issues/22692"
10333                );
10334            }
10335            self.request_autoscroll(Autoscroll::fit(), cx);
10336            self.unmark_text(window, cx);
10337            self.refresh_inline_completion(true, false, window, cx);
10338            cx.emit(EditorEvent::Edited { transaction_id });
10339        }
10340    }
10341
10342    pub fn finalize_last_transaction(&mut self, cx: &mut Context<Self>) {
10343        self.buffer
10344            .update(cx, |buffer, cx| buffer.finalize_last_transaction(cx));
10345    }
10346
10347    pub fn group_until_transaction(&mut self, tx_id: TransactionId, cx: &mut Context<Self>) {
10348        self.buffer
10349            .update(cx, |buffer, cx| buffer.group_until_transaction(tx_id, cx));
10350    }
10351
10352    pub fn move_left(&mut self, _: &MoveLeft, window: &mut Window, cx: &mut Context<Self>) {
10353        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
10354        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10355            s.move_with(|map, selection| {
10356                let cursor = if selection.is_empty() {
10357                    movement::left(map, selection.start)
10358                } else {
10359                    selection.start
10360                };
10361                selection.collapse_to(cursor, SelectionGoal::None);
10362            });
10363        })
10364    }
10365
10366    pub fn select_left(&mut self, _: &SelectLeft, window: &mut Window, cx: &mut Context<Self>) {
10367        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
10368        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10369            s.move_heads_with(|map, head, _| (movement::left(map, head), SelectionGoal::None));
10370        })
10371    }
10372
10373    pub fn move_right(&mut self, _: &MoveRight, window: &mut Window, cx: &mut Context<Self>) {
10374        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
10375        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10376            s.move_with(|map, selection| {
10377                let cursor = if selection.is_empty() {
10378                    movement::right(map, selection.end)
10379                } else {
10380                    selection.end
10381                };
10382                selection.collapse_to(cursor, SelectionGoal::None)
10383            });
10384        })
10385    }
10386
10387    pub fn select_right(&mut self, _: &SelectRight, window: &mut Window, cx: &mut Context<Self>) {
10388        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
10389        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10390            s.move_heads_with(|map, head, _| (movement::right(map, head), SelectionGoal::None));
10391        })
10392    }
10393
10394    pub fn move_up(&mut self, _: &MoveUp, window: &mut Window, cx: &mut Context<Self>) {
10395        if self.take_rename(true, window, cx).is_some() {
10396            return;
10397        }
10398
10399        if matches!(self.mode, EditorMode::SingleLine { .. }) {
10400            cx.propagate();
10401            return;
10402        }
10403
10404        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
10405
10406        let text_layout_details = &self.text_layout_details(window);
10407        let selection_count = self.selections.count();
10408        let first_selection = self.selections.first_anchor();
10409
10410        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10411            s.move_with(|map, selection| {
10412                if !selection.is_empty() {
10413                    selection.goal = SelectionGoal::None;
10414                }
10415                let (cursor, goal) = movement::up(
10416                    map,
10417                    selection.start,
10418                    selection.goal,
10419                    false,
10420                    text_layout_details,
10421                );
10422                selection.collapse_to(cursor, goal);
10423            });
10424        });
10425
10426        if selection_count == 1 && first_selection.range() == self.selections.first_anchor().range()
10427        {
10428            cx.propagate();
10429        }
10430    }
10431
10432    pub fn move_up_by_lines(
10433        &mut self,
10434        action: &MoveUpByLines,
10435        window: &mut Window,
10436        cx: &mut Context<Self>,
10437    ) {
10438        if self.take_rename(true, window, cx).is_some() {
10439            return;
10440        }
10441
10442        if matches!(self.mode, EditorMode::SingleLine { .. }) {
10443            cx.propagate();
10444            return;
10445        }
10446
10447        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
10448
10449        let text_layout_details = &self.text_layout_details(window);
10450
10451        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10452            s.move_with(|map, selection| {
10453                if !selection.is_empty() {
10454                    selection.goal = SelectionGoal::None;
10455                }
10456                let (cursor, goal) = movement::up_by_rows(
10457                    map,
10458                    selection.start,
10459                    action.lines,
10460                    selection.goal,
10461                    false,
10462                    text_layout_details,
10463                );
10464                selection.collapse_to(cursor, goal);
10465            });
10466        })
10467    }
10468
10469    pub fn move_down_by_lines(
10470        &mut self,
10471        action: &MoveDownByLines,
10472        window: &mut Window,
10473        cx: &mut Context<Self>,
10474    ) {
10475        if self.take_rename(true, window, cx).is_some() {
10476            return;
10477        }
10478
10479        if matches!(self.mode, EditorMode::SingleLine { .. }) {
10480            cx.propagate();
10481            return;
10482        }
10483
10484        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
10485
10486        let text_layout_details = &self.text_layout_details(window);
10487
10488        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10489            s.move_with(|map, selection| {
10490                if !selection.is_empty() {
10491                    selection.goal = SelectionGoal::None;
10492                }
10493                let (cursor, goal) = movement::down_by_rows(
10494                    map,
10495                    selection.start,
10496                    action.lines,
10497                    selection.goal,
10498                    false,
10499                    text_layout_details,
10500                );
10501                selection.collapse_to(cursor, goal);
10502            });
10503        })
10504    }
10505
10506    pub fn select_down_by_lines(
10507        &mut self,
10508        action: &SelectDownByLines,
10509        window: &mut Window,
10510        cx: &mut Context<Self>,
10511    ) {
10512        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
10513        let text_layout_details = &self.text_layout_details(window);
10514        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10515            s.move_heads_with(|map, head, goal| {
10516                movement::down_by_rows(map, head, action.lines, goal, false, text_layout_details)
10517            })
10518        })
10519    }
10520
10521    pub fn select_up_by_lines(
10522        &mut self,
10523        action: &SelectUpByLines,
10524        window: &mut Window,
10525        cx: &mut Context<Self>,
10526    ) {
10527        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
10528        let text_layout_details = &self.text_layout_details(window);
10529        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10530            s.move_heads_with(|map, head, goal| {
10531                movement::up_by_rows(map, head, action.lines, goal, false, text_layout_details)
10532            })
10533        })
10534    }
10535
10536    pub fn select_page_up(
10537        &mut self,
10538        _: &SelectPageUp,
10539        window: &mut Window,
10540        cx: &mut Context<Self>,
10541    ) {
10542        let Some(row_count) = self.visible_row_count() else {
10543            return;
10544        };
10545
10546        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
10547
10548        let text_layout_details = &self.text_layout_details(window);
10549
10550        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10551            s.move_heads_with(|map, head, goal| {
10552                movement::up_by_rows(map, head, row_count, goal, false, text_layout_details)
10553            })
10554        })
10555    }
10556
10557    pub fn move_page_up(
10558        &mut self,
10559        action: &MovePageUp,
10560        window: &mut Window,
10561        cx: &mut Context<Self>,
10562    ) {
10563        if self.take_rename(true, window, cx).is_some() {
10564            return;
10565        }
10566
10567        if self
10568            .context_menu
10569            .borrow_mut()
10570            .as_mut()
10571            .map(|menu| menu.select_first(self.completion_provider.as_deref(), cx))
10572            .unwrap_or(false)
10573        {
10574            return;
10575        }
10576
10577        if matches!(self.mode, EditorMode::SingleLine { .. }) {
10578            cx.propagate();
10579            return;
10580        }
10581
10582        let Some(row_count) = self.visible_row_count() else {
10583            return;
10584        };
10585
10586        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
10587
10588        let autoscroll = if action.center_cursor {
10589            Autoscroll::center()
10590        } else {
10591            Autoscroll::fit()
10592        };
10593
10594        let text_layout_details = &self.text_layout_details(window);
10595
10596        self.change_selections(Some(autoscroll), window, cx, |s| {
10597            s.move_with(|map, selection| {
10598                if !selection.is_empty() {
10599                    selection.goal = SelectionGoal::None;
10600                }
10601                let (cursor, goal) = movement::up_by_rows(
10602                    map,
10603                    selection.end,
10604                    row_count,
10605                    selection.goal,
10606                    false,
10607                    text_layout_details,
10608                );
10609                selection.collapse_to(cursor, goal);
10610            });
10611        });
10612    }
10613
10614    pub fn select_up(&mut self, _: &SelectUp, window: &mut Window, cx: &mut Context<Self>) {
10615        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
10616        let text_layout_details = &self.text_layout_details(window);
10617        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10618            s.move_heads_with(|map, head, goal| {
10619                movement::up(map, head, goal, false, text_layout_details)
10620            })
10621        })
10622    }
10623
10624    pub fn move_down(&mut self, _: &MoveDown, window: &mut Window, cx: &mut Context<Self>) {
10625        self.take_rename(true, window, cx);
10626
10627        if matches!(self.mode, EditorMode::SingleLine { .. }) {
10628            cx.propagate();
10629            return;
10630        }
10631
10632        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
10633
10634        let text_layout_details = &self.text_layout_details(window);
10635        let selection_count = self.selections.count();
10636        let first_selection = self.selections.first_anchor();
10637
10638        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10639            s.move_with(|map, selection| {
10640                if !selection.is_empty() {
10641                    selection.goal = SelectionGoal::None;
10642                }
10643                let (cursor, goal) = movement::down(
10644                    map,
10645                    selection.end,
10646                    selection.goal,
10647                    false,
10648                    text_layout_details,
10649                );
10650                selection.collapse_to(cursor, goal);
10651            });
10652        });
10653
10654        if selection_count == 1 && first_selection.range() == self.selections.first_anchor().range()
10655        {
10656            cx.propagate();
10657        }
10658    }
10659
10660    pub fn select_page_down(
10661        &mut self,
10662        _: &SelectPageDown,
10663        window: &mut Window,
10664        cx: &mut Context<Self>,
10665    ) {
10666        let Some(row_count) = self.visible_row_count() else {
10667            return;
10668        };
10669
10670        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
10671
10672        let text_layout_details = &self.text_layout_details(window);
10673
10674        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10675            s.move_heads_with(|map, head, goal| {
10676                movement::down_by_rows(map, head, row_count, goal, false, text_layout_details)
10677            })
10678        })
10679    }
10680
10681    pub fn move_page_down(
10682        &mut self,
10683        action: &MovePageDown,
10684        window: &mut Window,
10685        cx: &mut Context<Self>,
10686    ) {
10687        if self.take_rename(true, window, cx).is_some() {
10688            return;
10689        }
10690
10691        if self
10692            .context_menu
10693            .borrow_mut()
10694            .as_mut()
10695            .map(|menu| menu.select_last(self.completion_provider.as_deref(), cx))
10696            .unwrap_or(false)
10697        {
10698            return;
10699        }
10700
10701        if matches!(self.mode, EditorMode::SingleLine { .. }) {
10702            cx.propagate();
10703            return;
10704        }
10705
10706        let Some(row_count) = self.visible_row_count() else {
10707            return;
10708        };
10709
10710        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
10711
10712        let autoscroll = if action.center_cursor {
10713            Autoscroll::center()
10714        } else {
10715            Autoscroll::fit()
10716        };
10717
10718        let text_layout_details = &self.text_layout_details(window);
10719        self.change_selections(Some(autoscroll), window, cx, |s| {
10720            s.move_with(|map, selection| {
10721                if !selection.is_empty() {
10722                    selection.goal = SelectionGoal::None;
10723                }
10724                let (cursor, goal) = movement::down_by_rows(
10725                    map,
10726                    selection.end,
10727                    row_count,
10728                    selection.goal,
10729                    false,
10730                    text_layout_details,
10731                );
10732                selection.collapse_to(cursor, goal);
10733            });
10734        });
10735    }
10736
10737    pub fn select_down(&mut self, _: &SelectDown, window: &mut Window, cx: &mut Context<Self>) {
10738        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
10739        let text_layout_details = &self.text_layout_details(window);
10740        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10741            s.move_heads_with(|map, head, goal| {
10742                movement::down(map, head, goal, false, text_layout_details)
10743            })
10744        });
10745    }
10746
10747    pub fn context_menu_first(
10748        &mut self,
10749        _: &ContextMenuFirst,
10750        _window: &mut Window,
10751        cx: &mut Context<Self>,
10752    ) {
10753        if let Some(context_menu) = self.context_menu.borrow_mut().as_mut() {
10754            context_menu.select_first(self.completion_provider.as_deref(), cx);
10755        }
10756    }
10757
10758    pub fn context_menu_prev(
10759        &mut self,
10760        _: &ContextMenuPrevious,
10761        _window: &mut Window,
10762        cx: &mut Context<Self>,
10763    ) {
10764        if let Some(context_menu) = self.context_menu.borrow_mut().as_mut() {
10765            context_menu.select_prev(self.completion_provider.as_deref(), cx);
10766        }
10767    }
10768
10769    pub fn context_menu_next(
10770        &mut self,
10771        _: &ContextMenuNext,
10772        _window: &mut Window,
10773        cx: &mut Context<Self>,
10774    ) {
10775        if let Some(context_menu) = self.context_menu.borrow_mut().as_mut() {
10776            context_menu.select_next(self.completion_provider.as_deref(), cx);
10777        }
10778    }
10779
10780    pub fn context_menu_last(
10781        &mut self,
10782        _: &ContextMenuLast,
10783        _window: &mut Window,
10784        cx: &mut Context<Self>,
10785    ) {
10786        if let Some(context_menu) = self.context_menu.borrow_mut().as_mut() {
10787            context_menu.select_last(self.completion_provider.as_deref(), cx);
10788        }
10789    }
10790
10791    pub fn move_to_previous_word_start(
10792        &mut self,
10793        _: &MoveToPreviousWordStart,
10794        window: &mut Window,
10795        cx: &mut Context<Self>,
10796    ) {
10797        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
10798        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10799            s.move_cursors_with(|map, head, _| {
10800                (
10801                    movement::previous_word_start(map, head),
10802                    SelectionGoal::None,
10803                )
10804            });
10805        })
10806    }
10807
10808    pub fn move_to_previous_subword_start(
10809        &mut self,
10810        _: &MoveToPreviousSubwordStart,
10811        window: &mut Window,
10812        cx: &mut Context<Self>,
10813    ) {
10814        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
10815        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10816            s.move_cursors_with(|map, head, _| {
10817                (
10818                    movement::previous_subword_start(map, head),
10819                    SelectionGoal::None,
10820                )
10821            });
10822        })
10823    }
10824
10825    pub fn select_to_previous_word_start(
10826        &mut self,
10827        _: &SelectToPreviousWordStart,
10828        window: &mut Window,
10829        cx: &mut Context<Self>,
10830    ) {
10831        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
10832        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10833            s.move_heads_with(|map, head, _| {
10834                (
10835                    movement::previous_word_start(map, head),
10836                    SelectionGoal::None,
10837                )
10838            });
10839        })
10840    }
10841
10842    pub fn select_to_previous_subword_start(
10843        &mut self,
10844        _: &SelectToPreviousSubwordStart,
10845        window: &mut Window,
10846        cx: &mut Context<Self>,
10847    ) {
10848        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
10849        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10850            s.move_heads_with(|map, head, _| {
10851                (
10852                    movement::previous_subword_start(map, head),
10853                    SelectionGoal::None,
10854                )
10855            });
10856        })
10857    }
10858
10859    pub fn delete_to_previous_word_start(
10860        &mut self,
10861        action: &DeleteToPreviousWordStart,
10862        window: &mut Window,
10863        cx: &mut Context<Self>,
10864    ) {
10865        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
10866        self.transact(window, cx, |this, window, cx| {
10867            this.select_autoclose_pair(window, cx);
10868            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10869                s.move_with(|map, selection| {
10870                    if selection.is_empty() {
10871                        let cursor = if action.ignore_newlines {
10872                            movement::previous_word_start(map, selection.head())
10873                        } else {
10874                            movement::previous_word_start_or_newline(map, selection.head())
10875                        };
10876                        selection.set_head(cursor, SelectionGoal::None);
10877                    }
10878                });
10879            });
10880            this.insert("", window, cx);
10881        });
10882    }
10883
10884    pub fn delete_to_previous_subword_start(
10885        &mut self,
10886        _: &DeleteToPreviousSubwordStart,
10887        window: &mut Window,
10888        cx: &mut Context<Self>,
10889    ) {
10890        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
10891        self.transact(window, cx, |this, window, cx| {
10892            this.select_autoclose_pair(window, cx);
10893            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10894                s.move_with(|map, selection| {
10895                    if selection.is_empty() {
10896                        let cursor = movement::previous_subword_start(map, selection.head());
10897                        selection.set_head(cursor, SelectionGoal::None);
10898                    }
10899                });
10900            });
10901            this.insert("", window, cx);
10902        });
10903    }
10904
10905    pub fn move_to_next_word_end(
10906        &mut self,
10907        _: &MoveToNextWordEnd,
10908        window: &mut Window,
10909        cx: &mut Context<Self>,
10910    ) {
10911        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
10912        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10913            s.move_cursors_with(|map, head, _| {
10914                (movement::next_word_end(map, head), SelectionGoal::None)
10915            });
10916        })
10917    }
10918
10919    pub fn move_to_next_subword_end(
10920        &mut self,
10921        _: &MoveToNextSubwordEnd,
10922        window: &mut Window,
10923        cx: &mut Context<Self>,
10924    ) {
10925        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
10926        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10927            s.move_cursors_with(|map, head, _| {
10928                (movement::next_subword_end(map, head), SelectionGoal::None)
10929            });
10930        })
10931    }
10932
10933    pub fn select_to_next_word_end(
10934        &mut self,
10935        _: &SelectToNextWordEnd,
10936        window: &mut Window,
10937        cx: &mut Context<Self>,
10938    ) {
10939        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
10940        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10941            s.move_heads_with(|map, head, _| {
10942                (movement::next_word_end(map, head), SelectionGoal::None)
10943            });
10944        })
10945    }
10946
10947    pub fn select_to_next_subword_end(
10948        &mut self,
10949        _: &SelectToNextSubwordEnd,
10950        window: &mut Window,
10951        cx: &mut Context<Self>,
10952    ) {
10953        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
10954        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10955            s.move_heads_with(|map, head, _| {
10956                (movement::next_subword_end(map, head), SelectionGoal::None)
10957            });
10958        })
10959    }
10960
10961    pub fn delete_to_next_word_end(
10962        &mut self,
10963        action: &DeleteToNextWordEnd,
10964        window: &mut Window,
10965        cx: &mut Context<Self>,
10966    ) {
10967        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
10968        self.transact(window, cx, |this, window, cx| {
10969            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10970                s.move_with(|map, selection| {
10971                    if selection.is_empty() {
10972                        let cursor = if action.ignore_newlines {
10973                            movement::next_word_end(map, selection.head())
10974                        } else {
10975                            movement::next_word_end_or_newline(map, selection.head())
10976                        };
10977                        selection.set_head(cursor, SelectionGoal::None);
10978                    }
10979                });
10980            });
10981            this.insert("", window, cx);
10982        });
10983    }
10984
10985    pub fn delete_to_next_subword_end(
10986        &mut self,
10987        _: &DeleteToNextSubwordEnd,
10988        window: &mut Window,
10989        cx: &mut Context<Self>,
10990    ) {
10991        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
10992        self.transact(window, cx, |this, window, cx| {
10993            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10994                s.move_with(|map, selection| {
10995                    if selection.is_empty() {
10996                        let cursor = movement::next_subword_end(map, selection.head());
10997                        selection.set_head(cursor, SelectionGoal::None);
10998                    }
10999                });
11000            });
11001            this.insert("", window, cx);
11002        });
11003    }
11004
11005    pub fn move_to_beginning_of_line(
11006        &mut self,
11007        action: &MoveToBeginningOfLine,
11008        window: &mut Window,
11009        cx: &mut Context<Self>,
11010    ) {
11011        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11012        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11013            s.move_cursors_with(|map, head, _| {
11014                (
11015                    movement::indented_line_beginning(
11016                        map,
11017                        head,
11018                        action.stop_at_soft_wraps,
11019                        action.stop_at_indent,
11020                    ),
11021                    SelectionGoal::None,
11022                )
11023            });
11024        })
11025    }
11026
11027    pub fn select_to_beginning_of_line(
11028        &mut self,
11029        action: &SelectToBeginningOfLine,
11030        window: &mut Window,
11031        cx: &mut Context<Self>,
11032    ) {
11033        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11034        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11035            s.move_heads_with(|map, head, _| {
11036                (
11037                    movement::indented_line_beginning(
11038                        map,
11039                        head,
11040                        action.stop_at_soft_wraps,
11041                        action.stop_at_indent,
11042                    ),
11043                    SelectionGoal::None,
11044                )
11045            });
11046        });
11047    }
11048
11049    pub fn delete_to_beginning_of_line(
11050        &mut self,
11051        action: &DeleteToBeginningOfLine,
11052        window: &mut Window,
11053        cx: &mut Context<Self>,
11054    ) {
11055        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
11056        self.transact(window, cx, |this, window, cx| {
11057            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11058                s.move_with(|_, selection| {
11059                    selection.reversed = true;
11060                });
11061            });
11062
11063            this.select_to_beginning_of_line(
11064                &SelectToBeginningOfLine {
11065                    stop_at_soft_wraps: false,
11066                    stop_at_indent: action.stop_at_indent,
11067                },
11068                window,
11069                cx,
11070            );
11071            this.backspace(&Backspace, window, cx);
11072        });
11073    }
11074
11075    pub fn move_to_end_of_line(
11076        &mut self,
11077        action: &MoveToEndOfLine,
11078        window: &mut Window,
11079        cx: &mut Context<Self>,
11080    ) {
11081        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11082        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11083            s.move_cursors_with(|map, head, _| {
11084                (
11085                    movement::line_end(map, head, action.stop_at_soft_wraps),
11086                    SelectionGoal::None,
11087                )
11088            });
11089        })
11090    }
11091
11092    pub fn select_to_end_of_line(
11093        &mut self,
11094        action: &SelectToEndOfLine,
11095        window: &mut Window,
11096        cx: &mut Context<Self>,
11097    ) {
11098        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11099        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11100            s.move_heads_with(|map, head, _| {
11101                (
11102                    movement::line_end(map, head, action.stop_at_soft_wraps),
11103                    SelectionGoal::None,
11104                )
11105            });
11106        })
11107    }
11108
11109    pub fn delete_to_end_of_line(
11110        &mut self,
11111        _: &DeleteToEndOfLine,
11112        window: &mut Window,
11113        cx: &mut Context<Self>,
11114    ) {
11115        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
11116        self.transact(window, cx, |this, window, cx| {
11117            this.select_to_end_of_line(
11118                &SelectToEndOfLine {
11119                    stop_at_soft_wraps: false,
11120                },
11121                window,
11122                cx,
11123            );
11124            this.delete(&Delete, window, cx);
11125        });
11126    }
11127
11128    pub fn cut_to_end_of_line(
11129        &mut self,
11130        _: &CutToEndOfLine,
11131        window: &mut Window,
11132        cx: &mut Context<Self>,
11133    ) {
11134        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
11135        self.transact(window, cx, |this, window, cx| {
11136            this.select_to_end_of_line(
11137                &SelectToEndOfLine {
11138                    stop_at_soft_wraps: false,
11139                },
11140                window,
11141                cx,
11142            );
11143            this.cut(&Cut, window, cx);
11144        });
11145    }
11146
11147    pub fn move_to_start_of_paragraph(
11148        &mut self,
11149        _: &MoveToStartOfParagraph,
11150        window: &mut Window,
11151        cx: &mut Context<Self>,
11152    ) {
11153        if matches!(self.mode, EditorMode::SingleLine { .. }) {
11154            cx.propagate();
11155            return;
11156        }
11157        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11158        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11159            s.move_with(|map, selection| {
11160                selection.collapse_to(
11161                    movement::start_of_paragraph(map, selection.head(), 1),
11162                    SelectionGoal::None,
11163                )
11164            });
11165        })
11166    }
11167
11168    pub fn move_to_end_of_paragraph(
11169        &mut self,
11170        _: &MoveToEndOfParagraph,
11171        window: &mut Window,
11172        cx: &mut Context<Self>,
11173    ) {
11174        if matches!(self.mode, EditorMode::SingleLine { .. }) {
11175            cx.propagate();
11176            return;
11177        }
11178        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11179        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11180            s.move_with(|map, selection| {
11181                selection.collapse_to(
11182                    movement::end_of_paragraph(map, selection.head(), 1),
11183                    SelectionGoal::None,
11184                )
11185            });
11186        })
11187    }
11188
11189    pub fn select_to_start_of_paragraph(
11190        &mut self,
11191        _: &SelectToStartOfParagraph,
11192        window: &mut Window,
11193        cx: &mut Context<Self>,
11194    ) {
11195        if matches!(self.mode, EditorMode::SingleLine { .. }) {
11196            cx.propagate();
11197            return;
11198        }
11199        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11200        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11201            s.move_heads_with(|map, head, _| {
11202                (
11203                    movement::start_of_paragraph(map, head, 1),
11204                    SelectionGoal::None,
11205                )
11206            });
11207        })
11208    }
11209
11210    pub fn select_to_end_of_paragraph(
11211        &mut self,
11212        _: &SelectToEndOfParagraph,
11213        window: &mut Window,
11214        cx: &mut Context<Self>,
11215    ) {
11216        if matches!(self.mode, EditorMode::SingleLine { .. }) {
11217            cx.propagate();
11218            return;
11219        }
11220        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11221        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11222            s.move_heads_with(|map, head, _| {
11223                (
11224                    movement::end_of_paragraph(map, head, 1),
11225                    SelectionGoal::None,
11226                )
11227            });
11228        })
11229    }
11230
11231    pub fn move_to_start_of_excerpt(
11232        &mut self,
11233        _: &MoveToStartOfExcerpt,
11234        window: &mut Window,
11235        cx: &mut Context<Self>,
11236    ) {
11237        if matches!(self.mode, EditorMode::SingleLine { .. }) {
11238            cx.propagate();
11239            return;
11240        }
11241        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11242        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11243            s.move_with(|map, selection| {
11244                selection.collapse_to(
11245                    movement::start_of_excerpt(
11246                        map,
11247                        selection.head(),
11248                        workspace::searchable::Direction::Prev,
11249                    ),
11250                    SelectionGoal::None,
11251                )
11252            });
11253        })
11254    }
11255
11256    pub fn move_to_start_of_next_excerpt(
11257        &mut self,
11258        _: &MoveToStartOfNextExcerpt,
11259        window: &mut Window,
11260        cx: &mut Context<Self>,
11261    ) {
11262        if matches!(self.mode, EditorMode::SingleLine { .. }) {
11263            cx.propagate();
11264            return;
11265        }
11266
11267        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11268            s.move_with(|map, selection| {
11269                selection.collapse_to(
11270                    movement::start_of_excerpt(
11271                        map,
11272                        selection.head(),
11273                        workspace::searchable::Direction::Next,
11274                    ),
11275                    SelectionGoal::None,
11276                )
11277            });
11278        })
11279    }
11280
11281    pub fn move_to_end_of_excerpt(
11282        &mut self,
11283        _: &MoveToEndOfExcerpt,
11284        window: &mut Window,
11285        cx: &mut Context<Self>,
11286    ) {
11287        if matches!(self.mode, EditorMode::SingleLine { .. }) {
11288            cx.propagate();
11289            return;
11290        }
11291        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11292        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11293            s.move_with(|map, selection| {
11294                selection.collapse_to(
11295                    movement::end_of_excerpt(
11296                        map,
11297                        selection.head(),
11298                        workspace::searchable::Direction::Next,
11299                    ),
11300                    SelectionGoal::None,
11301                )
11302            });
11303        })
11304    }
11305
11306    pub fn move_to_end_of_previous_excerpt(
11307        &mut self,
11308        _: &MoveToEndOfPreviousExcerpt,
11309        window: &mut Window,
11310        cx: &mut Context<Self>,
11311    ) {
11312        if matches!(self.mode, EditorMode::SingleLine { .. }) {
11313            cx.propagate();
11314            return;
11315        }
11316        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11317        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11318            s.move_with(|map, selection| {
11319                selection.collapse_to(
11320                    movement::end_of_excerpt(
11321                        map,
11322                        selection.head(),
11323                        workspace::searchable::Direction::Prev,
11324                    ),
11325                    SelectionGoal::None,
11326                )
11327            });
11328        })
11329    }
11330
11331    pub fn select_to_start_of_excerpt(
11332        &mut self,
11333        _: &SelectToStartOfExcerpt,
11334        window: &mut Window,
11335        cx: &mut Context<Self>,
11336    ) {
11337        if matches!(self.mode, EditorMode::SingleLine { .. }) {
11338            cx.propagate();
11339            return;
11340        }
11341        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11342        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11343            s.move_heads_with(|map, head, _| {
11344                (
11345                    movement::start_of_excerpt(map, head, workspace::searchable::Direction::Prev),
11346                    SelectionGoal::None,
11347                )
11348            });
11349        })
11350    }
11351
11352    pub fn select_to_start_of_next_excerpt(
11353        &mut self,
11354        _: &SelectToStartOfNextExcerpt,
11355        window: &mut Window,
11356        cx: &mut Context<Self>,
11357    ) {
11358        if matches!(self.mode, EditorMode::SingleLine { .. }) {
11359            cx.propagate();
11360            return;
11361        }
11362        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11363        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11364            s.move_heads_with(|map, head, _| {
11365                (
11366                    movement::start_of_excerpt(map, head, workspace::searchable::Direction::Next),
11367                    SelectionGoal::None,
11368                )
11369            });
11370        })
11371    }
11372
11373    pub fn select_to_end_of_excerpt(
11374        &mut self,
11375        _: &SelectToEndOfExcerpt,
11376        window: &mut Window,
11377        cx: &mut Context<Self>,
11378    ) {
11379        if matches!(self.mode, EditorMode::SingleLine { .. }) {
11380            cx.propagate();
11381            return;
11382        }
11383        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11384        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11385            s.move_heads_with(|map, head, _| {
11386                (
11387                    movement::end_of_excerpt(map, head, workspace::searchable::Direction::Next),
11388                    SelectionGoal::None,
11389                )
11390            });
11391        })
11392    }
11393
11394    pub fn select_to_end_of_previous_excerpt(
11395        &mut self,
11396        _: &SelectToEndOfPreviousExcerpt,
11397        window: &mut Window,
11398        cx: &mut Context<Self>,
11399    ) {
11400        if matches!(self.mode, EditorMode::SingleLine { .. }) {
11401            cx.propagate();
11402            return;
11403        }
11404        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11405        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11406            s.move_heads_with(|map, head, _| {
11407                (
11408                    movement::end_of_excerpt(map, head, workspace::searchable::Direction::Prev),
11409                    SelectionGoal::None,
11410                )
11411            });
11412        })
11413    }
11414
11415    pub fn move_to_beginning(
11416        &mut self,
11417        _: &MoveToBeginning,
11418        window: &mut Window,
11419        cx: &mut Context<Self>,
11420    ) {
11421        if matches!(self.mode, EditorMode::SingleLine { .. }) {
11422            cx.propagate();
11423            return;
11424        }
11425        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11426        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11427            s.select_ranges(vec![0..0]);
11428        });
11429    }
11430
11431    pub fn select_to_beginning(
11432        &mut self,
11433        _: &SelectToBeginning,
11434        window: &mut Window,
11435        cx: &mut Context<Self>,
11436    ) {
11437        let mut selection = self.selections.last::<Point>(cx);
11438        selection.set_head(Point::zero(), SelectionGoal::None);
11439        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11440        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11441            s.select(vec![selection]);
11442        });
11443    }
11444
11445    pub fn move_to_end(&mut self, _: &MoveToEnd, window: &mut Window, cx: &mut Context<Self>) {
11446        if matches!(self.mode, EditorMode::SingleLine { .. }) {
11447            cx.propagate();
11448            return;
11449        }
11450        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11451        let cursor = self.buffer.read(cx).read(cx).len();
11452        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11453            s.select_ranges(vec![cursor..cursor])
11454        });
11455    }
11456
11457    pub fn set_nav_history(&mut self, nav_history: Option<ItemNavHistory>) {
11458        self.nav_history = nav_history;
11459    }
11460
11461    pub fn nav_history(&self) -> Option<&ItemNavHistory> {
11462        self.nav_history.as_ref()
11463    }
11464
11465    pub fn create_nav_history_entry(&mut self, cx: &mut Context<Self>) {
11466        self.push_to_nav_history(self.selections.newest_anchor().head(), None, false, cx);
11467    }
11468
11469    fn push_to_nav_history(
11470        &mut self,
11471        cursor_anchor: Anchor,
11472        new_position: Option<Point>,
11473        is_deactivate: bool,
11474        cx: &mut Context<Self>,
11475    ) {
11476        if let Some(nav_history) = self.nav_history.as_mut() {
11477            let buffer = self.buffer.read(cx).read(cx);
11478            let cursor_position = cursor_anchor.to_point(&buffer);
11479            let scroll_state = self.scroll_manager.anchor();
11480            let scroll_top_row = scroll_state.top_row(&buffer);
11481            drop(buffer);
11482
11483            if let Some(new_position) = new_position {
11484                let row_delta = (new_position.row as i64 - cursor_position.row as i64).abs();
11485                if row_delta < MIN_NAVIGATION_HISTORY_ROW_DELTA {
11486                    return;
11487                }
11488            }
11489
11490            nav_history.push(
11491                Some(NavigationData {
11492                    cursor_anchor,
11493                    cursor_position,
11494                    scroll_anchor: scroll_state,
11495                    scroll_top_row,
11496                }),
11497                cx,
11498            );
11499            cx.emit(EditorEvent::PushedToNavHistory {
11500                anchor: cursor_anchor,
11501                is_deactivate,
11502            })
11503        }
11504    }
11505
11506    pub fn select_to_end(&mut self, _: &SelectToEnd, window: &mut Window, cx: &mut Context<Self>) {
11507        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11508        let buffer = self.buffer.read(cx).snapshot(cx);
11509        let mut selection = self.selections.first::<usize>(cx);
11510        selection.set_head(buffer.len(), SelectionGoal::None);
11511        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11512            s.select(vec![selection]);
11513        });
11514    }
11515
11516    pub fn select_all(&mut self, _: &SelectAll, window: &mut Window, cx: &mut Context<Self>) {
11517        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11518        let end = self.buffer.read(cx).read(cx).len();
11519        self.change_selections(None, window, cx, |s| {
11520            s.select_ranges(vec![0..end]);
11521        });
11522    }
11523
11524    pub fn select_line(&mut self, _: &SelectLine, window: &mut Window, cx: &mut Context<Self>) {
11525        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11526        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
11527        let mut selections = self.selections.all::<Point>(cx);
11528        let max_point = display_map.buffer_snapshot.max_point();
11529        for selection in &mut selections {
11530            let rows = selection.spanned_rows(true, &display_map);
11531            selection.start = Point::new(rows.start.0, 0);
11532            selection.end = cmp::min(max_point, Point::new(rows.end.0, 0));
11533            selection.reversed = false;
11534        }
11535        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11536            s.select(selections);
11537        });
11538    }
11539
11540    pub fn split_selection_into_lines(
11541        &mut self,
11542        _: &SplitSelectionIntoLines,
11543        window: &mut Window,
11544        cx: &mut Context<Self>,
11545    ) {
11546        let selections = self
11547            .selections
11548            .all::<Point>(cx)
11549            .into_iter()
11550            .map(|selection| selection.start..selection.end)
11551            .collect::<Vec<_>>();
11552        self.unfold_ranges(&selections, true, true, cx);
11553
11554        let mut new_selection_ranges = Vec::new();
11555        {
11556            let buffer = self.buffer.read(cx).read(cx);
11557            for selection in selections {
11558                for row in selection.start.row..selection.end.row {
11559                    let cursor = Point::new(row, buffer.line_len(MultiBufferRow(row)));
11560                    new_selection_ranges.push(cursor..cursor);
11561                }
11562
11563                let is_multiline_selection = selection.start.row != selection.end.row;
11564                // Don't insert last one if it's a multi-line selection ending at the start of a line,
11565                // so this action feels more ergonomic when paired with other selection operations
11566                let should_skip_last = is_multiline_selection && selection.end.column == 0;
11567                if !should_skip_last {
11568                    new_selection_ranges.push(selection.end..selection.end);
11569                }
11570            }
11571        }
11572        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11573            s.select_ranges(new_selection_ranges);
11574        });
11575    }
11576
11577    pub fn add_selection_above(
11578        &mut self,
11579        _: &AddSelectionAbove,
11580        window: &mut Window,
11581        cx: &mut Context<Self>,
11582    ) {
11583        self.add_selection(true, window, cx);
11584    }
11585
11586    pub fn add_selection_below(
11587        &mut self,
11588        _: &AddSelectionBelow,
11589        window: &mut Window,
11590        cx: &mut Context<Self>,
11591    ) {
11592        self.add_selection(false, window, cx);
11593    }
11594
11595    fn add_selection(&mut self, above: bool, window: &mut Window, cx: &mut Context<Self>) {
11596        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11597
11598        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
11599        let mut selections = self.selections.all::<Point>(cx);
11600        let text_layout_details = self.text_layout_details(window);
11601        let mut state = self.add_selections_state.take().unwrap_or_else(|| {
11602            let oldest_selection = selections.iter().min_by_key(|s| s.id).unwrap().clone();
11603            let range = oldest_selection.display_range(&display_map).sorted();
11604
11605            let start_x = display_map.x_for_display_point(range.start, &text_layout_details);
11606            let end_x = display_map.x_for_display_point(range.end, &text_layout_details);
11607            let positions = start_x.min(end_x)..start_x.max(end_x);
11608
11609            selections.clear();
11610            let mut stack = Vec::new();
11611            for row in range.start.row().0..=range.end.row().0 {
11612                if let Some(selection) = self.selections.build_columnar_selection(
11613                    &display_map,
11614                    DisplayRow(row),
11615                    &positions,
11616                    oldest_selection.reversed,
11617                    &text_layout_details,
11618                ) {
11619                    stack.push(selection.id);
11620                    selections.push(selection);
11621                }
11622            }
11623
11624            if above {
11625                stack.reverse();
11626            }
11627
11628            AddSelectionsState { above, stack }
11629        });
11630
11631        let last_added_selection = *state.stack.last().unwrap();
11632        let mut new_selections = Vec::new();
11633        if above == state.above {
11634            let end_row = if above {
11635                DisplayRow(0)
11636            } else {
11637                display_map.max_point().row()
11638            };
11639
11640            'outer: for selection in selections {
11641                if selection.id == last_added_selection {
11642                    let range = selection.display_range(&display_map).sorted();
11643                    debug_assert_eq!(range.start.row(), range.end.row());
11644                    let mut row = range.start.row();
11645                    let positions =
11646                        if let SelectionGoal::HorizontalRange { start, end } = selection.goal {
11647                            px(start)..px(end)
11648                        } else {
11649                            let start_x =
11650                                display_map.x_for_display_point(range.start, &text_layout_details);
11651                            let end_x =
11652                                display_map.x_for_display_point(range.end, &text_layout_details);
11653                            start_x.min(end_x)..start_x.max(end_x)
11654                        };
11655
11656                    while row != end_row {
11657                        if above {
11658                            row.0 -= 1;
11659                        } else {
11660                            row.0 += 1;
11661                        }
11662
11663                        if let Some(new_selection) = self.selections.build_columnar_selection(
11664                            &display_map,
11665                            row,
11666                            &positions,
11667                            selection.reversed,
11668                            &text_layout_details,
11669                        ) {
11670                            state.stack.push(new_selection.id);
11671                            if above {
11672                                new_selections.push(new_selection);
11673                                new_selections.push(selection);
11674                            } else {
11675                                new_selections.push(selection);
11676                                new_selections.push(new_selection);
11677                            }
11678
11679                            continue 'outer;
11680                        }
11681                    }
11682                }
11683
11684                new_selections.push(selection);
11685            }
11686        } else {
11687            new_selections = selections;
11688            new_selections.retain(|s| s.id != last_added_selection);
11689            state.stack.pop();
11690        }
11691
11692        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11693            s.select(new_selections);
11694        });
11695        if state.stack.len() > 1 {
11696            self.add_selections_state = Some(state);
11697        }
11698    }
11699
11700    pub fn select_next_match_internal(
11701        &mut self,
11702        display_map: &DisplaySnapshot,
11703        replace_newest: bool,
11704        autoscroll: Option<Autoscroll>,
11705        window: &mut Window,
11706        cx: &mut Context<Self>,
11707    ) -> Result<()> {
11708        fn select_next_match_ranges(
11709            this: &mut Editor,
11710            range: Range<usize>,
11711            replace_newest: bool,
11712            auto_scroll: Option<Autoscroll>,
11713            window: &mut Window,
11714            cx: &mut Context<Editor>,
11715        ) {
11716            this.unfold_ranges(&[range.clone()], false, auto_scroll.is_some(), cx);
11717            this.change_selections(auto_scroll, window, cx, |s| {
11718                if replace_newest {
11719                    s.delete(s.newest_anchor().id);
11720                }
11721                s.insert_range(range.clone());
11722            });
11723        }
11724
11725        let buffer = &display_map.buffer_snapshot;
11726        let mut selections = self.selections.all::<usize>(cx);
11727        if let Some(mut select_next_state) = self.select_next_state.take() {
11728            let query = &select_next_state.query;
11729            if !select_next_state.done {
11730                let first_selection = selections.iter().min_by_key(|s| s.id).unwrap();
11731                let last_selection = selections.iter().max_by_key(|s| s.id).unwrap();
11732                let mut next_selected_range = None;
11733
11734                let bytes_after_last_selection =
11735                    buffer.bytes_in_range(last_selection.end..buffer.len());
11736                let bytes_before_first_selection = buffer.bytes_in_range(0..first_selection.start);
11737                let query_matches = query
11738                    .stream_find_iter(bytes_after_last_selection)
11739                    .map(|result| (last_selection.end, result))
11740                    .chain(
11741                        query
11742                            .stream_find_iter(bytes_before_first_selection)
11743                            .map(|result| (0, result)),
11744                    );
11745
11746                for (start_offset, query_match) in query_matches {
11747                    let query_match = query_match.unwrap(); // can only fail due to I/O
11748                    let offset_range =
11749                        start_offset + query_match.start()..start_offset + query_match.end();
11750                    let display_range = offset_range.start.to_display_point(display_map)
11751                        ..offset_range.end.to_display_point(display_map);
11752
11753                    if !select_next_state.wordwise
11754                        || (!movement::is_inside_word(display_map, display_range.start)
11755                            && !movement::is_inside_word(display_map, display_range.end))
11756                    {
11757                        // TODO: This is n^2, because we might check all the selections
11758                        if !selections
11759                            .iter()
11760                            .any(|selection| selection.range().overlaps(&offset_range))
11761                        {
11762                            next_selected_range = Some(offset_range);
11763                            break;
11764                        }
11765                    }
11766                }
11767
11768                if let Some(next_selected_range) = next_selected_range {
11769                    select_next_match_ranges(
11770                        self,
11771                        next_selected_range,
11772                        replace_newest,
11773                        autoscroll,
11774                        window,
11775                        cx,
11776                    );
11777                } else {
11778                    select_next_state.done = true;
11779                }
11780            }
11781
11782            self.select_next_state = Some(select_next_state);
11783        } else {
11784            let mut only_carets = true;
11785            let mut same_text_selected = true;
11786            let mut selected_text = None;
11787
11788            let mut selections_iter = selections.iter().peekable();
11789            while let Some(selection) = selections_iter.next() {
11790                if selection.start != selection.end {
11791                    only_carets = false;
11792                }
11793
11794                if same_text_selected {
11795                    if selected_text.is_none() {
11796                        selected_text =
11797                            Some(buffer.text_for_range(selection.range()).collect::<String>());
11798                    }
11799
11800                    if let Some(next_selection) = selections_iter.peek() {
11801                        if next_selection.range().len() == selection.range().len() {
11802                            let next_selected_text = buffer
11803                                .text_for_range(next_selection.range())
11804                                .collect::<String>();
11805                            if Some(next_selected_text) != selected_text {
11806                                same_text_selected = false;
11807                                selected_text = None;
11808                            }
11809                        } else {
11810                            same_text_selected = false;
11811                            selected_text = None;
11812                        }
11813                    }
11814                }
11815            }
11816
11817            if only_carets {
11818                for selection in &mut selections {
11819                    let word_range = movement::surrounding_word(
11820                        display_map,
11821                        selection.start.to_display_point(display_map),
11822                    );
11823                    selection.start = word_range.start.to_offset(display_map, Bias::Left);
11824                    selection.end = word_range.end.to_offset(display_map, Bias::Left);
11825                    selection.goal = SelectionGoal::None;
11826                    selection.reversed = false;
11827                    select_next_match_ranges(
11828                        self,
11829                        selection.start..selection.end,
11830                        replace_newest,
11831                        autoscroll,
11832                        window,
11833                        cx,
11834                    );
11835                }
11836
11837                if selections.len() == 1 {
11838                    let selection = selections
11839                        .last()
11840                        .expect("ensured that there's only one selection");
11841                    let query = buffer
11842                        .text_for_range(selection.start..selection.end)
11843                        .collect::<String>();
11844                    let is_empty = query.is_empty();
11845                    let select_state = SelectNextState {
11846                        query: AhoCorasick::new(&[query])?,
11847                        wordwise: true,
11848                        done: is_empty,
11849                    };
11850                    self.select_next_state = Some(select_state);
11851                } else {
11852                    self.select_next_state = None;
11853                }
11854            } else if let Some(selected_text) = selected_text {
11855                self.select_next_state = Some(SelectNextState {
11856                    query: AhoCorasick::new(&[selected_text])?,
11857                    wordwise: false,
11858                    done: false,
11859                });
11860                self.select_next_match_internal(
11861                    display_map,
11862                    replace_newest,
11863                    autoscroll,
11864                    window,
11865                    cx,
11866                )?;
11867            }
11868        }
11869        Ok(())
11870    }
11871
11872    pub fn select_all_matches(
11873        &mut self,
11874        _action: &SelectAllMatches,
11875        window: &mut Window,
11876        cx: &mut Context<Self>,
11877    ) -> Result<()> {
11878        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11879
11880        self.push_to_selection_history();
11881        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
11882
11883        self.select_next_match_internal(&display_map, false, None, window, cx)?;
11884        let Some(select_next_state) = self.select_next_state.as_mut() else {
11885            return Ok(());
11886        };
11887        if select_next_state.done {
11888            return Ok(());
11889        }
11890
11891        let mut new_selections = Vec::new();
11892
11893        let reversed = self.selections.oldest::<usize>(cx).reversed;
11894        let buffer = &display_map.buffer_snapshot;
11895        let query_matches = select_next_state
11896            .query
11897            .stream_find_iter(buffer.bytes_in_range(0..buffer.len()));
11898
11899        for query_match in query_matches.into_iter() {
11900            let query_match = query_match.context("query match for select all action")?; // can only fail due to I/O
11901            let offset_range = if reversed {
11902                query_match.end()..query_match.start()
11903            } else {
11904                query_match.start()..query_match.end()
11905            };
11906            let display_range = offset_range.start.to_display_point(&display_map)
11907                ..offset_range.end.to_display_point(&display_map);
11908
11909            if !select_next_state.wordwise
11910                || (!movement::is_inside_word(&display_map, display_range.start)
11911                    && !movement::is_inside_word(&display_map, display_range.end))
11912            {
11913                new_selections.push(offset_range.start..offset_range.end);
11914            }
11915        }
11916
11917        select_next_state.done = true;
11918        self.unfold_ranges(&new_selections.clone(), false, false, cx);
11919        self.change_selections(None, window, cx, |selections| {
11920            selections.select_ranges(new_selections)
11921        });
11922
11923        Ok(())
11924    }
11925
11926    pub fn select_next(
11927        &mut self,
11928        action: &SelectNext,
11929        window: &mut Window,
11930        cx: &mut Context<Self>,
11931    ) -> Result<()> {
11932        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11933        self.push_to_selection_history();
11934        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
11935        self.select_next_match_internal(
11936            &display_map,
11937            action.replace_newest,
11938            Some(Autoscroll::newest()),
11939            window,
11940            cx,
11941        )?;
11942        Ok(())
11943    }
11944
11945    pub fn select_previous(
11946        &mut self,
11947        action: &SelectPrevious,
11948        window: &mut Window,
11949        cx: &mut Context<Self>,
11950    ) -> Result<()> {
11951        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11952        self.push_to_selection_history();
11953        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
11954        let buffer = &display_map.buffer_snapshot;
11955        let mut selections = self.selections.all::<usize>(cx);
11956        if let Some(mut select_prev_state) = self.select_prev_state.take() {
11957            let query = &select_prev_state.query;
11958            if !select_prev_state.done {
11959                let first_selection = selections.iter().min_by_key(|s| s.id).unwrap();
11960                let last_selection = selections.iter().max_by_key(|s| s.id).unwrap();
11961                let mut next_selected_range = None;
11962                // When we're iterating matches backwards, the oldest match will actually be the furthest one in the buffer.
11963                let bytes_before_last_selection =
11964                    buffer.reversed_bytes_in_range(0..last_selection.start);
11965                let bytes_after_first_selection =
11966                    buffer.reversed_bytes_in_range(first_selection.end..buffer.len());
11967                let query_matches = query
11968                    .stream_find_iter(bytes_before_last_selection)
11969                    .map(|result| (last_selection.start, result))
11970                    .chain(
11971                        query
11972                            .stream_find_iter(bytes_after_first_selection)
11973                            .map(|result| (buffer.len(), result)),
11974                    );
11975                for (end_offset, query_match) in query_matches {
11976                    let query_match = query_match.unwrap(); // can only fail due to I/O
11977                    let offset_range =
11978                        end_offset - query_match.end()..end_offset - query_match.start();
11979                    let display_range = offset_range.start.to_display_point(&display_map)
11980                        ..offset_range.end.to_display_point(&display_map);
11981
11982                    if !select_prev_state.wordwise
11983                        || (!movement::is_inside_word(&display_map, display_range.start)
11984                            && !movement::is_inside_word(&display_map, display_range.end))
11985                    {
11986                        next_selected_range = Some(offset_range);
11987                        break;
11988                    }
11989                }
11990
11991                if let Some(next_selected_range) = next_selected_range {
11992                    self.unfold_ranges(&[next_selected_range.clone()], false, true, cx);
11993                    self.change_selections(Some(Autoscroll::newest()), window, cx, |s| {
11994                        if action.replace_newest {
11995                            s.delete(s.newest_anchor().id);
11996                        }
11997                        s.insert_range(next_selected_range);
11998                    });
11999                } else {
12000                    select_prev_state.done = true;
12001                }
12002            }
12003
12004            self.select_prev_state = Some(select_prev_state);
12005        } else {
12006            let mut only_carets = true;
12007            let mut same_text_selected = true;
12008            let mut selected_text = None;
12009
12010            let mut selections_iter = selections.iter().peekable();
12011            while let Some(selection) = selections_iter.next() {
12012                if selection.start != selection.end {
12013                    only_carets = false;
12014                }
12015
12016                if same_text_selected {
12017                    if selected_text.is_none() {
12018                        selected_text =
12019                            Some(buffer.text_for_range(selection.range()).collect::<String>());
12020                    }
12021
12022                    if let Some(next_selection) = selections_iter.peek() {
12023                        if next_selection.range().len() == selection.range().len() {
12024                            let next_selected_text = buffer
12025                                .text_for_range(next_selection.range())
12026                                .collect::<String>();
12027                            if Some(next_selected_text) != selected_text {
12028                                same_text_selected = false;
12029                                selected_text = None;
12030                            }
12031                        } else {
12032                            same_text_selected = false;
12033                            selected_text = None;
12034                        }
12035                    }
12036                }
12037            }
12038
12039            if only_carets {
12040                for selection in &mut selections {
12041                    let word_range = movement::surrounding_word(
12042                        &display_map,
12043                        selection.start.to_display_point(&display_map),
12044                    );
12045                    selection.start = word_range.start.to_offset(&display_map, Bias::Left);
12046                    selection.end = word_range.end.to_offset(&display_map, Bias::Left);
12047                    selection.goal = SelectionGoal::None;
12048                    selection.reversed = false;
12049                }
12050                if selections.len() == 1 {
12051                    let selection = selections
12052                        .last()
12053                        .expect("ensured that there's only one selection");
12054                    let query = buffer
12055                        .text_for_range(selection.start..selection.end)
12056                        .collect::<String>();
12057                    let is_empty = query.is_empty();
12058                    let select_state = SelectNextState {
12059                        query: AhoCorasick::new(&[query.chars().rev().collect::<String>()])?,
12060                        wordwise: true,
12061                        done: is_empty,
12062                    };
12063                    self.select_prev_state = Some(select_state);
12064                } else {
12065                    self.select_prev_state = None;
12066                }
12067
12068                self.unfold_ranges(
12069                    &selections.iter().map(|s| s.range()).collect::<Vec<_>>(),
12070                    false,
12071                    true,
12072                    cx,
12073                );
12074                self.change_selections(Some(Autoscroll::newest()), window, cx, |s| {
12075                    s.select(selections);
12076                });
12077            } else if let Some(selected_text) = selected_text {
12078                self.select_prev_state = Some(SelectNextState {
12079                    query: AhoCorasick::new(&[selected_text.chars().rev().collect::<String>()])?,
12080                    wordwise: false,
12081                    done: false,
12082                });
12083                self.select_previous(action, window, cx)?;
12084            }
12085        }
12086        Ok(())
12087    }
12088
12089    pub fn find_next_match(
12090        &mut self,
12091        _: &FindNextMatch,
12092        window: &mut Window,
12093        cx: &mut Context<Self>,
12094    ) -> Result<()> {
12095        let selections = self.selections.disjoint_anchors();
12096        match selections.first() {
12097            Some(first) if selections.len() >= 2 => {
12098                self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
12099                    s.select_ranges([first.range()]);
12100                });
12101            }
12102            _ => self.select_next(
12103                &SelectNext {
12104                    replace_newest: true,
12105                },
12106                window,
12107                cx,
12108            )?,
12109        }
12110        Ok(())
12111    }
12112
12113    pub fn find_previous_match(
12114        &mut self,
12115        _: &FindPreviousMatch,
12116        window: &mut Window,
12117        cx: &mut Context<Self>,
12118    ) -> Result<()> {
12119        let selections = self.selections.disjoint_anchors();
12120        match selections.last() {
12121            Some(last) if selections.len() >= 2 => {
12122                self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
12123                    s.select_ranges([last.range()]);
12124                });
12125            }
12126            _ => self.select_previous(
12127                &SelectPrevious {
12128                    replace_newest: true,
12129                },
12130                window,
12131                cx,
12132            )?,
12133        }
12134        Ok(())
12135    }
12136
12137    pub fn toggle_comments(
12138        &mut self,
12139        action: &ToggleComments,
12140        window: &mut Window,
12141        cx: &mut Context<Self>,
12142    ) {
12143        if self.read_only(cx) {
12144            return;
12145        }
12146        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
12147        let text_layout_details = &self.text_layout_details(window);
12148        self.transact(window, cx, |this, window, cx| {
12149            let mut selections = this.selections.all::<MultiBufferPoint>(cx);
12150            let mut edits = Vec::new();
12151            let mut selection_edit_ranges = Vec::new();
12152            let mut last_toggled_row = None;
12153            let snapshot = this.buffer.read(cx).read(cx);
12154            let empty_str: Arc<str> = Arc::default();
12155            let mut suffixes_inserted = Vec::new();
12156            let ignore_indent = action.ignore_indent;
12157
12158            fn comment_prefix_range(
12159                snapshot: &MultiBufferSnapshot,
12160                row: MultiBufferRow,
12161                comment_prefix: &str,
12162                comment_prefix_whitespace: &str,
12163                ignore_indent: bool,
12164            ) -> Range<Point> {
12165                let indent_size = if ignore_indent {
12166                    0
12167                } else {
12168                    snapshot.indent_size_for_line(row).len
12169                };
12170
12171                let start = Point::new(row.0, indent_size);
12172
12173                let mut line_bytes = snapshot
12174                    .bytes_in_range(start..snapshot.max_point())
12175                    .flatten()
12176                    .copied();
12177
12178                // If this line currently begins with the line comment prefix, then record
12179                // the range containing the prefix.
12180                if line_bytes
12181                    .by_ref()
12182                    .take(comment_prefix.len())
12183                    .eq(comment_prefix.bytes())
12184                {
12185                    // Include any whitespace that matches the comment prefix.
12186                    let matching_whitespace_len = line_bytes
12187                        .zip(comment_prefix_whitespace.bytes())
12188                        .take_while(|(a, b)| a == b)
12189                        .count() as u32;
12190                    let end = Point::new(
12191                        start.row,
12192                        start.column + comment_prefix.len() as u32 + matching_whitespace_len,
12193                    );
12194                    start..end
12195                } else {
12196                    start..start
12197                }
12198            }
12199
12200            fn comment_suffix_range(
12201                snapshot: &MultiBufferSnapshot,
12202                row: MultiBufferRow,
12203                comment_suffix: &str,
12204                comment_suffix_has_leading_space: bool,
12205            ) -> Range<Point> {
12206                let end = Point::new(row.0, snapshot.line_len(row));
12207                let suffix_start_column = end.column.saturating_sub(comment_suffix.len() as u32);
12208
12209                let mut line_end_bytes = snapshot
12210                    .bytes_in_range(Point::new(end.row, suffix_start_column.saturating_sub(1))..end)
12211                    .flatten()
12212                    .copied();
12213
12214                let leading_space_len = if suffix_start_column > 0
12215                    && line_end_bytes.next() == Some(b' ')
12216                    && comment_suffix_has_leading_space
12217                {
12218                    1
12219                } else {
12220                    0
12221                };
12222
12223                // If this line currently begins with the line comment prefix, then record
12224                // the range containing the prefix.
12225                if line_end_bytes.by_ref().eq(comment_suffix.bytes()) {
12226                    let start = Point::new(end.row, suffix_start_column - leading_space_len);
12227                    start..end
12228                } else {
12229                    end..end
12230                }
12231            }
12232
12233            // TODO: Handle selections that cross excerpts
12234            for selection in &mut selections {
12235                let start_column = snapshot
12236                    .indent_size_for_line(MultiBufferRow(selection.start.row))
12237                    .len;
12238                let language = if let Some(language) =
12239                    snapshot.language_scope_at(Point::new(selection.start.row, start_column))
12240                {
12241                    language
12242                } else {
12243                    continue;
12244                };
12245
12246                selection_edit_ranges.clear();
12247
12248                // If multiple selections contain a given row, avoid processing that
12249                // row more than once.
12250                let mut start_row = MultiBufferRow(selection.start.row);
12251                if last_toggled_row == Some(start_row) {
12252                    start_row = start_row.next_row();
12253                }
12254                let end_row =
12255                    if selection.end.row > selection.start.row && selection.end.column == 0 {
12256                        MultiBufferRow(selection.end.row - 1)
12257                    } else {
12258                        MultiBufferRow(selection.end.row)
12259                    };
12260                last_toggled_row = Some(end_row);
12261
12262                if start_row > end_row {
12263                    continue;
12264                }
12265
12266                // If the language has line comments, toggle those.
12267                let mut full_comment_prefixes = language.line_comment_prefixes().to_vec();
12268
12269                // If ignore_indent is set, trim spaces from the right side of all full_comment_prefixes
12270                if ignore_indent {
12271                    full_comment_prefixes = full_comment_prefixes
12272                        .into_iter()
12273                        .map(|s| Arc::from(s.trim_end()))
12274                        .collect();
12275                }
12276
12277                if !full_comment_prefixes.is_empty() {
12278                    let first_prefix = full_comment_prefixes
12279                        .first()
12280                        .expect("prefixes is non-empty");
12281                    let prefix_trimmed_lengths = full_comment_prefixes
12282                        .iter()
12283                        .map(|p| p.trim_end_matches(' ').len())
12284                        .collect::<SmallVec<[usize; 4]>>();
12285
12286                    let mut all_selection_lines_are_comments = true;
12287
12288                    for row in start_row.0..=end_row.0 {
12289                        let row = MultiBufferRow(row);
12290                        if start_row < end_row && snapshot.is_line_blank(row) {
12291                            continue;
12292                        }
12293
12294                        let prefix_range = full_comment_prefixes
12295                            .iter()
12296                            .zip(prefix_trimmed_lengths.iter().copied())
12297                            .map(|(prefix, trimmed_prefix_len)| {
12298                                comment_prefix_range(
12299                                    snapshot.deref(),
12300                                    row,
12301                                    &prefix[..trimmed_prefix_len],
12302                                    &prefix[trimmed_prefix_len..],
12303                                    ignore_indent,
12304                                )
12305                            })
12306                            .max_by_key(|range| range.end.column - range.start.column)
12307                            .expect("prefixes is non-empty");
12308
12309                        if prefix_range.is_empty() {
12310                            all_selection_lines_are_comments = false;
12311                        }
12312
12313                        selection_edit_ranges.push(prefix_range);
12314                    }
12315
12316                    if all_selection_lines_are_comments {
12317                        edits.extend(
12318                            selection_edit_ranges
12319                                .iter()
12320                                .cloned()
12321                                .map(|range| (range, empty_str.clone())),
12322                        );
12323                    } else {
12324                        let min_column = selection_edit_ranges
12325                            .iter()
12326                            .map(|range| range.start.column)
12327                            .min()
12328                            .unwrap_or(0);
12329                        edits.extend(selection_edit_ranges.iter().map(|range| {
12330                            let position = Point::new(range.start.row, min_column);
12331                            (position..position, first_prefix.clone())
12332                        }));
12333                    }
12334                } else if let Some((full_comment_prefix, comment_suffix)) =
12335                    language.block_comment_delimiters()
12336                {
12337                    let comment_prefix = full_comment_prefix.trim_end_matches(' ');
12338                    let comment_prefix_whitespace = &full_comment_prefix[comment_prefix.len()..];
12339                    let prefix_range = comment_prefix_range(
12340                        snapshot.deref(),
12341                        start_row,
12342                        comment_prefix,
12343                        comment_prefix_whitespace,
12344                        ignore_indent,
12345                    );
12346                    let suffix_range = comment_suffix_range(
12347                        snapshot.deref(),
12348                        end_row,
12349                        comment_suffix.trim_start_matches(' '),
12350                        comment_suffix.starts_with(' '),
12351                    );
12352
12353                    if prefix_range.is_empty() || suffix_range.is_empty() {
12354                        edits.push((
12355                            prefix_range.start..prefix_range.start,
12356                            full_comment_prefix.clone(),
12357                        ));
12358                        edits.push((suffix_range.end..suffix_range.end, comment_suffix.clone()));
12359                        suffixes_inserted.push((end_row, comment_suffix.len()));
12360                    } else {
12361                        edits.push((prefix_range, empty_str.clone()));
12362                        edits.push((suffix_range, empty_str.clone()));
12363                    }
12364                } else {
12365                    continue;
12366                }
12367            }
12368
12369            drop(snapshot);
12370            this.buffer.update(cx, |buffer, cx| {
12371                buffer.edit(edits, None, cx);
12372            });
12373
12374            // Adjust selections so that they end before any comment suffixes that
12375            // were inserted.
12376            let mut suffixes_inserted = suffixes_inserted.into_iter().peekable();
12377            let mut selections = this.selections.all::<Point>(cx);
12378            let snapshot = this.buffer.read(cx).read(cx);
12379            for selection in &mut selections {
12380                while let Some((row, suffix_len)) = suffixes_inserted.peek().copied() {
12381                    match row.cmp(&MultiBufferRow(selection.end.row)) {
12382                        Ordering::Less => {
12383                            suffixes_inserted.next();
12384                            continue;
12385                        }
12386                        Ordering::Greater => break,
12387                        Ordering::Equal => {
12388                            if selection.end.column == snapshot.line_len(row) {
12389                                if selection.is_empty() {
12390                                    selection.start.column -= suffix_len as u32;
12391                                }
12392                                selection.end.column -= suffix_len as u32;
12393                            }
12394                            break;
12395                        }
12396                    }
12397                }
12398            }
12399
12400            drop(snapshot);
12401            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
12402                s.select(selections)
12403            });
12404
12405            let selections = this.selections.all::<Point>(cx);
12406            let selections_on_single_row = selections.windows(2).all(|selections| {
12407                selections[0].start.row == selections[1].start.row
12408                    && selections[0].end.row == selections[1].end.row
12409                    && selections[0].start.row == selections[0].end.row
12410            });
12411            let selections_selecting = selections
12412                .iter()
12413                .any(|selection| selection.start != selection.end);
12414            let advance_downwards = action.advance_downwards
12415                && selections_on_single_row
12416                && !selections_selecting
12417                && !matches!(this.mode, EditorMode::SingleLine { .. });
12418
12419            if advance_downwards {
12420                let snapshot = this.buffer.read(cx).snapshot(cx);
12421
12422                this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
12423                    s.move_cursors_with(|display_snapshot, display_point, _| {
12424                        let mut point = display_point.to_point(display_snapshot);
12425                        point.row += 1;
12426                        point = snapshot.clip_point(point, Bias::Left);
12427                        let display_point = point.to_display_point(display_snapshot);
12428                        let goal = SelectionGoal::HorizontalPosition(
12429                            display_snapshot
12430                                .x_for_display_point(display_point, text_layout_details)
12431                                .into(),
12432                        );
12433                        (display_point, goal)
12434                    })
12435                });
12436            }
12437        });
12438    }
12439
12440    pub fn select_enclosing_symbol(
12441        &mut self,
12442        _: &SelectEnclosingSymbol,
12443        window: &mut Window,
12444        cx: &mut Context<Self>,
12445    ) {
12446        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
12447
12448        let buffer = self.buffer.read(cx).snapshot(cx);
12449        let old_selections = self.selections.all::<usize>(cx).into_boxed_slice();
12450
12451        fn update_selection(
12452            selection: &Selection<usize>,
12453            buffer_snap: &MultiBufferSnapshot,
12454        ) -> Option<Selection<usize>> {
12455            let cursor = selection.head();
12456            let (_buffer_id, symbols) = buffer_snap.symbols_containing(cursor, None)?;
12457            for symbol in symbols.iter().rev() {
12458                let start = symbol.range.start.to_offset(buffer_snap);
12459                let end = symbol.range.end.to_offset(buffer_snap);
12460                let new_range = start..end;
12461                if start < selection.start || end > selection.end {
12462                    return Some(Selection {
12463                        id: selection.id,
12464                        start: new_range.start,
12465                        end: new_range.end,
12466                        goal: SelectionGoal::None,
12467                        reversed: selection.reversed,
12468                    });
12469                }
12470            }
12471            None
12472        }
12473
12474        let mut selected_larger_symbol = false;
12475        let new_selections = old_selections
12476            .iter()
12477            .map(|selection| match update_selection(selection, &buffer) {
12478                Some(new_selection) => {
12479                    if new_selection.range() != selection.range() {
12480                        selected_larger_symbol = true;
12481                    }
12482                    new_selection
12483                }
12484                None => selection.clone(),
12485            })
12486            .collect::<Vec<_>>();
12487
12488        if selected_larger_symbol {
12489            self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
12490                s.select(new_selections);
12491            });
12492        }
12493    }
12494
12495    pub fn select_larger_syntax_node(
12496        &mut self,
12497        _: &SelectLargerSyntaxNode,
12498        window: &mut Window,
12499        cx: &mut Context<Self>,
12500    ) {
12501        let Some(visible_row_count) = self.visible_row_count() else {
12502            return;
12503        };
12504        let old_selections: Box<[_]> = self.selections.all::<usize>(cx).into();
12505        if old_selections.is_empty() {
12506            return;
12507        }
12508
12509        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
12510
12511        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
12512        let buffer = self.buffer.read(cx).snapshot(cx);
12513
12514        let mut selected_larger_node = false;
12515        let mut new_selections = old_selections
12516            .iter()
12517            .map(|selection| {
12518                let old_range = selection.start..selection.end;
12519                let mut new_range = old_range.clone();
12520                let mut new_node = None;
12521                while let Some((node, containing_range)) = buffer.syntax_ancestor(new_range.clone())
12522                {
12523                    new_node = Some(node);
12524                    new_range = match containing_range {
12525                        MultiOrSingleBufferOffsetRange::Single(_) => break,
12526                        MultiOrSingleBufferOffsetRange::Multi(range) => range,
12527                    };
12528                    if !display_map.intersects_fold(new_range.start)
12529                        && !display_map.intersects_fold(new_range.end)
12530                    {
12531                        break;
12532                    }
12533                }
12534
12535                if let Some(node) = new_node {
12536                    // Log the ancestor, to support using this action as a way to explore TreeSitter
12537                    // nodes. Parent and grandparent are also logged because this operation will not
12538                    // visit nodes that have the same range as their parent.
12539                    log::info!("Node: {node:?}");
12540                    let parent = node.parent();
12541                    log::info!("Parent: {parent:?}");
12542                    let grandparent = parent.and_then(|x| x.parent());
12543                    log::info!("Grandparent: {grandparent:?}");
12544                }
12545
12546                selected_larger_node |= new_range != old_range;
12547                Selection {
12548                    id: selection.id,
12549                    start: new_range.start,
12550                    end: new_range.end,
12551                    goal: SelectionGoal::None,
12552                    reversed: selection.reversed,
12553                }
12554            })
12555            .collect::<Vec<_>>();
12556
12557        if !selected_larger_node {
12558            return; // don't put this call in the history
12559        }
12560
12561        // scroll based on transformation done to the last selection created by the user
12562        let (last_old, last_new) = old_selections
12563            .last()
12564            .zip(new_selections.last().cloned())
12565            .expect("old_selections isn't empty");
12566
12567        // revert selection
12568        let is_selection_reversed = {
12569            let should_newest_selection_be_reversed = last_old.start != last_new.start;
12570            new_selections.last_mut().expect("checked above").reversed =
12571                should_newest_selection_be_reversed;
12572            should_newest_selection_be_reversed
12573        };
12574
12575        if selected_larger_node {
12576            self.select_syntax_node_history.disable_clearing = true;
12577            self.change_selections(None, window, cx, |s| {
12578                s.select(new_selections.clone());
12579            });
12580            self.select_syntax_node_history.disable_clearing = false;
12581        }
12582
12583        let start_row = last_new.start.to_display_point(&display_map).row().0;
12584        let end_row = last_new.end.to_display_point(&display_map).row().0;
12585        let selection_height = end_row - start_row + 1;
12586        let scroll_margin_rows = self.vertical_scroll_margin() as u32;
12587
12588        let fits_on_the_screen = visible_row_count >= selection_height + scroll_margin_rows * 2;
12589        let scroll_behavior = if fits_on_the_screen {
12590            self.request_autoscroll(Autoscroll::fit(), cx);
12591            SelectSyntaxNodeScrollBehavior::FitSelection
12592        } else if is_selection_reversed {
12593            self.scroll_cursor_top(&ScrollCursorTop, window, cx);
12594            SelectSyntaxNodeScrollBehavior::CursorTop
12595        } else {
12596            self.scroll_cursor_bottom(&ScrollCursorBottom, window, cx);
12597            SelectSyntaxNodeScrollBehavior::CursorBottom
12598        };
12599
12600        self.select_syntax_node_history.push((
12601            old_selections,
12602            scroll_behavior,
12603            is_selection_reversed,
12604        ));
12605    }
12606
12607    pub fn select_smaller_syntax_node(
12608        &mut self,
12609        _: &SelectSmallerSyntaxNode,
12610        window: &mut Window,
12611        cx: &mut Context<Self>,
12612    ) {
12613        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
12614
12615        if let Some((mut selections, scroll_behavior, is_selection_reversed)) =
12616            self.select_syntax_node_history.pop()
12617        {
12618            if let Some(selection) = selections.last_mut() {
12619                selection.reversed = is_selection_reversed;
12620            }
12621
12622            self.select_syntax_node_history.disable_clearing = true;
12623            self.change_selections(None, window, cx, |s| {
12624                s.select(selections.to_vec());
12625            });
12626            self.select_syntax_node_history.disable_clearing = false;
12627
12628            match scroll_behavior {
12629                SelectSyntaxNodeScrollBehavior::CursorTop => {
12630                    self.scroll_cursor_top(&ScrollCursorTop, window, cx);
12631                }
12632                SelectSyntaxNodeScrollBehavior::FitSelection => {
12633                    self.request_autoscroll(Autoscroll::fit(), cx);
12634                }
12635                SelectSyntaxNodeScrollBehavior::CursorBottom => {
12636                    self.scroll_cursor_bottom(&ScrollCursorBottom, window, cx);
12637                }
12638            }
12639        }
12640    }
12641
12642    fn refresh_runnables(&mut self, window: &mut Window, cx: &mut Context<Self>) -> Task<()> {
12643        if !EditorSettings::get_global(cx).gutter.runnables {
12644            self.clear_tasks();
12645            return Task::ready(());
12646        }
12647        let project = self.project.as_ref().map(Entity::downgrade);
12648        let task_sources = self.lsp_task_sources(cx);
12649        cx.spawn_in(window, async move |editor, cx| {
12650            cx.background_executor().timer(UPDATE_DEBOUNCE).await;
12651            let Some(project) = project.and_then(|p| p.upgrade()) else {
12652                return;
12653            };
12654            let Ok(display_snapshot) = editor.update(cx, |this, cx| {
12655                this.display_map.update(cx, |map, cx| map.snapshot(cx))
12656            }) else {
12657                return;
12658            };
12659
12660            let hide_runnables = project
12661                .update(cx, |project, cx| {
12662                    // Do not display any test indicators in non-dev server remote projects.
12663                    project.is_via_collab() && project.ssh_connection_string(cx).is_none()
12664                })
12665                .unwrap_or(true);
12666            if hide_runnables {
12667                return;
12668            }
12669            let new_rows =
12670                cx.background_spawn({
12671                    let snapshot = display_snapshot.clone();
12672                    async move {
12673                        Self::fetch_runnable_ranges(&snapshot, Anchor::min()..Anchor::max())
12674                    }
12675                })
12676                    .await;
12677            let Ok(lsp_tasks) =
12678                cx.update(|_, cx| crate::lsp_tasks(project.clone(), &task_sources, None, cx))
12679            else {
12680                return;
12681            };
12682            let lsp_tasks = lsp_tasks.await;
12683
12684            let Ok(mut lsp_tasks_by_rows) = cx.update(|_, cx| {
12685                lsp_tasks
12686                    .into_iter()
12687                    .flat_map(|(kind, tasks)| {
12688                        tasks.into_iter().filter_map(move |(location, task)| {
12689                            Some((kind.clone(), location?, task))
12690                        })
12691                    })
12692                    .fold(HashMap::default(), |mut acc, (kind, location, task)| {
12693                        let buffer = location.target.buffer;
12694                        let buffer_snapshot = buffer.read(cx).snapshot();
12695                        let offset = display_snapshot.buffer_snapshot.excerpts().find_map(
12696                            |(excerpt_id, snapshot, _)| {
12697                                if snapshot.remote_id() == buffer_snapshot.remote_id() {
12698                                    display_snapshot
12699                                        .buffer_snapshot
12700                                        .anchor_in_excerpt(excerpt_id, location.target.range.start)
12701                                } else {
12702                                    None
12703                                }
12704                            },
12705                        );
12706                        if let Some(offset) = offset {
12707                            let task_buffer_range =
12708                                location.target.range.to_point(&buffer_snapshot);
12709                            let context_buffer_range =
12710                                task_buffer_range.to_offset(&buffer_snapshot);
12711                            let context_range = BufferOffset(context_buffer_range.start)
12712                                ..BufferOffset(context_buffer_range.end);
12713
12714                            acc.entry((buffer_snapshot.remote_id(), task_buffer_range.start.row))
12715                                .or_insert_with(|| RunnableTasks {
12716                                    templates: Vec::new(),
12717                                    offset,
12718                                    column: task_buffer_range.start.column,
12719                                    extra_variables: HashMap::default(),
12720                                    context_range,
12721                                })
12722                                .templates
12723                                .push((kind, task.original_task().clone()));
12724                        }
12725
12726                        acc
12727                    })
12728            }) else {
12729                return;
12730            };
12731
12732            let rows = Self::runnable_rows(project, display_snapshot, new_rows, cx.clone());
12733            editor
12734                .update(cx, |editor, _| {
12735                    editor.clear_tasks();
12736                    for (key, mut value) in rows {
12737                        if let Some(lsp_tasks) = lsp_tasks_by_rows.remove(&key) {
12738                            value.templates.extend(lsp_tasks.templates);
12739                        }
12740
12741                        editor.insert_tasks(key, value);
12742                    }
12743                    for (key, value) in lsp_tasks_by_rows {
12744                        editor.insert_tasks(key, value);
12745                    }
12746                })
12747                .ok();
12748        })
12749    }
12750    fn fetch_runnable_ranges(
12751        snapshot: &DisplaySnapshot,
12752        range: Range<Anchor>,
12753    ) -> Vec<language::RunnableRange> {
12754        snapshot.buffer_snapshot.runnable_ranges(range).collect()
12755    }
12756
12757    fn runnable_rows(
12758        project: Entity<Project>,
12759        snapshot: DisplaySnapshot,
12760        runnable_ranges: Vec<RunnableRange>,
12761        mut cx: AsyncWindowContext,
12762    ) -> Vec<((BufferId, BufferRow), RunnableTasks)> {
12763        runnable_ranges
12764            .into_iter()
12765            .filter_map(|mut runnable| {
12766                let tasks = cx
12767                    .update(|_, cx| Self::templates_with_tags(&project, &mut runnable.runnable, cx))
12768                    .ok()?;
12769                if tasks.is_empty() {
12770                    return None;
12771                }
12772
12773                let point = runnable.run_range.start.to_point(&snapshot.buffer_snapshot);
12774
12775                let row = snapshot
12776                    .buffer_snapshot
12777                    .buffer_line_for_row(MultiBufferRow(point.row))?
12778                    .1
12779                    .start
12780                    .row;
12781
12782                let context_range =
12783                    BufferOffset(runnable.full_range.start)..BufferOffset(runnable.full_range.end);
12784                Some((
12785                    (runnable.buffer_id, row),
12786                    RunnableTasks {
12787                        templates: tasks,
12788                        offset: snapshot
12789                            .buffer_snapshot
12790                            .anchor_before(runnable.run_range.start),
12791                        context_range,
12792                        column: point.column,
12793                        extra_variables: runnable.extra_captures,
12794                    },
12795                ))
12796            })
12797            .collect()
12798    }
12799
12800    fn templates_with_tags(
12801        project: &Entity<Project>,
12802        runnable: &mut Runnable,
12803        cx: &mut App,
12804    ) -> Vec<(TaskSourceKind, TaskTemplate)> {
12805        let (inventory, worktree_id, file) = project.read_with(cx, |project, cx| {
12806            let (worktree_id, file) = project
12807                .buffer_for_id(runnable.buffer, cx)
12808                .and_then(|buffer| buffer.read(cx).file())
12809                .map(|file| (file.worktree_id(cx), file.clone()))
12810                .unzip();
12811
12812            (
12813                project.task_store().read(cx).task_inventory().cloned(),
12814                worktree_id,
12815                file,
12816            )
12817        });
12818
12819        let mut templates_with_tags = mem::take(&mut runnable.tags)
12820            .into_iter()
12821            .flat_map(|RunnableTag(tag)| {
12822                inventory
12823                    .as_ref()
12824                    .into_iter()
12825                    .flat_map(|inventory| {
12826                        inventory.read(cx).list_tasks(
12827                            file.clone(),
12828                            Some(runnable.language.clone()),
12829                            worktree_id,
12830                            cx,
12831                        )
12832                    })
12833                    .filter(move |(_, template)| {
12834                        template.tags.iter().any(|source_tag| source_tag == &tag)
12835                    })
12836            })
12837            .sorted_by_key(|(kind, _)| kind.to_owned())
12838            .collect::<Vec<_>>();
12839        if let Some((leading_tag_source, _)) = templates_with_tags.first() {
12840            // Strongest source wins; if we have worktree tag binding, prefer that to
12841            // global and language bindings;
12842            // if we have a global binding, prefer that to language binding.
12843            let first_mismatch = templates_with_tags
12844                .iter()
12845                .position(|(tag_source, _)| tag_source != leading_tag_source);
12846            if let Some(index) = first_mismatch {
12847                templates_with_tags.truncate(index);
12848            }
12849        }
12850
12851        templates_with_tags
12852    }
12853
12854    pub fn move_to_enclosing_bracket(
12855        &mut self,
12856        _: &MoveToEnclosingBracket,
12857        window: &mut Window,
12858        cx: &mut Context<Self>,
12859    ) {
12860        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
12861        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
12862            s.move_offsets_with(|snapshot, selection| {
12863                let Some(enclosing_bracket_ranges) =
12864                    snapshot.enclosing_bracket_ranges(selection.start..selection.end)
12865                else {
12866                    return;
12867                };
12868
12869                let mut best_length = usize::MAX;
12870                let mut best_inside = false;
12871                let mut best_in_bracket_range = false;
12872                let mut best_destination = None;
12873                for (open, close) in enclosing_bracket_ranges {
12874                    let close = close.to_inclusive();
12875                    let length = close.end() - open.start;
12876                    let inside = selection.start >= open.end && selection.end <= *close.start();
12877                    let in_bracket_range = open.to_inclusive().contains(&selection.head())
12878                        || close.contains(&selection.head());
12879
12880                    // If best is next to a bracket and current isn't, skip
12881                    if !in_bracket_range && best_in_bracket_range {
12882                        continue;
12883                    }
12884
12885                    // Prefer smaller lengths unless best is inside and current isn't
12886                    if length > best_length && (best_inside || !inside) {
12887                        continue;
12888                    }
12889
12890                    best_length = length;
12891                    best_inside = inside;
12892                    best_in_bracket_range = in_bracket_range;
12893                    best_destination = Some(
12894                        if close.contains(&selection.start) && close.contains(&selection.end) {
12895                            if inside { open.end } else { open.start }
12896                        } else if inside {
12897                            *close.start()
12898                        } else {
12899                            *close.end()
12900                        },
12901                    );
12902                }
12903
12904                if let Some(destination) = best_destination {
12905                    selection.collapse_to(destination, SelectionGoal::None);
12906                }
12907            })
12908        });
12909    }
12910
12911    pub fn undo_selection(
12912        &mut self,
12913        _: &UndoSelection,
12914        window: &mut Window,
12915        cx: &mut Context<Self>,
12916    ) {
12917        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
12918        self.end_selection(window, cx);
12919        self.selection_history.mode = SelectionHistoryMode::Undoing;
12920        if let Some(entry) = self.selection_history.undo_stack.pop_back() {
12921            self.change_selections(None, window, cx, |s| {
12922                s.select_anchors(entry.selections.to_vec())
12923            });
12924            self.select_next_state = entry.select_next_state;
12925            self.select_prev_state = entry.select_prev_state;
12926            self.add_selections_state = entry.add_selections_state;
12927            self.request_autoscroll(Autoscroll::newest(), cx);
12928        }
12929        self.selection_history.mode = SelectionHistoryMode::Normal;
12930    }
12931
12932    pub fn redo_selection(
12933        &mut self,
12934        _: &RedoSelection,
12935        window: &mut Window,
12936        cx: &mut Context<Self>,
12937    ) {
12938        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
12939        self.end_selection(window, cx);
12940        self.selection_history.mode = SelectionHistoryMode::Redoing;
12941        if let Some(entry) = self.selection_history.redo_stack.pop_back() {
12942            self.change_selections(None, window, cx, |s| {
12943                s.select_anchors(entry.selections.to_vec())
12944            });
12945            self.select_next_state = entry.select_next_state;
12946            self.select_prev_state = entry.select_prev_state;
12947            self.add_selections_state = entry.add_selections_state;
12948            self.request_autoscroll(Autoscroll::newest(), cx);
12949        }
12950        self.selection_history.mode = SelectionHistoryMode::Normal;
12951    }
12952
12953    pub fn expand_excerpts(
12954        &mut self,
12955        action: &ExpandExcerpts,
12956        _: &mut Window,
12957        cx: &mut Context<Self>,
12958    ) {
12959        self.expand_excerpts_for_direction(action.lines, ExpandExcerptDirection::UpAndDown, cx)
12960    }
12961
12962    pub fn expand_excerpts_down(
12963        &mut self,
12964        action: &ExpandExcerptsDown,
12965        _: &mut Window,
12966        cx: &mut Context<Self>,
12967    ) {
12968        self.expand_excerpts_for_direction(action.lines, ExpandExcerptDirection::Down, cx)
12969    }
12970
12971    pub fn expand_excerpts_up(
12972        &mut self,
12973        action: &ExpandExcerptsUp,
12974        _: &mut Window,
12975        cx: &mut Context<Self>,
12976    ) {
12977        self.expand_excerpts_for_direction(action.lines, ExpandExcerptDirection::Up, cx)
12978    }
12979
12980    pub fn expand_excerpts_for_direction(
12981        &mut self,
12982        lines: u32,
12983        direction: ExpandExcerptDirection,
12984
12985        cx: &mut Context<Self>,
12986    ) {
12987        let selections = self.selections.disjoint_anchors();
12988
12989        let lines = if lines == 0 {
12990            EditorSettings::get_global(cx).expand_excerpt_lines
12991        } else {
12992            lines
12993        };
12994
12995        self.buffer.update(cx, |buffer, cx| {
12996            let snapshot = buffer.snapshot(cx);
12997            let mut excerpt_ids = selections
12998                .iter()
12999                .flat_map(|selection| snapshot.excerpt_ids_for_range(selection.range()))
13000                .collect::<Vec<_>>();
13001            excerpt_ids.sort();
13002            excerpt_ids.dedup();
13003            buffer.expand_excerpts(excerpt_ids, lines, direction, cx)
13004        })
13005    }
13006
13007    pub fn expand_excerpt(
13008        &mut self,
13009        excerpt: ExcerptId,
13010        direction: ExpandExcerptDirection,
13011        window: &mut Window,
13012        cx: &mut Context<Self>,
13013    ) {
13014        let current_scroll_position = self.scroll_position(cx);
13015        let lines_to_expand = EditorSettings::get_global(cx).expand_excerpt_lines;
13016        let mut should_scroll_up = false;
13017
13018        if direction == ExpandExcerptDirection::Down {
13019            let multi_buffer = self.buffer.read(cx);
13020            let snapshot = multi_buffer.snapshot(cx);
13021            if let Some(buffer_id) = snapshot.buffer_id_for_excerpt(excerpt) {
13022                if let Some(buffer) = multi_buffer.buffer(buffer_id) {
13023                    if let Some(excerpt_range) = snapshot.buffer_range_for_excerpt(excerpt) {
13024                        let buffer_snapshot = buffer.read(cx).snapshot();
13025                        let excerpt_end_row =
13026                            Point::from_anchor(&excerpt_range.end, &buffer_snapshot).row;
13027                        let last_row = buffer_snapshot.max_point().row;
13028                        let lines_below = last_row.saturating_sub(excerpt_end_row);
13029                        should_scroll_up = lines_below >= lines_to_expand;
13030                    }
13031                }
13032            }
13033        }
13034
13035        self.buffer.update(cx, |buffer, cx| {
13036            buffer.expand_excerpts([excerpt], lines_to_expand, direction, cx)
13037        });
13038
13039        if should_scroll_up {
13040            let new_scroll_position =
13041                current_scroll_position + gpui::Point::new(0.0, lines_to_expand as f32);
13042            self.set_scroll_position(new_scroll_position, window, cx);
13043        }
13044    }
13045
13046    pub fn go_to_singleton_buffer_point(
13047        &mut self,
13048        point: Point,
13049        window: &mut Window,
13050        cx: &mut Context<Self>,
13051    ) {
13052        self.go_to_singleton_buffer_range(point..point, window, cx);
13053    }
13054
13055    pub fn go_to_singleton_buffer_range(
13056        &mut self,
13057        range: Range<Point>,
13058        window: &mut Window,
13059        cx: &mut Context<Self>,
13060    ) {
13061        let multibuffer = self.buffer().read(cx);
13062        let Some(buffer) = multibuffer.as_singleton() else {
13063            return;
13064        };
13065        let Some(start) = multibuffer.buffer_point_to_anchor(&buffer, range.start, cx) else {
13066            return;
13067        };
13068        let Some(end) = multibuffer.buffer_point_to_anchor(&buffer, range.end, cx) else {
13069            return;
13070        };
13071        self.change_selections(Some(Autoscroll::center()), window, cx, |s| {
13072            s.select_anchor_ranges([start..end])
13073        });
13074    }
13075
13076    pub fn go_to_diagnostic(
13077        &mut self,
13078        _: &GoToDiagnostic,
13079        window: &mut Window,
13080        cx: &mut Context<Self>,
13081    ) {
13082        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
13083        self.go_to_diagnostic_impl(Direction::Next, window, cx)
13084    }
13085
13086    pub fn go_to_prev_diagnostic(
13087        &mut self,
13088        _: &GoToPreviousDiagnostic,
13089        window: &mut Window,
13090        cx: &mut Context<Self>,
13091    ) {
13092        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
13093        self.go_to_diagnostic_impl(Direction::Prev, window, cx)
13094    }
13095
13096    pub fn go_to_diagnostic_impl(
13097        &mut self,
13098        direction: Direction,
13099        window: &mut Window,
13100        cx: &mut Context<Self>,
13101    ) {
13102        let buffer = self.buffer.read(cx).snapshot(cx);
13103        let selection = self.selections.newest::<usize>(cx);
13104
13105        let mut active_group_id = None;
13106        if let ActiveDiagnostic::Group(active_group) = &self.active_diagnostics {
13107            if active_group.active_range.start.to_offset(&buffer) == selection.start {
13108                active_group_id = Some(active_group.group_id);
13109            }
13110        }
13111
13112        fn filtered(
13113            snapshot: EditorSnapshot,
13114            diagnostics: impl Iterator<Item = DiagnosticEntry<usize>>,
13115        ) -> impl Iterator<Item = DiagnosticEntry<usize>> {
13116            diagnostics
13117                .filter(|entry| entry.range.start != entry.range.end)
13118                .filter(|entry| !entry.diagnostic.is_unnecessary)
13119                .filter(move |entry| !snapshot.intersects_fold(entry.range.start))
13120        }
13121
13122        let snapshot = self.snapshot(window, cx);
13123        let before = filtered(
13124            snapshot.clone(),
13125            buffer
13126                .diagnostics_in_range(0..selection.start)
13127                .filter(|entry| entry.range.start <= selection.start),
13128        );
13129        let after = filtered(
13130            snapshot,
13131            buffer
13132                .diagnostics_in_range(selection.start..buffer.len())
13133                .filter(|entry| entry.range.start >= selection.start),
13134        );
13135
13136        let mut found: Option<DiagnosticEntry<usize>> = None;
13137        if direction == Direction::Prev {
13138            'outer: for prev_diagnostics in [before.collect::<Vec<_>>(), after.collect::<Vec<_>>()]
13139            {
13140                for diagnostic in prev_diagnostics.into_iter().rev() {
13141                    if diagnostic.range.start != selection.start
13142                        || active_group_id
13143                            .is_some_and(|active| diagnostic.diagnostic.group_id < active)
13144                    {
13145                        found = Some(diagnostic);
13146                        break 'outer;
13147                    }
13148                }
13149            }
13150        } else {
13151            for diagnostic in after.chain(before) {
13152                if diagnostic.range.start != selection.start
13153                    || active_group_id.is_some_and(|active| diagnostic.diagnostic.group_id > active)
13154                {
13155                    found = Some(diagnostic);
13156                    break;
13157                }
13158            }
13159        }
13160        let Some(next_diagnostic) = found else {
13161            return;
13162        };
13163
13164        let Some(buffer_id) = buffer.anchor_after(next_diagnostic.range.start).buffer_id else {
13165            return;
13166        };
13167        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
13168            s.select_ranges(vec![
13169                next_diagnostic.range.start..next_diagnostic.range.start,
13170            ])
13171        });
13172        self.activate_diagnostics(buffer_id, next_diagnostic, window, cx);
13173        self.refresh_inline_completion(false, true, window, cx);
13174    }
13175
13176    fn go_to_next_hunk(&mut self, _: &GoToHunk, window: &mut Window, cx: &mut Context<Self>) {
13177        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
13178        let snapshot = self.snapshot(window, cx);
13179        let selection = self.selections.newest::<Point>(cx);
13180        self.go_to_hunk_before_or_after_position(
13181            &snapshot,
13182            selection.head(),
13183            Direction::Next,
13184            window,
13185            cx,
13186        );
13187    }
13188
13189    pub fn go_to_hunk_before_or_after_position(
13190        &mut self,
13191        snapshot: &EditorSnapshot,
13192        position: Point,
13193        direction: Direction,
13194        window: &mut Window,
13195        cx: &mut Context<Editor>,
13196    ) {
13197        let row = if direction == Direction::Next {
13198            self.hunk_after_position(snapshot, position)
13199                .map(|hunk| hunk.row_range.start)
13200        } else {
13201            self.hunk_before_position(snapshot, position)
13202        };
13203
13204        if let Some(row) = row {
13205            let destination = Point::new(row.0, 0);
13206            let autoscroll = Autoscroll::center();
13207
13208            self.unfold_ranges(&[destination..destination], false, false, cx);
13209            self.change_selections(Some(autoscroll), window, cx, |s| {
13210                s.select_ranges([destination..destination]);
13211            });
13212        }
13213    }
13214
13215    fn hunk_after_position(
13216        &mut self,
13217        snapshot: &EditorSnapshot,
13218        position: Point,
13219    ) -> Option<MultiBufferDiffHunk> {
13220        snapshot
13221            .buffer_snapshot
13222            .diff_hunks_in_range(position..snapshot.buffer_snapshot.max_point())
13223            .find(|hunk| hunk.row_range.start.0 > position.row)
13224            .or_else(|| {
13225                snapshot
13226                    .buffer_snapshot
13227                    .diff_hunks_in_range(Point::zero()..position)
13228                    .find(|hunk| hunk.row_range.end.0 < position.row)
13229            })
13230    }
13231
13232    fn go_to_prev_hunk(
13233        &mut self,
13234        _: &GoToPreviousHunk,
13235        window: &mut Window,
13236        cx: &mut Context<Self>,
13237    ) {
13238        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
13239        let snapshot = self.snapshot(window, cx);
13240        let selection = self.selections.newest::<Point>(cx);
13241        self.go_to_hunk_before_or_after_position(
13242            &snapshot,
13243            selection.head(),
13244            Direction::Prev,
13245            window,
13246            cx,
13247        );
13248    }
13249
13250    fn hunk_before_position(
13251        &mut self,
13252        snapshot: &EditorSnapshot,
13253        position: Point,
13254    ) -> Option<MultiBufferRow> {
13255        snapshot
13256            .buffer_snapshot
13257            .diff_hunk_before(position)
13258            .or_else(|| snapshot.buffer_snapshot.diff_hunk_before(Point::MAX))
13259    }
13260
13261    fn go_to_line<T: 'static>(
13262        &mut self,
13263        position: Anchor,
13264        highlight_color: Option<Hsla>,
13265        window: &mut Window,
13266        cx: &mut Context<Self>,
13267    ) {
13268        let snapshot = self.snapshot(window, cx).display_snapshot;
13269        let position = position.to_point(&snapshot.buffer_snapshot);
13270        let start = snapshot
13271            .buffer_snapshot
13272            .clip_point(Point::new(position.row, 0), Bias::Left);
13273        let end = start + Point::new(1, 0);
13274        let start = snapshot.buffer_snapshot.anchor_before(start);
13275        let end = snapshot.buffer_snapshot.anchor_before(end);
13276
13277        self.highlight_rows::<T>(
13278            start..end,
13279            highlight_color
13280                .unwrap_or_else(|| cx.theme().colors().editor_highlighted_line_background),
13281            false,
13282            cx,
13283        );
13284        self.request_autoscroll(Autoscroll::center().for_anchor(start), cx);
13285    }
13286
13287    pub fn go_to_definition(
13288        &mut self,
13289        _: &GoToDefinition,
13290        window: &mut Window,
13291        cx: &mut Context<Self>,
13292    ) -> Task<Result<Navigated>> {
13293        let definition =
13294            self.go_to_definition_of_kind(GotoDefinitionKind::Symbol, false, window, cx);
13295        let fallback_strategy = EditorSettings::get_global(cx).go_to_definition_fallback;
13296        cx.spawn_in(window, async move |editor, cx| {
13297            if definition.await? == Navigated::Yes {
13298                return Ok(Navigated::Yes);
13299            }
13300            match fallback_strategy {
13301                GoToDefinitionFallback::None => Ok(Navigated::No),
13302                GoToDefinitionFallback::FindAllReferences => {
13303                    match editor.update_in(cx, |editor, window, cx| {
13304                        editor.find_all_references(&FindAllReferences, window, cx)
13305                    })? {
13306                        Some(references) => references.await,
13307                        None => Ok(Navigated::No),
13308                    }
13309                }
13310            }
13311        })
13312    }
13313
13314    pub fn go_to_declaration(
13315        &mut self,
13316        _: &GoToDeclaration,
13317        window: &mut Window,
13318        cx: &mut Context<Self>,
13319    ) -> Task<Result<Navigated>> {
13320        self.go_to_definition_of_kind(GotoDefinitionKind::Declaration, false, window, cx)
13321    }
13322
13323    pub fn go_to_declaration_split(
13324        &mut self,
13325        _: &GoToDeclaration,
13326        window: &mut Window,
13327        cx: &mut Context<Self>,
13328    ) -> Task<Result<Navigated>> {
13329        self.go_to_definition_of_kind(GotoDefinitionKind::Declaration, true, window, cx)
13330    }
13331
13332    pub fn go_to_implementation(
13333        &mut self,
13334        _: &GoToImplementation,
13335        window: &mut Window,
13336        cx: &mut Context<Self>,
13337    ) -> Task<Result<Navigated>> {
13338        self.go_to_definition_of_kind(GotoDefinitionKind::Implementation, false, window, cx)
13339    }
13340
13341    pub fn go_to_implementation_split(
13342        &mut self,
13343        _: &GoToImplementationSplit,
13344        window: &mut Window,
13345        cx: &mut Context<Self>,
13346    ) -> Task<Result<Navigated>> {
13347        self.go_to_definition_of_kind(GotoDefinitionKind::Implementation, true, window, cx)
13348    }
13349
13350    pub fn go_to_type_definition(
13351        &mut self,
13352        _: &GoToTypeDefinition,
13353        window: &mut Window,
13354        cx: &mut Context<Self>,
13355    ) -> Task<Result<Navigated>> {
13356        self.go_to_definition_of_kind(GotoDefinitionKind::Type, false, window, cx)
13357    }
13358
13359    pub fn go_to_definition_split(
13360        &mut self,
13361        _: &GoToDefinitionSplit,
13362        window: &mut Window,
13363        cx: &mut Context<Self>,
13364    ) -> Task<Result<Navigated>> {
13365        self.go_to_definition_of_kind(GotoDefinitionKind::Symbol, true, window, cx)
13366    }
13367
13368    pub fn go_to_type_definition_split(
13369        &mut self,
13370        _: &GoToTypeDefinitionSplit,
13371        window: &mut Window,
13372        cx: &mut Context<Self>,
13373    ) -> Task<Result<Navigated>> {
13374        self.go_to_definition_of_kind(GotoDefinitionKind::Type, true, window, cx)
13375    }
13376
13377    fn go_to_definition_of_kind(
13378        &mut self,
13379        kind: GotoDefinitionKind,
13380        split: bool,
13381        window: &mut Window,
13382        cx: &mut Context<Self>,
13383    ) -> Task<Result<Navigated>> {
13384        let Some(provider) = self.semantics_provider.clone() else {
13385            return Task::ready(Ok(Navigated::No));
13386        };
13387        let head = self.selections.newest::<usize>(cx).head();
13388        let buffer = self.buffer.read(cx);
13389        let (buffer, head) = if let Some(text_anchor) = buffer.text_anchor_for_position(head, cx) {
13390            text_anchor
13391        } else {
13392            return Task::ready(Ok(Navigated::No));
13393        };
13394
13395        let Some(definitions) = provider.definitions(&buffer, head, kind, cx) else {
13396            return Task::ready(Ok(Navigated::No));
13397        };
13398
13399        cx.spawn_in(window, async move |editor, cx| {
13400            let definitions = definitions.await?;
13401            let navigated = editor
13402                .update_in(cx, |editor, window, cx| {
13403                    editor.navigate_to_hover_links(
13404                        Some(kind),
13405                        definitions
13406                            .into_iter()
13407                            .filter(|location| {
13408                                hover_links::exclude_link_to_position(&buffer, &head, location, cx)
13409                            })
13410                            .map(HoverLink::Text)
13411                            .collect::<Vec<_>>(),
13412                        split,
13413                        window,
13414                        cx,
13415                    )
13416                })?
13417                .await?;
13418            anyhow::Ok(navigated)
13419        })
13420    }
13421
13422    pub fn open_url(&mut self, _: &OpenUrl, window: &mut Window, cx: &mut Context<Self>) {
13423        let selection = self.selections.newest_anchor();
13424        let head = selection.head();
13425        let tail = selection.tail();
13426
13427        let Some((buffer, start_position)) =
13428            self.buffer.read(cx).text_anchor_for_position(head, cx)
13429        else {
13430            return;
13431        };
13432
13433        let end_position = if head != tail {
13434            let Some((_, pos)) = self.buffer.read(cx).text_anchor_for_position(tail, cx) else {
13435                return;
13436            };
13437            Some(pos)
13438        } else {
13439            None
13440        };
13441
13442        let url_finder = cx.spawn_in(window, async move |editor, cx| {
13443            let url = if let Some(end_pos) = end_position {
13444                find_url_from_range(&buffer, start_position..end_pos, cx.clone())
13445            } else {
13446                find_url(&buffer, start_position, cx.clone()).map(|(_, url)| url)
13447            };
13448
13449            if let Some(url) = url {
13450                editor.update(cx, |_, cx| {
13451                    cx.open_url(&url);
13452                })
13453            } else {
13454                Ok(())
13455            }
13456        });
13457
13458        url_finder.detach();
13459    }
13460
13461    pub fn open_selected_filename(
13462        &mut self,
13463        _: &OpenSelectedFilename,
13464        window: &mut Window,
13465        cx: &mut Context<Self>,
13466    ) {
13467        let Some(workspace) = self.workspace() else {
13468            return;
13469        };
13470
13471        let position = self.selections.newest_anchor().head();
13472
13473        let Some((buffer, buffer_position)) =
13474            self.buffer.read(cx).text_anchor_for_position(position, cx)
13475        else {
13476            return;
13477        };
13478
13479        let project = self.project.clone();
13480
13481        cx.spawn_in(window, async move |_, cx| {
13482            let result = find_file(&buffer, project, buffer_position, cx).await;
13483
13484            if let Some((_, path)) = result {
13485                workspace
13486                    .update_in(cx, |workspace, window, cx| {
13487                        workspace.open_resolved_path(path, window, cx)
13488                    })?
13489                    .await?;
13490            }
13491            anyhow::Ok(())
13492        })
13493        .detach();
13494    }
13495
13496    pub(crate) fn navigate_to_hover_links(
13497        &mut self,
13498        kind: Option<GotoDefinitionKind>,
13499        mut definitions: Vec<HoverLink>,
13500        split: bool,
13501        window: &mut Window,
13502        cx: &mut Context<Editor>,
13503    ) -> Task<Result<Navigated>> {
13504        // If there is one definition, just open it directly
13505        if definitions.len() == 1 {
13506            let definition = definitions.pop().unwrap();
13507
13508            enum TargetTaskResult {
13509                Location(Option<Location>),
13510                AlreadyNavigated,
13511            }
13512
13513            let target_task = match definition {
13514                HoverLink::Text(link) => {
13515                    Task::ready(anyhow::Ok(TargetTaskResult::Location(Some(link.target))))
13516                }
13517                HoverLink::InlayHint(lsp_location, server_id) => {
13518                    let computation =
13519                        self.compute_target_location(lsp_location, server_id, window, cx);
13520                    cx.background_spawn(async move {
13521                        let location = computation.await?;
13522                        Ok(TargetTaskResult::Location(location))
13523                    })
13524                }
13525                HoverLink::Url(url) => {
13526                    cx.open_url(&url);
13527                    Task::ready(Ok(TargetTaskResult::AlreadyNavigated))
13528                }
13529                HoverLink::File(path) => {
13530                    if let Some(workspace) = self.workspace() {
13531                        cx.spawn_in(window, async move |_, cx| {
13532                            workspace
13533                                .update_in(cx, |workspace, window, cx| {
13534                                    workspace.open_resolved_path(path, window, cx)
13535                                })?
13536                                .await
13537                                .map(|_| TargetTaskResult::AlreadyNavigated)
13538                        })
13539                    } else {
13540                        Task::ready(Ok(TargetTaskResult::Location(None)))
13541                    }
13542                }
13543            };
13544            cx.spawn_in(window, async move |editor, cx| {
13545                let target = match target_task.await.context("target resolution task")? {
13546                    TargetTaskResult::AlreadyNavigated => return Ok(Navigated::Yes),
13547                    TargetTaskResult::Location(None) => return Ok(Navigated::No),
13548                    TargetTaskResult::Location(Some(target)) => target,
13549                };
13550
13551                editor.update_in(cx, |editor, window, cx| {
13552                    let Some(workspace) = editor.workspace() else {
13553                        return Navigated::No;
13554                    };
13555                    let pane = workspace.read(cx).active_pane().clone();
13556
13557                    let range = target.range.to_point(target.buffer.read(cx));
13558                    let range = editor.range_for_match(&range);
13559                    let range = collapse_multiline_range(range);
13560
13561                    if !split
13562                        && Some(&target.buffer) == editor.buffer.read(cx).as_singleton().as_ref()
13563                    {
13564                        editor.go_to_singleton_buffer_range(range.clone(), window, cx);
13565                    } else {
13566                        window.defer(cx, move |window, cx| {
13567                            let target_editor: Entity<Self> =
13568                                workspace.update(cx, |workspace, cx| {
13569                                    let pane = if split {
13570                                        workspace.adjacent_pane(window, cx)
13571                                    } else {
13572                                        workspace.active_pane().clone()
13573                                    };
13574
13575                                    workspace.open_project_item(
13576                                        pane,
13577                                        target.buffer.clone(),
13578                                        true,
13579                                        true,
13580                                        window,
13581                                        cx,
13582                                    )
13583                                });
13584                            target_editor.update(cx, |target_editor, cx| {
13585                                // When selecting a definition in a different buffer, disable the nav history
13586                                // to avoid creating a history entry at the previous cursor location.
13587                                pane.update(cx, |pane, _| pane.disable_history());
13588                                target_editor.go_to_singleton_buffer_range(range, window, cx);
13589                                pane.update(cx, |pane, _| pane.enable_history());
13590                            });
13591                        });
13592                    }
13593                    Navigated::Yes
13594                })
13595            })
13596        } else if !definitions.is_empty() {
13597            cx.spawn_in(window, async move |editor, cx| {
13598                let (title, location_tasks, workspace) = editor
13599                    .update_in(cx, |editor, window, cx| {
13600                        let tab_kind = match kind {
13601                            Some(GotoDefinitionKind::Implementation) => "Implementations",
13602                            _ => "Definitions",
13603                        };
13604                        let title = definitions
13605                            .iter()
13606                            .find_map(|definition| match definition {
13607                                HoverLink::Text(link) => link.origin.as_ref().map(|origin| {
13608                                    let buffer = origin.buffer.read(cx);
13609                                    format!(
13610                                        "{} for {}",
13611                                        tab_kind,
13612                                        buffer
13613                                            .text_for_range(origin.range.clone())
13614                                            .collect::<String>()
13615                                    )
13616                                }),
13617                                HoverLink::InlayHint(_, _) => None,
13618                                HoverLink::Url(_) => None,
13619                                HoverLink::File(_) => None,
13620                            })
13621                            .unwrap_or(tab_kind.to_string());
13622                        let location_tasks = definitions
13623                            .into_iter()
13624                            .map(|definition| match definition {
13625                                HoverLink::Text(link) => Task::ready(Ok(Some(link.target))),
13626                                HoverLink::InlayHint(lsp_location, server_id) => editor
13627                                    .compute_target_location(lsp_location, server_id, window, cx),
13628                                HoverLink::Url(_) => Task::ready(Ok(None)),
13629                                HoverLink::File(_) => Task::ready(Ok(None)),
13630                            })
13631                            .collect::<Vec<_>>();
13632                        (title, location_tasks, editor.workspace().clone())
13633                    })
13634                    .context("location tasks preparation")?;
13635
13636                let locations = future::join_all(location_tasks)
13637                    .await
13638                    .into_iter()
13639                    .filter_map(|location| location.transpose())
13640                    .collect::<Result<_>>()
13641                    .context("location tasks")?;
13642
13643                let Some(workspace) = workspace else {
13644                    return Ok(Navigated::No);
13645                };
13646                let opened = workspace
13647                    .update_in(cx, |workspace, window, cx| {
13648                        Self::open_locations_in_multibuffer(
13649                            workspace,
13650                            locations,
13651                            title,
13652                            split,
13653                            MultibufferSelectionMode::First,
13654                            window,
13655                            cx,
13656                        )
13657                    })
13658                    .ok();
13659
13660                anyhow::Ok(Navigated::from_bool(opened.is_some()))
13661            })
13662        } else {
13663            Task::ready(Ok(Navigated::No))
13664        }
13665    }
13666
13667    fn compute_target_location(
13668        &self,
13669        lsp_location: lsp::Location,
13670        server_id: LanguageServerId,
13671        window: &mut Window,
13672        cx: &mut Context<Self>,
13673    ) -> Task<anyhow::Result<Option<Location>>> {
13674        let Some(project) = self.project.clone() else {
13675            return Task::ready(Ok(None));
13676        };
13677
13678        cx.spawn_in(window, async move |editor, cx| {
13679            let location_task = editor.update(cx, |_, cx| {
13680                project.update(cx, |project, cx| {
13681                    let language_server_name = project
13682                        .language_server_statuses(cx)
13683                        .find(|(id, _)| server_id == *id)
13684                        .map(|(_, status)| LanguageServerName::from(status.name.as_str()));
13685                    language_server_name.map(|language_server_name| {
13686                        project.open_local_buffer_via_lsp(
13687                            lsp_location.uri.clone(),
13688                            server_id,
13689                            language_server_name,
13690                            cx,
13691                        )
13692                    })
13693                })
13694            })?;
13695            let location = match location_task {
13696                Some(task) => Some({
13697                    let target_buffer_handle = task.await.context("open local buffer")?;
13698                    let range = target_buffer_handle.update(cx, |target_buffer, _| {
13699                        let target_start = target_buffer
13700                            .clip_point_utf16(point_from_lsp(lsp_location.range.start), Bias::Left);
13701                        let target_end = target_buffer
13702                            .clip_point_utf16(point_from_lsp(lsp_location.range.end), Bias::Left);
13703                        target_buffer.anchor_after(target_start)
13704                            ..target_buffer.anchor_before(target_end)
13705                    })?;
13706                    Location {
13707                        buffer: target_buffer_handle,
13708                        range,
13709                    }
13710                }),
13711                None => None,
13712            };
13713            Ok(location)
13714        })
13715    }
13716
13717    pub fn find_all_references(
13718        &mut self,
13719        _: &FindAllReferences,
13720        window: &mut Window,
13721        cx: &mut Context<Self>,
13722    ) -> Option<Task<Result<Navigated>>> {
13723        let selection = self.selections.newest::<usize>(cx);
13724        let multi_buffer = self.buffer.read(cx);
13725        let head = selection.head();
13726
13727        let multi_buffer_snapshot = multi_buffer.snapshot(cx);
13728        let head_anchor = multi_buffer_snapshot.anchor_at(
13729            head,
13730            if head < selection.tail() {
13731                Bias::Right
13732            } else {
13733                Bias::Left
13734            },
13735        );
13736
13737        match self
13738            .find_all_references_task_sources
13739            .binary_search_by(|anchor| anchor.cmp(&head_anchor, &multi_buffer_snapshot))
13740        {
13741            Ok(_) => {
13742                log::info!(
13743                    "Ignoring repeated FindAllReferences invocation with the position of already running task"
13744                );
13745                return None;
13746            }
13747            Err(i) => {
13748                self.find_all_references_task_sources.insert(i, head_anchor);
13749            }
13750        }
13751
13752        let (buffer, head) = multi_buffer.text_anchor_for_position(head, cx)?;
13753        let workspace = self.workspace()?;
13754        let project = workspace.read(cx).project().clone();
13755        let references = project.update(cx, |project, cx| project.references(&buffer, head, cx));
13756        Some(cx.spawn_in(window, async move |editor, cx| {
13757            let _cleanup = cx.on_drop(&editor, move |editor, _| {
13758                if let Ok(i) = editor
13759                    .find_all_references_task_sources
13760                    .binary_search_by(|anchor| anchor.cmp(&head_anchor, &multi_buffer_snapshot))
13761                {
13762                    editor.find_all_references_task_sources.remove(i);
13763                }
13764            });
13765
13766            let locations = references.await?;
13767            if locations.is_empty() {
13768                return anyhow::Ok(Navigated::No);
13769            }
13770
13771            workspace.update_in(cx, |workspace, window, cx| {
13772                let title = locations
13773                    .first()
13774                    .as_ref()
13775                    .map(|location| {
13776                        let buffer = location.buffer.read(cx);
13777                        format!(
13778                            "References to `{}`",
13779                            buffer
13780                                .text_for_range(location.range.clone())
13781                                .collect::<String>()
13782                        )
13783                    })
13784                    .unwrap();
13785                Self::open_locations_in_multibuffer(
13786                    workspace,
13787                    locations,
13788                    title,
13789                    false,
13790                    MultibufferSelectionMode::First,
13791                    window,
13792                    cx,
13793                );
13794                Navigated::Yes
13795            })
13796        }))
13797    }
13798
13799    /// Opens a multibuffer with the given project locations in it
13800    pub fn open_locations_in_multibuffer(
13801        workspace: &mut Workspace,
13802        mut locations: Vec<Location>,
13803        title: String,
13804        split: bool,
13805        multibuffer_selection_mode: MultibufferSelectionMode,
13806        window: &mut Window,
13807        cx: &mut Context<Workspace>,
13808    ) {
13809        // If there are multiple definitions, open them in a multibuffer
13810        locations.sort_by_key(|location| location.buffer.read(cx).remote_id());
13811        let mut locations = locations.into_iter().peekable();
13812        let mut ranges: Vec<Range<Anchor>> = Vec::new();
13813        let capability = workspace.project().read(cx).capability();
13814
13815        let excerpt_buffer = cx.new(|cx| {
13816            let mut multibuffer = MultiBuffer::new(capability);
13817            while let Some(location) = locations.next() {
13818                let buffer = location.buffer.read(cx);
13819                let mut ranges_for_buffer = Vec::new();
13820                let range = location.range.to_point(buffer);
13821                ranges_for_buffer.push(range.clone());
13822
13823                while let Some(next_location) = locations.peek() {
13824                    if next_location.buffer == location.buffer {
13825                        ranges_for_buffer.push(next_location.range.to_point(buffer));
13826                        locations.next();
13827                    } else {
13828                        break;
13829                    }
13830                }
13831
13832                ranges_for_buffer.sort_by_key(|range| (range.start, Reverse(range.end)));
13833                let (new_ranges, _) = multibuffer.set_excerpts_for_path(
13834                    PathKey::for_buffer(&location.buffer, cx),
13835                    location.buffer.clone(),
13836                    ranges_for_buffer,
13837                    DEFAULT_MULTIBUFFER_CONTEXT,
13838                    cx,
13839                );
13840                ranges.extend(new_ranges)
13841            }
13842
13843            multibuffer.with_title(title)
13844        });
13845
13846        let editor = cx.new(|cx| {
13847            Editor::for_multibuffer(
13848                excerpt_buffer,
13849                Some(workspace.project().clone()),
13850                window,
13851                cx,
13852            )
13853        });
13854        editor.update(cx, |editor, cx| {
13855            match multibuffer_selection_mode {
13856                MultibufferSelectionMode::First => {
13857                    if let Some(first_range) = ranges.first() {
13858                        editor.change_selections(None, window, cx, |selections| {
13859                            selections.clear_disjoint();
13860                            selections.select_anchor_ranges(std::iter::once(first_range.clone()));
13861                        });
13862                    }
13863                    editor.highlight_background::<Self>(
13864                        &ranges,
13865                        |theme| theme.editor_highlighted_line_background,
13866                        cx,
13867                    );
13868                }
13869                MultibufferSelectionMode::All => {
13870                    editor.change_selections(None, window, cx, |selections| {
13871                        selections.clear_disjoint();
13872                        selections.select_anchor_ranges(ranges);
13873                    });
13874                }
13875            }
13876            editor.register_buffers_with_language_servers(cx);
13877        });
13878
13879        let item = Box::new(editor);
13880        let item_id = item.item_id();
13881
13882        if split {
13883            workspace.split_item(SplitDirection::Right, item.clone(), window, cx);
13884        } else {
13885            if PreviewTabsSettings::get_global(cx).enable_preview_from_code_navigation {
13886                let (preview_item_id, preview_item_idx) =
13887                    workspace.active_pane().update(cx, |pane, _| {
13888                        (pane.preview_item_id(), pane.preview_item_idx())
13889                    });
13890
13891                workspace.add_item_to_active_pane(item.clone(), preview_item_idx, true, window, cx);
13892
13893                if let Some(preview_item_id) = preview_item_id {
13894                    workspace.active_pane().update(cx, |pane, cx| {
13895                        pane.remove_item(preview_item_id, false, false, window, cx);
13896                    });
13897                }
13898            } else {
13899                workspace.add_item_to_active_pane(item.clone(), None, true, window, cx);
13900            }
13901        }
13902        workspace.active_pane().update(cx, |pane, cx| {
13903            pane.set_preview_item_id(Some(item_id), cx);
13904        });
13905    }
13906
13907    pub fn rename(
13908        &mut self,
13909        _: &Rename,
13910        window: &mut Window,
13911        cx: &mut Context<Self>,
13912    ) -> Option<Task<Result<()>>> {
13913        use language::ToOffset as _;
13914
13915        let provider = self.semantics_provider.clone()?;
13916        let selection = self.selections.newest_anchor().clone();
13917        let (cursor_buffer, cursor_buffer_position) = self
13918            .buffer
13919            .read(cx)
13920            .text_anchor_for_position(selection.head(), cx)?;
13921        let (tail_buffer, cursor_buffer_position_end) = self
13922            .buffer
13923            .read(cx)
13924            .text_anchor_for_position(selection.tail(), cx)?;
13925        if tail_buffer != cursor_buffer {
13926            return None;
13927        }
13928
13929        let snapshot = cursor_buffer.read(cx).snapshot();
13930        let cursor_buffer_offset = cursor_buffer_position.to_offset(&snapshot);
13931        let cursor_buffer_offset_end = cursor_buffer_position_end.to_offset(&snapshot);
13932        let prepare_rename = provider
13933            .range_for_rename(&cursor_buffer, cursor_buffer_position, cx)
13934            .unwrap_or_else(|| Task::ready(Ok(None)));
13935        drop(snapshot);
13936
13937        Some(cx.spawn_in(window, async move |this, cx| {
13938            let rename_range = if let Some(range) = prepare_rename.await? {
13939                Some(range)
13940            } else {
13941                this.update(cx, |this, cx| {
13942                    let buffer = this.buffer.read(cx).snapshot(cx);
13943                    let mut buffer_highlights = this
13944                        .document_highlights_for_position(selection.head(), &buffer)
13945                        .filter(|highlight| {
13946                            highlight.start.excerpt_id == selection.head().excerpt_id
13947                                && highlight.end.excerpt_id == selection.head().excerpt_id
13948                        });
13949                    buffer_highlights
13950                        .next()
13951                        .map(|highlight| highlight.start.text_anchor..highlight.end.text_anchor)
13952                })?
13953            };
13954            if let Some(rename_range) = rename_range {
13955                this.update_in(cx, |this, window, cx| {
13956                    let snapshot = cursor_buffer.read(cx).snapshot();
13957                    let rename_buffer_range = rename_range.to_offset(&snapshot);
13958                    let cursor_offset_in_rename_range =
13959                        cursor_buffer_offset.saturating_sub(rename_buffer_range.start);
13960                    let cursor_offset_in_rename_range_end =
13961                        cursor_buffer_offset_end.saturating_sub(rename_buffer_range.start);
13962
13963                    this.take_rename(false, window, cx);
13964                    let buffer = this.buffer.read(cx).read(cx);
13965                    let cursor_offset = selection.head().to_offset(&buffer);
13966                    let rename_start = cursor_offset.saturating_sub(cursor_offset_in_rename_range);
13967                    let rename_end = rename_start + rename_buffer_range.len();
13968                    let range = buffer.anchor_before(rename_start)..buffer.anchor_after(rename_end);
13969                    let mut old_highlight_id = None;
13970                    let old_name: Arc<str> = buffer
13971                        .chunks(rename_start..rename_end, true)
13972                        .map(|chunk| {
13973                            if old_highlight_id.is_none() {
13974                                old_highlight_id = chunk.syntax_highlight_id;
13975                            }
13976                            chunk.text
13977                        })
13978                        .collect::<String>()
13979                        .into();
13980
13981                    drop(buffer);
13982
13983                    // Position the selection in the rename editor so that it matches the current selection.
13984                    this.show_local_selections = false;
13985                    let rename_editor = cx.new(|cx| {
13986                        let mut editor = Editor::single_line(window, cx);
13987                        editor.buffer.update(cx, |buffer, cx| {
13988                            buffer.edit([(0..0, old_name.clone())], None, cx)
13989                        });
13990                        let rename_selection_range = match cursor_offset_in_rename_range
13991                            .cmp(&cursor_offset_in_rename_range_end)
13992                        {
13993                            Ordering::Equal => {
13994                                editor.select_all(&SelectAll, window, cx);
13995                                return editor;
13996                            }
13997                            Ordering::Less => {
13998                                cursor_offset_in_rename_range..cursor_offset_in_rename_range_end
13999                            }
14000                            Ordering::Greater => {
14001                                cursor_offset_in_rename_range_end..cursor_offset_in_rename_range
14002                            }
14003                        };
14004                        if rename_selection_range.end > old_name.len() {
14005                            editor.select_all(&SelectAll, window, cx);
14006                        } else {
14007                            editor.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
14008                                s.select_ranges([rename_selection_range]);
14009                            });
14010                        }
14011                        editor
14012                    });
14013                    cx.subscribe(&rename_editor, |_, _, e: &EditorEvent, cx| {
14014                        if e == &EditorEvent::Focused {
14015                            cx.emit(EditorEvent::FocusedIn)
14016                        }
14017                    })
14018                    .detach();
14019
14020                    let write_highlights =
14021                        this.clear_background_highlights::<DocumentHighlightWrite>(cx);
14022                    let read_highlights =
14023                        this.clear_background_highlights::<DocumentHighlightRead>(cx);
14024                    let ranges = write_highlights
14025                        .iter()
14026                        .flat_map(|(_, ranges)| ranges.iter())
14027                        .chain(read_highlights.iter().flat_map(|(_, ranges)| ranges.iter()))
14028                        .cloned()
14029                        .collect();
14030
14031                    this.highlight_text::<Rename>(
14032                        ranges,
14033                        HighlightStyle {
14034                            fade_out: Some(0.6),
14035                            ..Default::default()
14036                        },
14037                        cx,
14038                    );
14039                    let rename_focus_handle = rename_editor.focus_handle(cx);
14040                    window.focus(&rename_focus_handle);
14041                    let block_id = this.insert_blocks(
14042                        [BlockProperties {
14043                            style: BlockStyle::Flex,
14044                            placement: BlockPlacement::Below(range.start),
14045                            height: Some(1),
14046                            render: Arc::new({
14047                                let rename_editor = rename_editor.clone();
14048                                move |cx: &mut BlockContext| {
14049                                    let mut text_style = cx.editor_style.text.clone();
14050                                    if let Some(highlight_style) = old_highlight_id
14051                                        .and_then(|h| h.style(&cx.editor_style.syntax))
14052                                    {
14053                                        text_style = text_style.highlight(highlight_style);
14054                                    }
14055                                    div()
14056                                        .block_mouse_down()
14057                                        .pl(cx.anchor_x)
14058                                        .child(EditorElement::new(
14059                                            &rename_editor,
14060                                            EditorStyle {
14061                                                background: cx.theme().system().transparent,
14062                                                local_player: cx.editor_style.local_player,
14063                                                text: text_style,
14064                                                scrollbar_width: cx.editor_style.scrollbar_width,
14065                                                syntax: cx.editor_style.syntax.clone(),
14066                                                status: cx.editor_style.status.clone(),
14067                                                inlay_hints_style: HighlightStyle {
14068                                                    font_weight: Some(FontWeight::BOLD),
14069                                                    ..make_inlay_hints_style(cx.app)
14070                                                },
14071                                                inline_completion_styles: make_suggestion_styles(
14072                                                    cx.app,
14073                                                ),
14074                                                ..EditorStyle::default()
14075                                            },
14076                                        ))
14077                                        .into_any_element()
14078                                }
14079                            }),
14080                            priority: 0,
14081                        }],
14082                        Some(Autoscroll::fit()),
14083                        cx,
14084                    )[0];
14085                    this.pending_rename = Some(RenameState {
14086                        range,
14087                        old_name,
14088                        editor: rename_editor,
14089                        block_id,
14090                    });
14091                })?;
14092            }
14093
14094            Ok(())
14095        }))
14096    }
14097
14098    pub fn confirm_rename(
14099        &mut self,
14100        _: &ConfirmRename,
14101        window: &mut Window,
14102        cx: &mut Context<Self>,
14103    ) -> Option<Task<Result<()>>> {
14104        let rename = self.take_rename(false, window, cx)?;
14105        let workspace = self.workspace()?.downgrade();
14106        let (buffer, start) = self
14107            .buffer
14108            .read(cx)
14109            .text_anchor_for_position(rename.range.start, cx)?;
14110        let (end_buffer, _) = self
14111            .buffer
14112            .read(cx)
14113            .text_anchor_for_position(rename.range.end, cx)?;
14114        if buffer != end_buffer {
14115            return None;
14116        }
14117
14118        let old_name = rename.old_name;
14119        let new_name = rename.editor.read(cx).text(cx);
14120
14121        let rename = self.semantics_provider.as_ref()?.perform_rename(
14122            &buffer,
14123            start,
14124            new_name.clone(),
14125            cx,
14126        )?;
14127
14128        Some(cx.spawn_in(window, async move |editor, cx| {
14129            let project_transaction = rename.await?;
14130            Self::open_project_transaction(
14131                &editor,
14132                workspace,
14133                project_transaction,
14134                format!("Rename: {}{}", old_name, new_name),
14135                cx,
14136            )
14137            .await?;
14138
14139            editor.update(cx, |editor, cx| {
14140                editor.refresh_document_highlights(cx);
14141            })?;
14142            Ok(())
14143        }))
14144    }
14145
14146    fn take_rename(
14147        &mut self,
14148        moving_cursor: bool,
14149        window: &mut Window,
14150        cx: &mut Context<Self>,
14151    ) -> Option<RenameState> {
14152        let rename = self.pending_rename.take()?;
14153        if rename.editor.focus_handle(cx).is_focused(window) {
14154            window.focus(&self.focus_handle);
14155        }
14156
14157        self.remove_blocks(
14158            [rename.block_id].into_iter().collect(),
14159            Some(Autoscroll::fit()),
14160            cx,
14161        );
14162        self.clear_highlights::<Rename>(cx);
14163        self.show_local_selections = true;
14164
14165        if moving_cursor {
14166            let cursor_in_rename_editor = rename.editor.update(cx, |editor, cx| {
14167                editor.selections.newest::<usize>(cx).head()
14168            });
14169
14170            // Update the selection to match the position of the selection inside
14171            // the rename editor.
14172            let snapshot = self.buffer.read(cx).read(cx);
14173            let rename_range = rename.range.to_offset(&snapshot);
14174            let cursor_in_editor = snapshot
14175                .clip_offset(rename_range.start + cursor_in_rename_editor, Bias::Left)
14176                .min(rename_range.end);
14177            drop(snapshot);
14178
14179            self.change_selections(None, window, cx, |s| {
14180                s.select_ranges(vec![cursor_in_editor..cursor_in_editor])
14181            });
14182        } else {
14183            self.refresh_document_highlights(cx);
14184        }
14185
14186        Some(rename)
14187    }
14188
14189    pub fn pending_rename(&self) -> Option<&RenameState> {
14190        self.pending_rename.as_ref()
14191    }
14192
14193    fn format(
14194        &mut self,
14195        _: &Format,
14196        window: &mut Window,
14197        cx: &mut Context<Self>,
14198    ) -> Option<Task<Result<()>>> {
14199        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
14200
14201        let project = match &self.project {
14202            Some(project) => project.clone(),
14203            None => return None,
14204        };
14205
14206        Some(self.perform_format(
14207            project,
14208            FormatTrigger::Manual,
14209            FormatTarget::Buffers,
14210            window,
14211            cx,
14212        ))
14213    }
14214
14215    fn format_selections(
14216        &mut self,
14217        _: &FormatSelections,
14218        window: &mut Window,
14219        cx: &mut Context<Self>,
14220    ) -> Option<Task<Result<()>>> {
14221        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
14222
14223        let project = match &self.project {
14224            Some(project) => project.clone(),
14225            None => return None,
14226        };
14227
14228        let ranges = self
14229            .selections
14230            .all_adjusted(cx)
14231            .into_iter()
14232            .map(|selection| selection.range())
14233            .collect_vec();
14234
14235        Some(self.perform_format(
14236            project,
14237            FormatTrigger::Manual,
14238            FormatTarget::Ranges(ranges),
14239            window,
14240            cx,
14241        ))
14242    }
14243
14244    fn perform_format(
14245        &mut self,
14246        project: Entity<Project>,
14247        trigger: FormatTrigger,
14248        target: FormatTarget,
14249        window: &mut Window,
14250        cx: &mut Context<Self>,
14251    ) -> Task<Result<()>> {
14252        let buffer = self.buffer.clone();
14253        let (buffers, target) = match target {
14254            FormatTarget::Buffers => {
14255                let mut buffers = buffer.read(cx).all_buffers();
14256                if trigger == FormatTrigger::Save {
14257                    buffers.retain(|buffer| buffer.read(cx).is_dirty());
14258                }
14259                (buffers, LspFormatTarget::Buffers)
14260            }
14261            FormatTarget::Ranges(selection_ranges) => {
14262                let multi_buffer = buffer.read(cx);
14263                let snapshot = multi_buffer.read(cx);
14264                let mut buffers = HashSet::default();
14265                let mut buffer_id_to_ranges: BTreeMap<BufferId, Vec<Range<text::Anchor>>> =
14266                    BTreeMap::new();
14267                for selection_range in selection_ranges {
14268                    for (buffer, buffer_range, _) in
14269                        snapshot.range_to_buffer_ranges(selection_range)
14270                    {
14271                        let buffer_id = buffer.remote_id();
14272                        let start = buffer.anchor_before(buffer_range.start);
14273                        let end = buffer.anchor_after(buffer_range.end);
14274                        buffers.insert(multi_buffer.buffer(buffer_id).unwrap());
14275                        buffer_id_to_ranges
14276                            .entry(buffer_id)
14277                            .and_modify(|buffer_ranges| buffer_ranges.push(start..end))
14278                            .or_insert_with(|| vec![start..end]);
14279                    }
14280                }
14281                (buffers, LspFormatTarget::Ranges(buffer_id_to_ranges))
14282            }
14283        };
14284
14285        let transaction_id_prev = buffer.read_with(cx, |b, cx| b.last_transaction_id(cx));
14286        let selections_prev = transaction_id_prev
14287            .and_then(|transaction_id_prev| {
14288                // default to selections as they were after the last edit, if we have them,
14289                // instead of how they are now.
14290                // This will make it so that editing, moving somewhere else, formatting, then undoing the format
14291                // will take you back to where you made the last edit, instead of staying where you scrolled
14292                self.selection_history
14293                    .transaction(transaction_id_prev)
14294                    .map(|t| t.0.clone())
14295            })
14296            .unwrap_or_else(|| {
14297                log::info!("Failed to determine selections from before format. Falling back to selections when format was initiated");
14298                self.selections.disjoint_anchors()
14299            });
14300
14301        let mut timeout = cx.background_executor().timer(FORMAT_TIMEOUT).fuse();
14302        let format = project.update(cx, |project, cx| {
14303            project.format(buffers, target, true, trigger, cx)
14304        });
14305
14306        cx.spawn_in(window, async move |editor, cx| {
14307            let transaction = futures::select_biased! {
14308                transaction = format.log_err().fuse() => transaction,
14309                () = timeout => {
14310                    log::warn!("timed out waiting for formatting");
14311                    None
14312                }
14313            };
14314
14315            buffer
14316                .update(cx, |buffer, cx| {
14317                    if let Some(transaction) = transaction {
14318                        if !buffer.is_singleton() {
14319                            buffer.push_transaction(&transaction.0, cx);
14320                        }
14321                    }
14322                    cx.notify();
14323                })
14324                .ok();
14325
14326            if let Some(transaction_id_now) =
14327                buffer.read_with(cx, |b, cx| b.last_transaction_id(cx))?
14328            {
14329                let has_new_transaction = transaction_id_prev != Some(transaction_id_now);
14330                if has_new_transaction {
14331                    _ = editor.update(cx, |editor, _| {
14332                        editor
14333                            .selection_history
14334                            .insert_transaction(transaction_id_now, selections_prev);
14335                    });
14336                }
14337            }
14338
14339            Ok(())
14340        })
14341    }
14342
14343    fn organize_imports(
14344        &mut self,
14345        _: &OrganizeImports,
14346        window: &mut Window,
14347        cx: &mut Context<Self>,
14348    ) -> Option<Task<Result<()>>> {
14349        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
14350        let project = match &self.project {
14351            Some(project) => project.clone(),
14352            None => return None,
14353        };
14354        Some(self.perform_code_action_kind(
14355            project,
14356            CodeActionKind::SOURCE_ORGANIZE_IMPORTS,
14357            window,
14358            cx,
14359        ))
14360    }
14361
14362    fn perform_code_action_kind(
14363        &mut self,
14364        project: Entity<Project>,
14365        kind: CodeActionKind,
14366        window: &mut Window,
14367        cx: &mut Context<Self>,
14368    ) -> Task<Result<()>> {
14369        let buffer = self.buffer.clone();
14370        let buffers = buffer.read(cx).all_buffers();
14371        let mut timeout = cx.background_executor().timer(CODE_ACTION_TIMEOUT).fuse();
14372        let apply_action = project.update(cx, |project, cx| {
14373            project.apply_code_action_kind(buffers, kind, true, cx)
14374        });
14375        cx.spawn_in(window, async move |_, cx| {
14376            let transaction = futures::select_biased! {
14377                () = timeout => {
14378                    log::warn!("timed out waiting for executing code action");
14379                    None
14380                }
14381                transaction = apply_action.log_err().fuse() => transaction,
14382            };
14383            buffer
14384                .update(cx, |buffer, cx| {
14385                    // check if we need this
14386                    if let Some(transaction) = transaction {
14387                        if !buffer.is_singleton() {
14388                            buffer.push_transaction(&transaction.0, cx);
14389                        }
14390                    }
14391                    cx.notify();
14392                })
14393                .ok();
14394            Ok(())
14395        })
14396    }
14397
14398    fn restart_language_server(
14399        &mut self,
14400        _: &RestartLanguageServer,
14401        _: &mut Window,
14402        cx: &mut Context<Self>,
14403    ) {
14404        if let Some(project) = self.project.clone() {
14405            self.buffer.update(cx, |multi_buffer, cx| {
14406                project.update(cx, |project, cx| {
14407                    project.restart_language_servers_for_buffers(
14408                        multi_buffer.all_buffers().into_iter().collect(),
14409                        cx,
14410                    );
14411                });
14412            })
14413        }
14414    }
14415
14416    fn stop_language_server(
14417        &mut self,
14418        _: &StopLanguageServer,
14419        _: &mut Window,
14420        cx: &mut Context<Self>,
14421    ) {
14422        if let Some(project) = self.project.clone() {
14423            self.buffer.update(cx, |multi_buffer, cx| {
14424                project.update(cx, |project, cx| {
14425                    project.stop_language_servers_for_buffers(
14426                        multi_buffer.all_buffers().into_iter().collect(),
14427                        cx,
14428                    );
14429                    cx.emit(project::Event::RefreshInlayHints);
14430                });
14431            });
14432        }
14433    }
14434
14435    fn cancel_language_server_work(
14436        workspace: &mut Workspace,
14437        _: &actions::CancelLanguageServerWork,
14438        _: &mut Window,
14439        cx: &mut Context<Workspace>,
14440    ) {
14441        let project = workspace.project();
14442        let buffers = workspace
14443            .active_item(cx)
14444            .and_then(|item| item.act_as::<Editor>(cx))
14445            .map_or(HashSet::default(), |editor| {
14446                editor.read(cx).buffer.read(cx).all_buffers()
14447            });
14448        project.update(cx, |project, cx| {
14449            project.cancel_language_server_work_for_buffers(buffers, cx);
14450        });
14451    }
14452
14453    fn show_character_palette(
14454        &mut self,
14455        _: &ShowCharacterPalette,
14456        window: &mut Window,
14457        _: &mut Context<Self>,
14458    ) {
14459        window.show_character_palette();
14460    }
14461
14462    fn refresh_active_diagnostics(&mut self, cx: &mut Context<Editor>) {
14463        if let ActiveDiagnostic::Group(active_diagnostics) = &mut self.active_diagnostics {
14464            let buffer = self.buffer.read(cx).snapshot(cx);
14465            let primary_range_start = active_diagnostics.active_range.start.to_offset(&buffer);
14466            let primary_range_end = active_diagnostics.active_range.end.to_offset(&buffer);
14467            let is_valid = buffer
14468                .diagnostics_in_range::<usize>(primary_range_start..primary_range_end)
14469                .any(|entry| {
14470                    entry.diagnostic.is_primary
14471                        && !entry.range.is_empty()
14472                        && entry.range.start == primary_range_start
14473                        && entry.diagnostic.message == active_diagnostics.active_message
14474                });
14475
14476            if !is_valid {
14477                self.dismiss_diagnostics(cx);
14478            }
14479        }
14480    }
14481
14482    pub fn active_diagnostic_group(&self) -> Option<&ActiveDiagnosticGroup> {
14483        match &self.active_diagnostics {
14484            ActiveDiagnostic::Group(group) => Some(group),
14485            _ => None,
14486        }
14487    }
14488
14489    pub fn set_all_diagnostics_active(&mut self, cx: &mut Context<Self>) {
14490        self.dismiss_diagnostics(cx);
14491        self.active_diagnostics = ActiveDiagnostic::All;
14492    }
14493
14494    fn activate_diagnostics(
14495        &mut self,
14496        buffer_id: BufferId,
14497        diagnostic: DiagnosticEntry<usize>,
14498        window: &mut Window,
14499        cx: &mut Context<Self>,
14500    ) {
14501        if matches!(self.active_diagnostics, ActiveDiagnostic::All) {
14502            return;
14503        }
14504        self.dismiss_diagnostics(cx);
14505        let snapshot = self.snapshot(window, cx);
14506        let Some(diagnostic_renderer) = cx
14507            .try_global::<GlobalDiagnosticRenderer>()
14508            .map(|g| g.0.clone())
14509        else {
14510            return;
14511        };
14512        let buffer = self.buffer.read(cx).snapshot(cx);
14513
14514        let diagnostic_group = buffer
14515            .diagnostic_group(buffer_id, diagnostic.diagnostic.group_id)
14516            .collect::<Vec<_>>();
14517
14518        let blocks = diagnostic_renderer.render_group(
14519            diagnostic_group,
14520            buffer_id,
14521            snapshot,
14522            cx.weak_entity(),
14523            cx,
14524        );
14525
14526        let blocks = self.display_map.update(cx, |display_map, cx| {
14527            display_map.insert_blocks(blocks, cx).into_iter().collect()
14528        });
14529        self.active_diagnostics = ActiveDiagnostic::Group(ActiveDiagnosticGroup {
14530            active_range: buffer.anchor_before(diagnostic.range.start)
14531                ..buffer.anchor_after(diagnostic.range.end),
14532            active_message: diagnostic.diagnostic.message.clone(),
14533            group_id: diagnostic.diagnostic.group_id,
14534            blocks,
14535        });
14536        cx.notify();
14537    }
14538
14539    fn dismiss_diagnostics(&mut self, cx: &mut Context<Self>) {
14540        if matches!(self.active_diagnostics, ActiveDiagnostic::All) {
14541            return;
14542        };
14543
14544        let prev = mem::replace(&mut self.active_diagnostics, ActiveDiagnostic::None);
14545        if let ActiveDiagnostic::Group(group) = prev {
14546            self.display_map.update(cx, |display_map, cx| {
14547                display_map.remove_blocks(group.blocks, cx);
14548            });
14549            cx.notify();
14550        }
14551    }
14552
14553    /// Disable inline diagnostics rendering for this editor.
14554    pub fn disable_inline_diagnostics(&mut self) {
14555        self.inline_diagnostics_enabled = false;
14556        self.inline_diagnostics_update = Task::ready(());
14557        self.inline_diagnostics.clear();
14558    }
14559
14560    pub fn inline_diagnostics_enabled(&self) -> bool {
14561        self.inline_diagnostics_enabled
14562    }
14563
14564    pub fn show_inline_diagnostics(&self) -> bool {
14565        self.show_inline_diagnostics
14566    }
14567
14568    pub fn toggle_inline_diagnostics(
14569        &mut self,
14570        _: &ToggleInlineDiagnostics,
14571        window: &mut Window,
14572        cx: &mut Context<Editor>,
14573    ) {
14574        self.show_inline_diagnostics = !self.show_inline_diagnostics;
14575        self.refresh_inline_diagnostics(false, window, cx);
14576    }
14577
14578    fn refresh_inline_diagnostics(
14579        &mut self,
14580        debounce: bool,
14581        window: &mut Window,
14582        cx: &mut Context<Self>,
14583    ) {
14584        if !self.inline_diagnostics_enabled || !self.show_inline_diagnostics {
14585            self.inline_diagnostics_update = Task::ready(());
14586            self.inline_diagnostics.clear();
14587            return;
14588        }
14589
14590        let debounce_ms = ProjectSettings::get_global(cx)
14591            .diagnostics
14592            .inline
14593            .update_debounce_ms;
14594        let debounce = if debounce && debounce_ms > 0 {
14595            Some(Duration::from_millis(debounce_ms))
14596        } else {
14597            None
14598        };
14599        self.inline_diagnostics_update = cx.spawn_in(window, async move |editor, cx| {
14600            let editor = editor.upgrade().unwrap();
14601
14602            if let Some(debounce) = debounce {
14603                cx.background_executor().timer(debounce).await;
14604            }
14605            let Some(snapshot) = editor
14606                .update(cx, |editor, cx| editor.buffer().read(cx).snapshot(cx))
14607                .ok()
14608            else {
14609                return;
14610            };
14611
14612            let new_inline_diagnostics = cx
14613                .background_spawn(async move {
14614                    let mut inline_diagnostics = Vec::<(Anchor, InlineDiagnostic)>::new();
14615                    for diagnostic_entry in snapshot.diagnostics_in_range(0..snapshot.len()) {
14616                        let message = diagnostic_entry
14617                            .diagnostic
14618                            .message
14619                            .split_once('\n')
14620                            .map(|(line, _)| line)
14621                            .map(SharedString::new)
14622                            .unwrap_or_else(|| {
14623                                SharedString::from(diagnostic_entry.diagnostic.message)
14624                            });
14625                        let start_anchor = snapshot.anchor_before(diagnostic_entry.range.start);
14626                        let (Ok(i) | Err(i)) = inline_diagnostics
14627                            .binary_search_by(|(probe, _)| probe.cmp(&start_anchor, &snapshot));
14628                        inline_diagnostics.insert(
14629                            i,
14630                            (
14631                                start_anchor,
14632                                InlineDiagnostic {
14633                                    message,
14634                                    group_id: diagnostic_entry.diagnostic.group_id,
14635                                    start: diagnostic_entry.range.start.to_point(&snapshot),
14636                                    is_primary: diagnostic_entry.diagnostic.is_primary,
14637                                    severity: diagnostic_entry.diagnostic.severity,
14638                                },
14639                            ),
14640                        );
14641                    }
14642                    inline_diagnostics
14643                })
14644                .await;
14645
14646            editor
14647                .update(cx, |editor, cx| {
14648                    editor.inline_diagnostics = new_inline_diagnostics;
14649                    cx.notify();
14650                })
14651                .ok();
14652        });
14653    }
14654
14655    pub fn set_selections_from_remote(
14656        &mut self,
14657        selections: Vec<Selection<Anchor>>,
14658        pending_selection: Option<Selection<Anchor>>,
14659        window: &mut Window,
14660        cx: &mut Context<Self>,
14661    ) {
14662        let old_cursor_position = self.selections.newest_anchor().head();
14663        self.selections.change_with(cx, |s| {
14664            s.select_anchors(selections);
14665            if let Some(pending_selection) = pending_selection {
14666                s.set_pending(pending_selection, SelectMode::Character);
14667            } else {
14668                s.clear_pending();
14669            }
14670        });
14671        self.selections_did_change(false, &old_cursor_position, true, window, cx);
14672    }
14673
14674    fn push_to_selection_history(&mut self) {
14675        self.selection_history.push(SelectionHistoryEntry {
14676            selections: self.selections.disjoint_anchors(),
14677            select_next_state: self.select_next_state.clone(),
14678            select_prev_state: self.select_prev_state.clone(),
14679            add_selections_state: self.add_selections_state.clone(),
14680        });
14681    }
14682
14683    pub fn transact(
14684        &mut self,
14685        window: &mut Window,
14686        cx: &mut Context<Self>,
14687        update: impl FnOnce(&mut Self, &mut Window, &mut Context<Self>),
14688    ) -> Option<TransactionId> {
14689        self.start_transaction_at(Instant::now(), window, cx);
14690        update(self, window, cx);
14691        self.end_transaction_at(Instant::now(), cx)
14692    }
14693
14694    pub fn start_transaction_at(
14695        &mut self,
14696        now: Instant,
14697        window: &mut Window,
14698        cx: &mut Context<Self>,
14699    ) {
14700        self.end_selection(window, cx);
14701        if let Some(tx_id) = self
14702            .buffer
14703            .update(cx, |buffer, cx| buffer.start_transaction_at(now, cx))
14704        {
14705            self.selection_history
14706                .insert_transaction(tx_id, self.selections.disjoint_anchors());
14707            cx.emit(EditorEvent::TransactionBegun {
14708                transaction_id: tx_id,
14709            })
14710        }
14711    }
14712
14713    pub fn end_transaction_at(
14714        &mut self,
14715        now: Instant,
14716        cx: &mut Context<Self>,
14717    ) -> Option<TransactionId> {
14718        if let Some(transaction_id) = self
14719            .buffer
14720            .update(cx, |buffer, cx| buffer.end_transaction_at(now, cx))
14721        {
14722            if let Some((_, end_selections)) =
14723                self.selection_history.transaction_mut(transaction_id)
14724            {
14725                *end_selections = Some(self.selections.disjoint_anchors());
14726            } else {
14727                log::error!("unexpectedly ended a transaction that wasn't started by this editor");
14728            }
14729
14730            cx.emit(EditorEvent::Edited { transaction_id });
14731            Some(transaction_id)
14732        } else {
14733            None
14734        }
14735    }
14736
14737    pub fn set_mark(&mut self, _: &actions::SetMark, window: &mut Window, cx: &mut Context<Self>) {
14738        if self.selection_mark_mode {
14739            self.change_selections(None, window, cx, |s| {
14740                s.move_with(|_, sel| {
14741                    sel.collapse_to(sel.head(), SelectionGoal::None);
14742                });
14743            })
14744        }
14745        self.selection_mark_mode = true;
14746        cx.notify();
14747    }
14748
14749    pub fn swap_selection_ends(
14750        &mut self,
14751        _: &actions::SwapSelectionEnds,
14752        window: &mut Window,
14753        cx: &mut Context<Self>,
14754    ) {
14755        self.change_selections(None, window, cx, |s| {
14756            s.move_with(|_, sel| {
14757                if sel.start != sel.end {
14758                    sel.reversed = !sel.reversed
14759                }
14760            });
14761        });
14762        self.request_autoscroll(Autoscroll::newest(), cx);
14763        cx.notify();
14764    }
14765
14766    pub fn toggle_fold(
14767        &mut self,
14768        _: &actions::ToggleFold,
14769        window: &mut Window,
14770        cx: &mut Context<Self>,
14771    ) {
14772        if self.is_singleton(cx) {
14773            let selection = self.selections.newest::<Point>(cx);
14774
14775            let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
14776            let range = if selection.is_empty() {
14777                let point = selection.head().to_display_point(&display_map);
14778                let start = DisplayPoint::new(point.row(), 0).to_point(&display_map);
14779                let end = DisplayPoint::new(point.row(), display_map.line_len(point.row()))
14780                    .to_point(&display_map);
14781                start..end
14782            } else {
14783                selection.range()
14784            };
14785            if display_map.folds_in_range(range).next().is_some() {
14786                self.unfold_lines(&Default::default(), window, cx)
14787            } else {
14788                self.fold(&Default::default(), window, cx)
14789            }
14790        } else {
14791            let multi_buffer_snapshot = self.buffer.read(cx).snapshot(cx);
14792            let buffer_ids: HashSet<_> = self
14793                .selections
14794                .disjoint_anchor_ranges()
14795                .flat_map(|range| multi_buffer_snapshot.buffer_ids_for_range(range))
14796                .collect();
14797
14798            let should_unfold = buffer_ids
14799                .iter()
14800                .any(|buffer_id| self.is_buffer_folded(*buffer_id, cx));
14801
14802            for buffer_id in buffer_ids {
14803                if should_unfold {
14804                    self.unfold_buffer(buffer_id, cx);
14805                } else {
14806                    self.fold_buffer(buffer_id, cx);
14807                }
14808            }
14809        }
14810    }
14811
14812    pub fn toggle_fold_recursive(
14813        &mut self,
14814        _: &actions::ToggleFoldRecursive,
14815        window: &mut Window,
14816        cx: &mut Context<Self>,
14817    ) {
14818        let selection = self.selections.newest::<Point>(cx);
14819
14820        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
14821        let range = if selection.is_empty() {
14822            let point = selection.head().to_display_point(&display_map);
14823            let start = DisplayPoint::new(point.row(), 0).to_point(&display_map);
14824            let end = DisplayPoint::new(point.row(), display_map.line_len(point.row()))
14825                .to_point(&display_map);
14826            start..end
14827        } else {
14828            selection.range()
14829        };
14830        if display_map.folds_in_range(range).next().is_some() {
14831            self.unfold_recursive(&Default::default(), window, cx)
14832        } else {
14833            self.fold_recursive(&Default::default(), window, cx)
14834        }
14835    }
14836
14837    pub fn fold(&mut self, _: &actions::Fold, window: &mut Window, cx: &mut Context<Self>) {
14838        if self.is_singleton(cx) {
14839            let mut to_fold = Vec::new();
14840            let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
14841            let selections = self.selections.all_adjusted(cx);
14842
14843            for selection in selections {
14844                let range = selection.range().sorted();
14845                let buffer_start_row = range.start.row;
14846
14847                if range.start.row != range.end.row {
14848                    let mut found = false;
14849                    let mut row = range.start.row;
14850                    while row <= range.end.row {
14851                        if let Some(crease) = display_map.crease_for_buffer_row(MultiBufferRow(row))
14852                        {
14853                            found = true;
14854                            row = crease.range().end.row + 1;
14855                            to_fold.push(crease);
14856                        } else {
14857                            row += 1
14858                        }
14859                    }
14860                    if found {
14861                        continue;
14862                    }
14863                }
14864
14865                for row in (0..=range.start.row).rev() {
14866                    if let Some(crease) = display_map.crease_for_buffer_row(MultiBufferRow(row)) {
14867                        if crease.range().end.row >= buffer_start_row {
14868                            to_fold.push(crease);
14869                            if row <= range.start.row {
14870                                break;
14871                            }
14872                        }
14873                    }
14874                }
14875            }
14876
14877            self.fold_creases(to_fold, true, window, cx);
14878        } else {
14879            let multi_buffer_snapshot = self.buffer.read(cx).snapshot(cx);
14880            let buffer_ids = self
14881                .selections
14882                .disjoint_anchor_ranges()
14883                .flat_map(|range| multi_buffer_snapshot.buffer_ids_for_range(range))
14884                .collect::<HashSet<_>>();
14885            for buffer_id in buffer_ids {
14886                self.fold_buffer(buffer_id, cx);
14887            }
14888        }
14889    }
14890
14891    fn fold_at_level(
14892        &mut self,
14893        fold_at: &FoldAtLevel,
14894        window: &mut Window,
14895        cx: &mut Context<Self>,
14896    ) {
14897        if !self.buffer.read(cx).is_singleton() {
14898            return;
14899        }
14900
14901        let fold_at_level = fold_at.0;
14902        let snapshot = self.buffer.read(cx).snapshot(cx);
14903        let mut to_fold = Vec::new();
14904        let mut stack = vec![(0, snapshot.max_row().0, 1)];
14905
14906        while let Some((mut start_row, end_row, current_level)) = stack.pop() {
14907            while start_row < end_row {
14908                match self
14909                    .snapshot(window, cx)
14910                    .crease_for_buffer_row(MultiBufferRow(start_row))
14911                {
14912                    Some(crease) => {
14913                        let nested_start_row = crease.range().start.row + 1;
14914                        let nested_end_row = crease.range().end.row;
14915
14916                        if current_level < fold_at_level {
14917                            stack.push((nested_start_row, nested_end_row, current_level + 1));
14918                        } else if current_level == fold_at_level {
14919                            to_fold.push(crease);
14920                        }
14921
14922                        start_row = nested_end_row + 1;
14923                    }
14924                    None => start_row += 1,
14925                }
14926            }
14927        }
14928
14929        self.fold_creases(to_fold, true, window, cx);
14930    }
14931
14932    pub fn fold_all(&mut self, _: &actions::FoldAll, window: &mut Window, cx: &mut Context<Self>) {
14933        if self.buffer.read(cx).is_singleton() {
14934            let mut fold_ranges = Vec::new();
14935            let snapshot = self.buffer.read(cx).snapshot(cx);
14936
14937            for row in 0..snapshot.max_row().0 {
14938                if let Some(foldable_range) = self
14939                    .snapshot(window, cx)
14940                    .crease_for_buffer_row(MultiBufferRow(row))
14941                {
14942                    fold_ranges.push(foldable_range);
14943                }
14944            }
14945
14946            self.fold_creases(fold_ranges, true, window, cx);
14947        } else {
14948            self.toggle_fold_multiple_buffers = cx.spawn_in(window, async move |editor, cx| {
14949                editor
14950                    .update_in(cx, |editor, _, cx| {
14951                        for buffer_id in editor.buffer.read(cx).excerpt_buffer_ids() {
14952                            editor.fold_buffer(buffer_id, cx);
14953                        }
14954                    })
14955                    .ok();
14956            });
14957        }
14958    }
14959
14960    pub fn fold_function_bodies(
14961        &mut self,
14962        _: &actions::FoldFunctionBodies,
14963        window: &mut Window,
14964        cx: &mut Context<Self>,
14965    ) {
14966        let snapshot = self.buffer.read(cx).snapshot(cx);
14967
14968        let ranges = snapshot
14969            .text_object_ranges(0..snapshot.len(), TreeSitterOptions::default())
14970            .filter_map(|(range, obj)| (obj == TextObject::InsideFunction).then_some(range))
14971            .collect::<Vec<_>>();
14972
14973        let creases = ranges
14974            .into_iter()
14975            .map(|range| Crease::simple(range, self.display_map.read(cx).fold_placeholder.clone()))
14976            .collect();
14977
14978        self.fold_creases(creases, true, window, cx);
14979    }
14980
14981    pub fn fold_recursive(
14982        &mut self,
14983        _: &actions::FoldRecursive,
14984        window: &mut Window,
14985        cx: &mut Context<Self>,
14986    ) {
14987        let mut to_fold = Vec::new();
14988        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
14989        let selections = self.selections.all_adjusted(cx);
14990
14991        for selection in selections {
14992            let range = selection.range().sorted();
14993            let buffer_start_row = range.start.row;
14994
14995            if range.start.row != range.end.row {
14996                let mut found = false;
14997                for row in range.start.row..=range.end.row {
14998                    if let Some(crease) = display_map.crease_for_buffer_row(MultiBufferRow(row)) {
14999                        found = true;
15000                        to_fold.push(crease);
15001                    }
15002                }
15003                if found {
15004                    continue;
15005                }
15006            }
15007
15008            for row in (0..=range.start.row).rev() {
15009                if let Some(crease) = display_map.crease_for_buffer_row(MultiBufferRow(row)) {
15010                    if crease.range().end.row >= buffer_start_row {
15011                        to_fold.push(crease);
15012                    } else {
15013                        break;
15014                    }
15015                }
15016            }
15017        }
15018
15019        self.fold_creases(to_fold, true, window, cx);
15020    }
15021
15022    pub fn fold_at(
15023        &mut self,
15024        buffer_row: MultiBufferRow,
15025        window: &mut Window,
15026        cx: &mut Context<Self>,
15027    ) {
15028        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
15029
15030        if let Some(crease) = display_map.crease_for_buffer_row(buffer_row) {
15031            let autoscroll = self
15032                .selections
15033                .all::<Point>(cx)
15034                .iter()
15035                .any(|selection| crease.range().overlaps(&selection.range()));
15036
15037            self.fold_creases(vec![crease], autoscroll, window, cx);
15038        }
15039    }
15040
15041    pub fn unfold_lines(&mut self, _: &UnfoldLines, _window: &mut Window, cx: &mut Context<Self>) {
15042        if self.is_singleton(cx) {
15043            let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
15044            let buffer = &display_map.buffer_snapshot;
15045            let selections = self.selections.all::<Point>(cx);
15046            let ranges = selections
15047                .iter()
15048                .map(|s| {
15049                    let range = s.display_range(&display_map).sorted();
15050                    let mut start = range.start.to_point(&display_map);
15051                    let mut end = range.end.to_point(&display_map);
15052                    start.column = 0;
15053                    end.column = buffer.line_len(MultiBufferRow(end.row));
15054                    start..end
15055                })
15056                .collect::<Vec<_>>();
15057
15058            self.unfold_ranges(&ranges, true, true, cx);
15059        } else {
15060            let multi_buffer_snapshot = self.buffer.read(cx).snapshot(cx);
15061            let buffer_ids = self
15062                .selections
15063                .disjoint_anchor_ranges()
15064                .flat_map(|range| multi_buffer_snapshot.buffer_ids_for_range(range))
15065                .collect::<HashSet<_>>();
15066            for buffer_id in buffer_ids {
15067                self.unfold_buffer(buffer_id, cx);
15068            }
15069        }
15070    }
15071
15072    pub fn unfold_recursive(
15073        &mut self,
15074        _: &UnfoldRecursive,
15075        _window: &mut Window,
15076        cx: &mut Context<Self>,
15077    ) {
15078        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
15079        let selections = self.selections.all::<Point>(cx);
15080        let ranges = selections
15081            .iter()
15082            .map(|s| {
15083                let mut range = s.display_range(&display_map).sorted();
15084                *range.start.column_mut() = 0;
15085                *range.end.column_mut() = display_map.line_len(range.end.row());
15086                let start = range.start.to_point(&display_map);
15087                let end = range.end.to_point(&display_map);
15088                start..end
15089            })
15090            .collect::<Vec<_>>();
15091
15092        self.unfold_ranges(&ranges, true, true, cx);
15093    }
15094
15095    pub fn unfold_at(
15096        &mut self,
15097        buffer_row: MultiBufferRow,
15098        _window: &mut Window,
15099        cx: &mut Context<Self>,
15100    ) {
15101        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
15102
15103        let intersection_range = Point::new(buffer_row.0, 0)
15104            ..Point::new(
15105                buffer_row.0,
15106                display_map.buffer_snapshot.line_len(buffer_row),
15107            );
15108
15109        let autoscroll = self
15110            .selections
15111            .all::<Point>(cx)
15112            .iter()
15113            .any(|selection| RangeExt::overlaps(&selection.range(), &intersection_range));
15114
15115        self.unfold_ranges(&[intersection_range], true, autoscroll, cx);
15116    }
15117
15118    pub fn unfold_all(
15119        &mut self,
15120        _: &actions::UnfoldAll,
15121        _window: &mut Window,
15122        cx: &mut Context<Self>,
15123    ) {
15124        if self.buffer.read(cx).is_singleton() {
15125            let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
15126            self.unfold_ranges(&[0..display_map.buffer_snapshot.len()], true, true, cx);
15127        } else {
15128            self.toggle_fold_multiple_buffers = cx.spawn(async move |editor, cx| {
15129                editor
15130                    .update(cx, |editor, cx| {
15131                        for buffer_id in editor.buffer.read(cx).excerpt_buffer_ids() {
15132                            editor.unfold_buffer(buffer_id, cx);
15133                        }
15134                    })
15135                    .ok();
15136            });
15137        }
15138    }
15139
15140    pub fn fold_selected_ranges(
15141        &mut self,
15142        _: &FoldSelectedRanges,
15143        window: &mut Window,
15144        cx: &mut Context<Self>,
15145    ) {
15146        let selections = self.selections.all_adjusted(cx);
15147        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
15148        let ranges = selections
15149            .into_iter()
15150            .map(|s| Crease::simple(s.range(), display_map.fold_placeholder.clone()))
15151            .collect::<Vec<_>>();
15152        self.fold_creases(ranges, true, window, cx);
15153    }
15154
15155    pub fn fold_ranges<T: ToOffset + Clone>(
15156        &mut self,
15157        ranges: Vec<Range<T>>,
15158        auto_scroll: bool,
15159        window: &mut Window,
15160        cx: &mut Context<Self>,
15161    ) {
15162        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
15163        let ranges = ranges
15164            .into_iter()
15165            .map(|r| Crease::simple(r, display_map.fold_placeholder.clone()))
15166            .collect::<Vec<_>>();
15167        self.fold_creases(ranges, auto_scroll, window, cx);
15168    }
15169
15170    pub fn fold_creases<T: ToOffset + Clone>(
15171        &mut self,
15172        creases: Vec<Crease<T>>,
15173        auto_scroll: bool,
15174        _window: &mut Window,
15175        cx: &mut Context<Self>,
15176    ) {
15177        if creases.is_empty() {
15178            return;
15179        }
15180
15181        let mut buffers_affected = HashSet::default();
15182        let multi_buffer = self.buffer().read(cx);
15183        for crease in &creases {
15184            if let Some((_, buffer, _)) =
15185                multi_buffer.excerpt_containing(crease.range().start.clone(), cx)
15186            {
15187                buffers_affected.insert(buffer.read(cx).remote_id());
15188            };
15189        }
15190
15191        self.display_map.update(cx, |map, cx| map.fold(creases, cx));
15192
15193        if auto_scroll {
15194            self.request_autoscroll(Autoscroll::fit(), cx);
15195        }
15196
15197        cx.notify();
15198
15199        self.scrollbar_marker_state.dirty = true;
15200        self.folds_did_change(cx);
15201    }
15202
15203    /// Removes any folds whose ranges intersect any of the given ranges.
15204    pub fn unfold_ranges<T: ToOffset + Clone>(
15205        &mut self,
15206        ranges: &[Range<T>],
15207        inclusive: bool,
15208        auto_scroll: bool,
15209        cx: &mut Context<Self>,
15210    ) {
15211        self.remove_folds_with(ranges, auto_scroll, cx, |map, cx| {
15212            map.unfold_intersecting(ranges.iter().cloned(), inclusive, cx)
15213        });
15214        self.folds_did_change(cx);
15215    }
15216
15217    pub fn fold_buffer(&mut self, buffer_id: BufferId, cx: &mut Context<Self>) {
15218        if self.buffer().read(cx).is_singleton() || self.is_buffer_folded(buffer_id, cx) {
15219            return;
15220        }
15221        let folded_excerpts = self.buffer().read(cx).excerpts_for_buffer(buffer_id, cx);
15222        self.display_map.update(cx, |display_map, cx| {
15223            display_map.fold_buffers([buffer_id], cx)
15224        });
15225        cx.emit(EditorEvent::BufferFoldToggled {
15226            ids: folded_excerpts.iter().map(|&(id, _)| id).collect(),
15227            folded: true,
15228        });
15229        cx.notify();
15230    }
15231
15232    pub fn unfold_buffer(&mut self, buffer_id: BufferId, cx: &mut Context<Self>) {
15233        if self.buffer().read(cx).is_singleton() || !self.is_buffer_folded(buffer_id, cx) {
15234            return;
15235        }
15236        let unfolded_excerpts = self.buffer().read(cx).excerpts_for_buffer(buffer_id, cx);
15237        self.display_map.update(cx, |display_map, cx| {
15238            display_map.unfold_buffers([buffer_id], cx);
15239        });
15240        cx.emit(EditorEvent::BufferFoldToggled {
15241            ids: unfolded_excerpts.iter().map(|&(id, _)| id).collect(),
15242            folded: false,
15243        });
15244        cx.notify();
15245    }
15246
15247    pub fn is_buffer_folded(&self, buffer: BufferId, cx: &App) -> bool {
15248        self.display_map.read(cx).is_buffer_folded(buffer)
15249    }
15250
15251    pub fn folded_buffers<'a>(&self, cx: &'a App) -> &'a HashSet<BufferId> {
15252        self.display_map.read(cx).folded_buffers()
15253    }
15254
15255    pub fn disable_header_for_buffer(&mut self, buffer_id: BufferId, cx: &mut Context<Self>) {
15256        self.display_map.update(cx, |display_map, cx| {
15257            display_map.disable_header_for_buffer(buffer_id, cx);
15258        });
15259        cx.notify();
15260    }
15261
15262    /// Removes any folds with the given ranges.
15263    pub fn remove_folds_with_type<T: ToOffset + Clone>(
15264        &mut self,
15265        ranges: &[Range<T>],
15266        type_id: TypeId,
15267        auto_scroll: bool,
15268        cx: &mut Context<Self>,
15269    ) {
15270        self.remove_folds_with(ranges, auto_scroll, cx, |map, cx| {
15271            map.remove_folds_with_type(ranges.iter().cloned(), type_id, cx)
15272        });
15273        self.folds_did_change(cx);
15274    }
15275
15276    fn remove_folds_with<T: ToOffset + Clone>(
15277        &mut self,
15278        ranges: &[Range<T>],
15279        auto_scroll: bool,
15280        cx: &mut Context<Self>,
15281        update: impl FnOnce(&mut DisplayMap, &mut Context<DisplayMap>),
15282    ) {
15283        if ranges.is_empty() {
15284            return;
15285        }
15286
15287        let mut buffers_affected = HashSet::default();
15288        let multi_buffer = self.buffer().read(cx);
15289        for range in ranges {
15290            if let Some((_, buffer, _)) = multi_buffer.excerpt_containing(range.start.clone(), cx) {
15291                buffers_affected.insert(buffer.read(cx).remote_id());
15292            };
15293        }
15294
15295        self.display_map.update(cx, update);
15296
15297        if auto_scroll {
15298            self.request_autoscroll(Autoscroll::fit(), cx);
15299        }
15300
15301        cx.notify();
15302        self.scrollbar_marker_state.dirty = true;
15303        self.active_indent_guides_state.dirty = true;
15304    }
15305
15306    pub fn update_fold_widths(
15307        &mut self,
15308        widths: impl IntoIterator<Item = (FoldId, Pixels)>,
15309        cx: &mut Context<Self>,
15310    ) -> bool {
15311        self.display_map
15312            .update(cx, |map, cx| map.update_fold_widths(widths, cx))
15313    }
15314
15315    pub fn default_fold_placeholder(&self, cx: &App) -> FoldPlaceholder {
15316        self.display_map.read(cx).fold_placeholder.clone()
15317    }
15318
15319    pub fn set_expand_all_diff_hunks(&mut self, cx: &mut App) {
15320        self.buffer.update(cx, |buffer, cx| {
15321            buffer.set_all_diff_hunks_expanded(cx);
15322        });
15323    }
15324
15325    pub fn expand_all_diff_hunks(
15326        &mut self,
15327        _: &ExpandAllDiffHunks,
15328        _window: &mut Window,
15329        cx: &mut Context<Self>,
15330    ) {
15331        self.buffer.update(cx, |buffer, cx| {
15332            buffer.expand_diff_hunks(vec![Anchor::min()..Anchor::max()], cx)
15333        });
15334    }
15335
15336    pub fn toggle_selected_diff_hunks(
15337        &mut self,
15338        _: &ToggleSelectedDiffHunks,
15339        _window: &mut Window,
15340        cx: &mut Context<Self>,
15341    ) {
15342        let ranges: Vec<_> = self.selections.disjoint.iter().map(|s| s.range()).collect();
15343        self.toggle_diff_hunks_in_ranges(ranges, cx);
15344    }
15345
15346    pub fn diff_hunks_in_ranges<'a>(
15347        &'a self,
15348        ranges: &'a [Range<Anchor>],
15349        buffer: &'a MultiBufferSnapshot,
15350    ) -> impl 'a + Iterator<Item = MultiBufferDiffHunk> {
15351        ranges.iter().flat_map(move |range| {
15352            let end_excerpt_id = range.end.excerpt_id;
15353            let range = range.to_point(buffer);
15354            let mut peek_end = range.end;
15355            if range.end.row < buffer.max_row().0 {
15356                peek_end = Point::new(range.end.row + 1, 0);
15357            }
15358            buffer
15359                .diff_hunks_in_range(range.start..peek_end)
15360                .filter(move |hunk| hunk.excerpt_id.cmp(&end_excerpt_id, buffer).is_le())
15361        })
15362    }
15363
15364    pub fn has_stageable_diff_hunks_in_ranges(
15365        &self,
15366        ranges: &[Range<Anchor>],
15367        snapshot: &MultiBufferSnapshot,
15368    ) -> bool {
15369        let mut hunks = self.diff_hunks_in_ranges(ranges, &snapshot);
15370        hunks.any(|hunk| hunk.status().has_secondary_hunk())
15371    }
15372
15373    pub fn toggle_staged_selected_diff_hunks(
15374        &mut self,
15375        _: &::git::ToggleStaged,
15376        _: &mut Window,
15377        cx: &mut Context<Self>,
15378    ) {
15379        let snapshot = self.buffer.read(cx).snapshot(cx);
15380        let ranges: Vec<_> = self.selections.disjoint.iter().map(|s| s.range()).collect();
15381        let stage = self.has_stageable_diff_hunks_in_ranges(&ranges, &snapshot);
15382        self.stage_or_unstage_diff_hunks(stage, ranges, cx);
15383    }
15384
15385    pub fn set_render_diff_hunk_controls(
15386        &mut self,
15387        render_diff_hunk_controls: RenderDiffHunkControlsFn,
15388        cx: &mut Context<Self>,
15389    ) {
15390        self.render_diff_hunk_controls = render_diff_hunk_controls;
15391        cx.notify();
15392    }
15393
15394    pub fn stage_and_next(
15395        &mut self,
15396        _: &::git::StageAndNext,
15397        window: &mut Window,
15398        cx: &mut Context<Self>,
15399    ) {
15400        self.do_stage_or_unstage_and_next(true, window, cx);
15401    }
15402
15403    pub fn unstage_and_next(
15404        &mut self,
15405        _: &::git::UnstageAndNext,
15406        window: &mut Window,
15407        cx: &mut Context<Self>,
15408    ) {
15409        self.do_stage_or_unstage_and_next(false, window, cx);
15410    }
15411
15412    pub fn stage_or_unstage_diff_hunks(
15413        &mut self,
15414        stage: bool,
15415        ranges: Vec<Range<Anchor>>,
15416        cx: &mut Context<Self>,
15417    ) {
15418        let task = self.save_buffers_for_ranges_if_needed(&ranges, cx);
15419        cx.spawn(async move |this, cx| {
15420            task.await?;
15421            this.update(cx, |this, cx| {
15422                let snapshot = this.buffer.read(cx).snapshot(cx);
15423                let chunk_by = this
15424                    .diff_hunks_in_ranges(&ranges, &snapshot)
15425                    .chunk_by(|hunk| hunk.buffer_id);
15426                for (buffer_id, hunks) in &chunk_by {
15427                    this.do_stage_or_unstage(stage, buffer_id, hunks, cx);
15428                }
15429            })
15430        })
15431        .detach_and_log_err(cx);
15432    }
15433
15434    fn save_buffers_for_ranges_if_needed(
15435        &mut self,
15436        ranges: &[Range<Anchor>],
15437        cx: &mut Context<Editor>,
15438    ) -> Task<Result<()>> {
15439        let multibuffer = self.buffer.read(cx);
15440        let snapshot = multibuffer.read(cx);
15441        let buffer_ids: HashSet<_> = ranges
15442            .iter()
15443            .flat_map(|range| snapshot.buffer_ids_for_range(range.clone()))
15444            .collect();
15445        drop(snapshot);
15446
15447        let mut buffers = HashSet::default();
15448        for buffer_id in buffer_ids {
15449            if let Some(buffer_entity) = multibuffer.buffer(buffer_id) {
15450                let buffer = buffer_entity.read(cx);
15451                if buffer.file().is_some_and(|file| file.disk_state().exists()) && buffer.is_dirty()
15452                {
15453                    buffers.insert(buffer_entity);
15454                }
15455            }
15456        }
15457
15458        if let Some(project) = &self.project {
15459            project.update(cx, |project, cx| project.save_buffers(buffers, cx))
15460        } else {
15461            Task::ready(Ok(()))
15462        }
15463    }
15464
15465    fn do_stage_or_unstage_and_next(
15466        &mut self,
15467        stage: bool,
15468        window: &mut Window,
15469        cx: &mut Context<Self>,
15470    ) {
15471        let ranges = self.selections.disjoint_anchor_ranges().collect::<Vec<_>>();
15472
15473        if ranges.iter().any(|range| range.start != range.end) {
15474            self.stage_or_unstage_diff_hunks(stage, ranges, cx);
15475            return;
15476        }
15477
15478        self.stage_or_unstage_diff_hunks(stage, ranges, cx);
15479        let snapshot = self.snapshot(window, cx);
15480        let position = self.selections.newest::<Point>(cx).head();
15481        let mut row = snapshot
15482            .buffer_snapshot
15483            .diff_hunks_in_range(position..snapshot.buffer_snapshot.max_point())
15484            .find(|hunk| hunk.row_range.start.0 > position.row)
15485            .map(|hunk| hunk.row_range.start);
15486
15487        let all_diff_hunks_expanded = self.buffer().read(cx).all_diff_hunks_expanded();
15488        // Outside of the project diff editor, wrap around to the beginning.
15489        if !all_diff_hunks_expanded {
15490            row = row.or_else(|| {
15491                snapshot
15492                    .buffer_snapshot
15493                    .diff_hunks_in_range(Point::zero()..position)
15494                    .find(|hunk| hunk.row_range.end.0 < position.row)
15495                    .map(|hunk| hunk.row_range.start)
15496            });
15497        }
15498
15499        if let Some(row) = row {
15500            let destination = Point::new(row.0, 0);
15501            let autoscroll = Autoscroll::center();
15502
15503            self.unfold_ranges(&[destination..destination], false, false, cx);
15504            self.change_selections(Some(autoscroll), window, cx, |s| {
15505                s.select_ranges([destination..destination]);
15506            });
15507        }
15508    }
15509
15510    fn do_stage_or_unstage(
15511        &self,
15512        stage: bool,
15513        buffer_id: BufferId,
15514        hunks: impl Iterator<Item = MultiBufferDiffHunk>,
15515        cx: &mut App,
15516    ) -> Option<()> {
15517        let project = self.project.as_ref()?;
15518        let buffer = project.read(cx).buffer_for_id(buffer_id, cx)?;
15519        let diff = self.buffer.read(cx).diff_for(buffer_id)?;
15520        let buffer_snapshot = buffer.read(cx).snapshot();
15521        let file_exists = buffer_snapshot
15522            .file()
15523            .is_some_and(|file| file.disk_state().exists());
15524        diff.update(cx, |diff, cx| {
15525            diff.stage_or_unstage_hunks(
15526                stage,
15527                &hunks
15528                    .map(|hunk| buffer_diff::DiffHunk {
15529                        buffer_range: hunk.buffer_range,
15530                        diff_base_byte_range: hunk.diff_base_byte_range,
15531                        secondary_status: hunk.secondary_status,
15532                        range: Point::zero()..Point::zero(), // unused
15533                    })
15534                    .collect::<Vec<_>>(),
15535                &buffer_snapshot,
15536                file_exists,
15537                cx,
15538            )
15539        });
15540        None
15541    }
15542
15543    pub fn expand_selected_diff_hunks(&mut self, cx: &mut Context<Self>) {
15544        let ranges: Vec<_> = self.selections.disjoint.iter().map(|s| s.range()).collect();
15545        self.buffer
15546            .update(cx, |buffer, cx| buffer.expand_diff_hunks(ranges, cx))
15547    }
15548
15549    pub fn clear_expanded_diff_hunks(&mut self, cx: &mut Context<Self>) -> bool {
15550        self.buffer.update(cx, |buffer, cx| {
15551            let ranges = vec![Anchor::min()..Anchor::max()];
15552            if !buffer.all_diff_hunks_expanded()
15553                && buffer.has_expanded_diff_hunks_in_ranges(&ranges, cx)
15554            {
15555                buffer.collapse_diff_hunks(ranges, cx);
15556                true
15557            } else {
15558                false
15559            }
15560        })
15561    }
15562
15563    fn toggle_diff_hunks_in_ranges(
15564        &mut self,
15565        ranges: Vec<Range<Anchor>>,
15566        cx: &mut Context<Editor>,
15567    ) {
15568        self.buffer.update(cx, |buffer, cx| {
15569            let expand = !buffer.has_expanded_diff_hunks_in_ranges(&ranges, cx);
15570            buffer.expand_or_collapse_diff_hunks(ranges, expand, cx);
15571        })
15572    }
15573
15574    fn toggle_single_diff_hunk(&mut self, range: Range<Anchor>, cx: &mut Context<Self>) {
15575        self.buffer.update(cx, |buffer, cx| {
15576            let snapshot = buffer.snapshot(cx);
15577            let excerpt_id = range.end.excerpt_id;
15578            let point_range = range.to_point(&snapshot);
15579            let expand = !buffer.single_hunk_is_expanded(range, cx);
15580            buffer.expand_or_collapse_diff_hunks_inner([(point_range, excerpt_id)], expand, cx);
15581        })
15582    }
15583
15584    pub(crate) fn apply_all_diff_hunks(
15585        &mut self,
15586        _: &ApplyAllDiffHunks,
15587        window: &mut Window,
15588        cx: &mut Context<Self>,
15589    ) {
15590        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
15591
15592        let buffers = self.buffer.read(cx).all_buffers();
15593        for branch_buffer in buffers {
15594            branch_buffer.update(cx, |branch_buffer, cx| {
15595                branch_buffer.merge_into_base(Vec::new(), cx);
15596            });
15597        }
15598
15599        if let Some(project) = self.project.clone() {
15600            self.save(true, project, window, cx).detach_and_log_err(cx);
15601        }
15602    }
15603
15604    pub(crate) fn apply_selected_diff_hunks(
15605        &mut self,
15606        _: &ApplyDiffHunk,
15607        window: &mut Window,
15608        cx: &mut Context<Self>,
15609    ) {
15610        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
15611        let snapshot = self.snapshot(window, cx);
15612        let hunks = snapshot.hunks_for_ranges(self.selections.ranges(cx));
15613        let mut ranges_by_buffer = HashMap::default();
15614        self.transact(window, cx, |editor, _window, cx| {
15615            for hunk in hunks {
15616                if let Some(buffer) = editor.buffer.read(cx).buffer(hunk.buffer_id) {
15617                    ranges_by_buffer
15618                        .entry(buffer.clone())
15619                        .or_insert_with(Vec::new)
15620                        .push(hunk.buffer_range.to_offset(buffer.read(cx)));
15621                }
15622            }
15623
15624            for (buffer, ranges) in ranges_by_buffer {
15625                buffer.update(cx, |buffer, cx| {
15626                    buffer.merge_into_base(ranges, cx);
15627                });
15628            }
15629        });
15630
15631        if let Some(project) = self.project.clone() {
15632            self.save(true, project, window, cx).detach_and_log_err(cx);
15633        }
15634    }
15635
15636    pub fn set_gutter_hovered(&mut self, hovered: bool, cx: &mut Context<Self>) {
15637        if hovered != self.gutter_hovered {
15638            self.gutter_hovered = hovered;
15639            cx.notify();
15640        }
15641    }
15642
15643    pub fn insert_blocks(
15644        &mut self,
15645        blocks: impl IntoIterator<Item = BlockProperties<Anchor>>,
15646        autoscroll: Option<Autoscroll>,
15647        cx: &mut Context<Self>,
15648    ) -> Vec<CustomBlockId> {
15649        let blocks = self
15650            .display_map
15651            .update(cx, |display_map, cx| display_map.insert_blocks(blocks, cx));
15652        if let Some(autoscroll) = autoscroll {
15653            self.request_autoscroll(autoscroll, cx);
15654        }
15655        cx.notify();
15656        blocks
15657    }
15658
15659    pub fn resize_blocks(
15660        &mut self,
15661        heights: HashMap<CustomBlockId, u32>,
15662        autoscroll: Option<Autoscroll>,
15663        cx: &mut Context<Self>,
15664    ) {
15665        self.display_map
15666            .update(cx, |display_map, cx| display_map.resize_blocks(heights, cx));
15667        if let Some(autoscroll) = autoscroll {
15668            self.request_autoscroll(autoscroll, cx);
15669        }
15670        cx.notify();
15671    }
15672
15673    pub fn replace_blocks(
15674        &mut self,
15675        renderers: HashMap<CustomBlockId, RenderBlock>,
15676        autoscroll: Option<Autoscroll>,
15677        cx: &mut Context<Self>,
15678    ) {
15679        self.display_map
15680            .update(cx, |display_map, _cx| display_map.replace_blocks(renderers));
15681        if let Some(autoscroll) = autoscroll {
15682            self.request_autoscroll(autoscroll, cx);
15683        }
15684        cx.notify();
15685    }
15686
15687    pub fn remove_blocks(
15688        &mut self,
15689        block_ids: HashSet<CustomBlockId>,
15690        autoscroll: Option<Autoscroll>,
15691        cx: &mut Context<Self>,
15692    ) {
15693        self.display_map.update(cx, |display_map, cx| {
15694            display_map.remove_blocks(block_ids, cx)
15695        });
15696        if let Some(autoscroll) = autoscroll {
15697            self.request_autoscroll(autoscroll, cx);
15698        }
15699        cx.notify();
15700    }
15701
15702    pub fn row_for_block(
15703        &self,
15704        block_id: CustomBlockId,
15705        cx: &mut Context<Self>,
15706    ) -> Option<DisplayRow> {
15707        self.display_map
15708            .update(cx, |map, cx| map.row_for_block(block_id, cx))
15709    }
15710
15711    pub(crate) fn set_focused_block(&mut self, focused_block: FocusedBlock) {
15712        self.focused_block = Some(focused_block);
15713    }
15714
15715    pub(crate) fn take_focused_block(&mut self) -> Option<FocusedBlock> {
15716        self.focused_block.take()
15717    }
15718
15719    pub fn insert_creases(
15720        &mut self,
15721        creases: impl IntoIterator<Item = Crease<Anchor>>,
15722        cx: &mut Context<Self>,
15723    ) -> Vec<CreaseId> {
15724        self.display_map
15725            .update(cx, |map, cx| map.insert_creases(creases, cx))
15726    }
15727
15728    pub fn remove_creases(
15729        &mut self,
15730        ids: impl IntoIterator<Item = CreaseId>,
15731        cx: &mut Context<Self>,
15732    ) {
15733        self.display_map
15734            .update(cx, |map, cx| map.remove_creases(ids, cx));
15735    }
15736
15737    pub fn longest_row(&self, cx: &mut App) -> DisplayRow {
15738        self.display_map
15739            .update(cx, |map, cx| map.snapshot(cx))
15740            .longest_row()
15741    }
15742
15743    pub fn max_point(&self, cx: &mut App) -> DisplayPoint {
15744        self.display_map
15745            .update(cx, |map, cx| map.snapshot(cx))
15746            .max_point()
15747    }
15748
15749    pub fn text(&self, cx: &App) -> String {
15750        self.buffer.read(cx).read(cx).text()
15751    }
15752
15753    pub fn is_empty(&self, cx: &App) -> bool {
15754        self.buffer.read(cx).read(cx).is_empty()
15755    }
15756
15757    pub fn text_option(&self, cx: &App) -> Option<String> {
15758        let text = self.text(cx);
15759        let text = text.trim();
15760
15761        if text.is_empty() {
15762            return None;
15763        }
15764
15765        Some(text.to_string())
15766    }
15767
15768    pub fn set_text(
15769        &mut self,
15770        text: impl Into<Arc<str>>,
15771        window: &mut Window,
15772        cx: &mut Context<Self>,
15773    ) {
15774        self.transact(window, cx, |this, _, cx| {
15775            this.buffer
15776                .read(cx)
15777                .as_singleton()
15778                .expect("you can only call set_text on editors for singleton buffers")
15779                .update(cx, |buffer, cx| buffer.set_text(text, cx));
15780        });
15781    }
15782
15783    pub fn display_text(&self, cx: &mut App) -> String {
15784        self.display_map
15785            .update(cx, |map, cx| map.snapshot(cx))
15786            .text()
15787    }
15788
15789    pub fn wrap_guides(&self, cx: &App) -> SmallVec<[(usize, bool); 2]> {
15790        let mut wrap_guides = smallvec::smallvec![];
15791
15792        if self.show_wrap_guides == Some(false) {
15793            return wrap_guides;
15794        }
15795
15796        let settings = self.buffer.read(cx).language_settings(cx);
15797        if settings.show_wrap_guides {
15798            match self.soft_wrap_mode(cx) {
15799                SoftWrap::Column(soft_wrap) => {
15800                    wrap_guides.push((soft_wrap as usize, true));
15801                }
15802                SoftWrap::Bounded(soft_wrap) => {
15803                    wrap_guides.push((soft_wrap as usize, true));
15804                }
15805                SoftWrap::GitDiff | SoftWrap::None | SoftWrap::EditorWidth => {}
15806            }
15807            wrap_guides.extend(settings.wrap_guides.iter().map(|guide| (*guide, false)))
15808        }
15809
15810        wrap_guides
15811    }
15812
15813    pub fn soft_wrap_mode(&self, cx: &App) -> SoftWrap {
15814        let settings = self.buffer.read(cx).language_settings(cx);
15815        let mode = self.soft_wrap_mode_override.unwrap_or(settings.soft_wrap);
15816        match mode {
15817            language_settings::SoftWrap::PreferLine | language_settings::SoftWrap::None => {
15818                SoftWrap::None
15819            }
15820            language_settings::SoftWrap::EditorWidth => SoftWrap::EditorWidth,
15821            language_settings::SoftWrap::PreferredLineLength => {
15822                SoftWrap::Column(settings.preferred_line_length)
15823            }
15824            language_settings::SoftWrap::Bounded => {
15825                SoftWrap::Bounded(settings.preferred_line_length)
15826            }
15827        }
15828    }
15829
15830    pub fn set_soft_wrap_mode(
15831        &mut self,
15832        mode: language_settings::SoftWrap,
15833
15834        cx: &mut Context<Self>,
15835    ) {
15836        self.soft_wrap_mode_override = Some(mode);
15837        cx.notify();
15838    }
15839
15840    pub fn set_hard_wrap(&mut self, hard_wrap: Option<usize>, cx: &mut Context<Self>) {
15841        self.hard_wrap = hard_wrap;
15842        cx.notify();
15843    }
15844
15845    pub fn set_text_style_refinement(&mut self, style: TextStyleRefinement) {
15846        self.text_style_refinement = Some(style);
15847    }
15848
15849    /// called by the Element so we know what style we were most recently rendered with.
15850    pub(crate) fn set_style(
15851        &mut self,
15852        style: EditorStyle,
15853        window: &mut Window,
15854        cx: &mut Context<Self>,
15855    ) {
15856        let rem_size = window.rem_size();
15857        self.display_map.update(cx, |map, cx| {
15858            map.set_font(
15859                style.text.font(),
15860                style.text.font_size.to_pixels(rem_size),
15861                cx,
15862            )
15863        });
15864        self.style = Some(style);
15865    }
15866
15867    pub fn style(&self) -> Option<&EditorStyle> {
15868        self.style.as_ref()
15869    }
15870
15871    // Called by the element. This method is not designed to be called outside of the editor
15872    // element's layout code because it does not notify when rewrapping is computed synchronously.
15873    pub(crate) fn set_wrap_width(&self, width: Option<Pixels>, cx: &mut App) -> bool {
15874        self.display_map
15875            .update(cx, |map, cx| map.set_wrap_width(width, cx))
15876    }
15877
15878    pub fn set_soft_wrap(&mut self) {
15879        self.soft_wrap_mode_override = Some(language_settings::SoftWrap::EditorWidth)
15880    }
15881
15882    pub fn toggle_soft_wrap(&mut self, _: &ToggleSoftWrap, _: &mut Window, cx: &mut Context<Self>) {
15883        if self.soft_wrap_mode_override.is_some() {
15884            self.soft_wrap_mode_override.take();
15885        } else {
15886            let soft_wrap = match self.soft_wrap_mode(cx) {
15887                SoftWrap::GitDiff => return,
15888                SoftWrap::None => language_settings::SoftWrap::EditorWidth,
15889                SoftWrap::EditorWidth | SoftWrap::Column(_) | SoftWrap::Bounded(_) => {
15890                    language_settings::SoftWrap::None
15891                }
15892            };
15893            self.soft_wrap_mode_override = Some(soft_wrap);
15894        }
15895        cx.notify();
15896    }
15897
15898    pub fn toggle_tab_bar(&mut self, _: &ToggleTabBar, _: &mut Window, cx: &mut Context<Self>) {
15899        let Some(workspace) = self.workspace() else {
15900            return;
15901        };
15902        let fs = workspace.read(cx).app_state().fs.clone();
15903        let current_show = TabBarSettings::get_global(cx).show;
15904        update_settings_file::<TabBarSettings>(fs, cx, move |setting, _| {
15905            setting.show = Some(!current_show);
15906        });
15907    }
15908
15909    pub fn toggle_indent_guides(
15910        &mut self,
15911        _: &ToggleIndentGuides,
15912        _: &mut Window,
15913        cx: &mut Context<Self>,
15914    ) {
15915        let currently_enabled = self.should_show_indent_guides().unwrap_or_else(|| {
15916            self.buffer
15917                .read(cx)
15918                .language_settings(cx)
15919                .indent_guides
15920                .enabled
15921        });
15922        self.show_indent_guides = Some(!currently_enabled);
15923        cx.notify();
15924    }
15925
15926    fn should_show_indent_guides(&self) -> Option<bool> {
15927        self.show_indent_guides
15928    }
15929
15930    pub fn toggle_line_numbers(
15931        &mut self,
15932        _: &ToggleLineNumbers,
15933        _: &mut Window,
15934        cx: &mut Context<Self>,
15935    ) {
15936        let mut editor_settings = EditorSettings::get_global(cx).clone();
15937        editor_settings.gutter.line_numbers = !editor_settings.gutter.line_numbers;
15938        EditorSettings::override_global(editor_settings, cx);
15939    }
15940
15941    pub fn line_numbers_enabled(&self, cx: &App) -> bool {
15942        if let Some(show_line_numbers) = self.show_line_numbers {
15943            return show_line_numbers;
15944        }
15945        EditorSettings::get_global(cx).gutter.line_numbers
15946    }
15947
15948    pub fn should_use_relative_line_numbers(&self, cx: &mut App) -> bool {
15949        self.use_relative_line_numbers
15950            .unwrap_or(EditorSettings::get_global(cx).relative_line_numbers)
15951    }
15952
15953    pub fn toggle_relative_line_numbers(
15954        &mut self,
15955        _: &ToggleRelativeLineNumbers,
15956        _: &mut Window,
15957        cx: &mut Context<Self>,
15958    ) {
15959        let is_relative = self.should_use_relative_line_numbers(cx);
15960        self.set_relative_line_number(Some(!is_relative), cx)
15961    }
15962
15963    pub fn set_relative_line_number(&mut self, is_relative: Option<bool>, cx: &mut Context<Self>) {
15964        self.use_relative_line_numbers = is_relative;
15965        cx.notify();
15966    }
15967
15968    pub fn set_show_gutter(&mut self, show_gutter: bool, cx: &mut Context<Self>) {
15969        self.show_gutter = show_gutter;
15970        cx.notify();
15971    }
15972
15973    pub fn set_show_scrollbars(&mut self, show_scrollbars: bool, cx: &mut Context<Self>) {
15974        self.show_scrollbars = show_scrollbars;
15975        cx.notify();
15976    }
15977
15978    pub fn set_show_line_numbers(&mut self, show_line_numbers: bool, cx: &mut Context<Self>) {
15979        self.show_line_numbers = Some(show_line_numbers);
15980        cx.notify();
15981    }
15982
15983    pub fn set_show_git_diff_gutter(&mut self, show_git_diff_gutter: bool, cx: &mut Context<Self>) {
15984        self.show_git_diff_gutter = Some(show_git_diff_gutter);
15985        cx.notify();
15986    }
15987
15988    pub fn set_show_code_actions(&mut self, show_code_actions: bool, cx: &mut Context<Self>) {
15989        self.show_code_actions = Some(show_code_actions);
15990        cx.notify();
15991    }
15992
15993    pub fn set_show_runnables(&mut self, show_runnables: bool, cx: &mut Context<Self>) {
15994        self.show_runnables = Some(show_runnables);
15995        cx.notify();
15996    }
15997
15998    pub fn set_show_breakpoints(&mut self, show_breakpoints: bool, cx: &mut Context<Self>) {
15999        self.show_breakpoints = Some(show_breakpoints);
16000        cx.notify();
16001    }
16002
16003    pub fn set_masked(&mut self, masked: bool, cx: &mut Context<Self>) {
16004        if self.display_map.read(cx).masked != masked {
16005            self.display_map.update(cx, |map, _| map.masked = masked);
16006        }
16007        cx.notify()
16008    }
16009
16010    pub fn set_show_wrap_guides(&mut self, show_wrap_guides: bool, cx: &mut Context<Self>) {
16011        self.show_wrap_guides = Some(show_wrap_guides);
16012        cx.notify();
16013    }
16014
16015    pub fn set_show_indent_guides(&mut self, show_indent_guides: bool, cx: &mut Context<Self>) {
16016        self.show_indent_guides = Some(show_indent_guides);
16017        cx.notify();
16018    }
16019
16020    pub fn working_directory(&self, cx: &App) -> Option<PathBuf> {
16021        if let Some(buffer) = self.buffer().read(cx).as_singleton() {
16022            if let Some(file) = buffer.read(cx).file().and_then(|f| f.as_local()) {
16023                if let Some(dir) = file.abs_path(cx).parent() {
16024                    return Some(dir.to_owned());
16025                }
16026            }
16027
16028            if let Some(project_path) = buffer.read(cx).project_path(cx) {
16029                return Some(project_path.path.to_path_buf());
16030            }
16031        }
16032
16033        None
16034    }
16035
16036    fn target_file<'a>(&self, cx: &'a App) -> Option<&'a dyn language::LocalFile> {
16037        self.active_excerpt(cx)?
16038            .1
16039            .read(cx)
16040            .file()
16041            .and_then(|f| f.as_local())
16042    }
16043
16044    pub fn target_file_abs_path(&self, cx: &mut Context<Self>) -> Option<PathBuf> {
16045        self.active_excerpt(cx).and_then(|(_, buffer, _)| {
16046            let buffer = buffer.read(cx);
16047            if let Some(project_path) = buffer.project_path(cx) {
16048                let project = self.project.as_ref()?.read(cx);
16049                project.absolute_path(&project_path, cx)
16050            } else {
16051                buffer
16052                    .file()
16053                    .and_then(|file| file.as_local().map(|file| file.abs_path(cx)))
16054            }
16055        })
16056    }
16057
16058    fn target_file_path(&self, cx: &mut Context<Self>) -> Option<PathBuf> {
16059        self.active_excerpt(cx).and_then(|(_, buffer, _)| {
16060            let project_path = buffer.read(cx).project_path(cx)?;
16061            let project = self.project.as_ref()?.read(cx);
16062            let entry = project.entry_for_path(&project_path, cx)?;
16063            let path = entry.path.to_path_buf();
16064            Some(path)
16065        })
16066    }
16067
16068    pub fn reveal_in_finder(
16069        &mut self,
16070        _: &RevealInFileManager,
16071        _window: &mut Window,
16072        cx: &mut Context<Self>,
16073    ) {
16074        if let Some(target) = self.target_file(cx) {
16075            cx.reveal_path(&target.abs_path(cx));
16076        }
16077    }
16078
16079    pub fn copy_path(
16080        &mut self,
16081        _: &zed_actions::workspace::CopyPath,
16082        _window: &mut Window,
16083        cx: &mut Context<Self>,
16084    ) {
16085        if let Some(path) = self.target_file_abs_path(cx) {
16086            if let Some(path) = path.to_str() {
16087                cx.write_to_clipboard(ClipboardItem::new_string(path.to_string()));
16088            }
16089        }
16090    }
16091
16092    pub fn copy_relative_path(
16093        &mut self,
16094        _: &zed_actions::workspace::CopyRelativePath,
16095        _window: &mut Window,
16096        cx: &mut Context<Self>,
16097    ) {
16098        if let Some(path) = self.target_file_path(cx) {
16099            if let Some(path) = path.to_str() {
16100                cx.write_to_clipboard(ClipboardItem::new_string(path.to_string()));
16101            }
16102        }
16103    }
16104
16105    pub fn project_path(&self, cx: &App) -> Option<ProjectPath> {
16106        if let Some(buffer) = self.buffer.read(cx).as_singleton() {
16107            buffer.read(cx).project_path(cx)
16108        } else {
16109            None
16110        }
16111    }
16112
16113    // Returns true if the editor handled a go-to-line request
16114    pub fn go_to_active_debug_line(&mut self, window: &mut Window, cx: &mut Context<Self>) -> bool {
16115        maybe!({
16116            let breakpoint_store = self.breakpoint_store.as_ref()?;
16117
16118            let Some((_, _, active_position)) =
16119                breakpoint_store.read(cx).active_position().cloned()
16120            else {
16121                self.clear_row_highlights::<DebugCurrentRowHighlight>();
16122                return None;
16123            };
16124
16125            let snapshot = self
16126                .project
16127                .as_ref()?
16128                .read(cx)
16129                .buffer_for_id(active_position.buffer_id?, cx)?
16130                .read(cx)
16131                .snapshot();
16132
16133            let mut handled = false;
16134            for (id, ExcerptRange { context, .. }) in self
16135                .buffer
16136                .read(cx)
16137                .excerpts_for_buffer(active_position.buffer_id?, cx)
16138            {
16139                if context.start.cmp(&active_position, &snapshot).is_ge()
16140                    || context.end.cmp(&active_position, &snapshot).is_lt()
16141                {
16142                    continue;
16143                }
16144                let snapshot = self.buffer.read(cx).snapshot(cx);
16145                let multibuffer_anchor = snapshot.anchor_in_excerpt(id, active_position)?;
16146
16147                handled = true;
16148                self.clear_row_highlights::<DebugCurrentRowHighlight>();
16149                self.go_to_line::<DebugCurrentRowHighlight>(
16150                    multibuffer_anchor,
16151                    Some(cx.theme().colors().editor_debugger_active_line_background),
16152                    window,
16153                    cx,
16154                );
16155
16156                cx.notify();
16157            }
16158            handled.then_some(())
16159        })
16160        .is_some()
16161    }
16162
16163    pub fn copy_file_name_without_extension(
16164        &mut self,
16165        _: &CopyFileNameWithoutExtension,
16166        _: &mut Window,
16167        cx: &mut Context<Self>,
16168    ) {
16169        if let Some(file) = self.target_file(cx) {
16170            if let Some(file_stem) = file.path().file_stem() {
16171                if let Some(name) = file_stem.to_str() {
16172                    cx.write_to_clipboard(ClipboardItem::new_string(name.to_string()));
16173                }
16174            }
16175        }
16176    }
16177
16178    pub fn copy_file_name(&mut self, _: &CopyFileName, _: &mut Window, cx: &mut Context<Self>) {
16179        if let Some(file) = self.target_file(cx) {
16180            if let Some(file_name) = file.path().file_name() {
16181                if let Some(name) = file_name.to_str() {
16182                    cx.write_to_clipboard(ClipboardItem::new_string(name.to_string()));
16183                }
16184            }
16185        }
16186    }
16187
16188    pub fn toggle_git_blame(
16189        &mut self,
16190        _: &::git::Blame,
16191        window: &mut Window,
16192        cx: &mut Context<Self>,
16193    ) {
16194        self.show_git_blame_gutter = !self.show_git_blame_gutter;
16195
16196        if self.show_git_blame_gutter && !self.has_blame_entries(cx) {
16197            self.start_git_blame(true, window, cx);
16198        }
16199
16200        cx.notify();
16201    }
16202
16203    pub fn toggle_git_blame_inline(
16204        &mut self,
16205        _: &ToggleGitBlameInline,
16206        window: &mut Window,
16207        cx: &mut Context<Self>,
16208    ) {
16209        self.toggle_git_blame_inline_internal(true, window, cx);
16210        cx.notify();
16211    }
16212
16213    pub fn open_git_blame_commit(
16214        &mut self,
16215        _: &OpenGitBlameCommit,
16216        window: &mut Window,
16217        cx: &mut Context<Self>,
16218    ) {
16219        self.open_git_blame_commit_internal(window, cx);
16220    }
16221
16222    fn open_git_blame_commit_internal(
16223        &mut self,
16224        window: &mut Window,
16225        cx: &mut Context<Self>,
16226    ) -> Option<()> {
16227        let blame = self.blame.as_ref()?;
16228        let snapshot = self.snapshot(window, cx);
16229        let cursor = self.selections.newest::<Point>(cx).head();
16230        let (buffer, point, _) = snapshot.buffer_snapshot.point_to_buffer_point(cursor)?;
16231        let blame_entry = blame
16232            .update(cx, |blame, cx| {
16233                blame
16234                    .blame_for_rows(
16235                        &[RowInfo {
16236                            buffer_id: Some(buffer.remote_id()),
16237                            buffer_row: Some(point.row),
16238                            ..Default::default()
16239                        }],
16240                        cx,
16241                    )
16242                    .next()
16243            })
16244            .flatten()?;
16245        let renderer = cx.global::<GlobalBlameRenderer>().0.clone();
16246        let repo = blame.read(cx).repository(cx)?;
16247        let workspace = self.workspace()?.downgrade();
16248        renderer.open_blame_commit(blame_entry, repo, workspace, window, cx);
16249        None
16250    }
16251
16252    pub fn git_blame_inline_enabled(&self) -> bool {
16253        self.git_blame_inline_enabled
16254    }
16255
16256    pub fn toggle_selection_menu(
16257        &mut self,
16258        _: &ToggleSelectionMenu,
16259        _: &mut Window,
16260        cx: &mut Context<Self>,
16261    ) {
16262        self.show_selection_menu = self
16263            .show_selection_menu
16264            .map(|show_selections_menu| !show_selections_menu)
16265            .or_else(|| Some(!EditorSettings::get_global(cx).toolbar.selections_menu));
16266
16267        cx.notify();
16268    }
16269
16270    pub fn selection_menu_enabled(&self, cx: &App) -> bool {
16271        self.show_selection_menu
16272            .unwrap_or_else(|| EditorSettings::get_global(cx).toolbar.selections_menu)
16273    }
16274
16275    fn start_git_blame(
16276        &mut self,
16277        user_triggered: bool,
16278        window: &mut Window,
16279        cx: &mut Context<Self>,
16280    ) {
16281        if let Some(project) = self.project.as_ref() {
16282            let Some(buffer) = self.buffer().read(cx).as_singleton() else {
16283                return;
16284            };
16285
16286            if buffer.read(cx).file().is_none() {
16287                return;
16288            }
16289
16290            let focused = self.focus_handle(cx).contains_focused(window, cx);
16291
16292            let project = project.clone();
16293            let blame = cx.new(|cx| GitBlame::new(buffer, project, user_triggered, focused, cx));
16294            self.blame_subscription =
16295                Some(cx.observe_in(&blame, window, |_, _, _, cx| cx.notify()));
16296            self.blame = Some(blame);
16297        }
16298    }
16299
16300    fn toggle_git_blame_inline_internal(
16301        &mut self,
16302        user_triggered: bool,
16303        window: &mut Window,
16304        cx: &mut Context<Self>,
16305    ) {
16306        if self.git_blame_inline_enabled {
16307            self.git_blame_inline_enabled = false;
16308            self.show_git_blame_inline = false;
16309            self.show_git_blame_inline_delay_task.take();
16310        } else {
16311            self.git_blame_inline_enabled = true;
16312            self.start_git_blame_inline(user_triggered, window, cx);
16313        }
16314
16315        cx.notify();
16316    }
16317
16318    fn start_git_blame_inline(
16319        &mut self,
16320        user_triggered: bool,
16321        window: &mut Window,
16322        cx: &mut Context<Self>,
16323    ) {
16324        self.start_git_blame(user_triggered, window, cx);
16325
16326        if ProjectSettings::get_global(cx)
16327            .git
16328            .inline_blame_delay()
16329            .is_some()
16330        {
16331            self.start_inline_blame_timer(window, cx);
16332        } else {
16333            self.show_git_blame_inline = true
16334        }
16335    }
16336
16337    pub fn blame(&self) -> Option<&Entity<GitBlame>> {
16338        self.blame.as_ref()
16339    }
16340
16341    pub fn show_git_blame_gutter(&self) -> bool {
16342        self.show_git_blame_gutter
16343    }
16344
16345    pub fn render_git_blame_gutter(&self, cx: &App) -> bool {
16346        self.show_git_blame_gutter && self.has_blame_entries(cx)
16347    }
16348
16349    pub fn render_git_blame_inline(&self, window: &Window, cx: &App) -> bool {
16350        self.show_git_blame_inline
16351            && (self.focus_handle.is_focused(window)
16352                || self
16353                    .git_blame_inline_tooltip
16354                    .as_ref()
16355                    .and_then(|t| t.upgrade())
16356                    .is_some())
16357            && !self.newest_selection_head_on_empty_line(cx)
16358            && self.has_blame_entries(cx)
16359    }
16360
16361    fn has_blame_entries(&self, cx: &App) -> bool {
16362        self.blame()
16363            .map_or(false, |blame| blame.read(cx).has_generated_entries())
16364    }
16365
16366    fn newest_selection_head_on_empty_line(&self, cx: &App) -> bool {
16367        let cursor_anchor = self.selections.newest_anchor().head();
16368
16369        let snapshot = self.buffer.read(cx).snapshot(cx);
16370        let buffer_row = MultiBufferRow(cursor_anchor.to_point(&snapshot).row);
16371
16372        snapshot.line_len(buffer_row) == 0
16373    }
16374
16375    fn get_permalink_to_line(&self, cx: &mut Context<Self>) -> Task<Result<url::Url>> {
16376        let buffer_and_selection = maybe!({
16377            let selection = self.selections.newest::<Point>(cx);
16378            let selection_range = selection.range();
16379
16380            let multi_buffer = self.buffer().read(cx);
16381            let multi_buffer_snapshot = multi_buffer.snapshot(cx);
16382            let buffer_ranges = multi_buffer_snapshot.range_to_buffer_ranges(selection_range);
16383
16384            let (buffer, range, _) = if selection.reversed {
16385                buffer_ranges.first()
16386            } else {
16387                buffer_ranges.last()
16388            }?;
16389
16390            let selection = text::ToPoint::to_point(&range.start, &buffer).row
16391                ..text::ToPoint::to_point(&range.end, &buffer).row;
16392            Some((
16393                multi_buffer.buffer(buffer.remote_id()).unwrap().clone(),
16394                selection,
16395            ))
16396        });
16397
16398        let Some((buffer, selection)) = buffer_and_selection else {
16399            return Task::ready(Err(anyhow!("failed to determine buffer and selection")));
16400        };
16401
16402        let Some(project) = self.project.as_ref() else {
16403            return Task::ready(Err(anyhow!("editor does not have project")));
16404        };
16405
16406        project.update(cx, |project, cx| {
16407            project.get_permalink_to_line(&buffer, selection, cx)
16408        })
16409    }
16410
16411    pub fn copy_permalink_to_line(
16412        &mut self,
16413        _: &CopyPermalinkToLine,
16414        window: &mut Window,
16415        cx: &mut Context<Self>,
16416    ) {
16417        let permalink_task = self.get_permalink_to_line(cx);
16418        let workspace = self.workspace();
16419
16420        cx.spawn_in(window, async move |_, cx| match permalink_task.await {
16421            Ok(permalink) => {
16422                cx.update(|_, cx| {
16423                    cx.write_to_clipboard(ClipboardItem::new_string(permalink.to_string()));
16424                })
16425                .ok();
16426            }
16427            Err(err) => {
16428                let message = format!("Failed to copy permalink: {err}");
16429
16430                Err::<(), anyhow::Error>(err).log_err();
16431
16432                if let Some(workspace) = workspace {
16433                    workspace
16434                        .update_in(cx, |workspace, _, cx| {
16435                            struct CopyPermalinkToLine;
16436
16437                            workspace.show_toast(
16438                                Toast::new(
16439                                    NotificationId::unique::<CopyPermalinkToLine>(),
16440                                    message,
16441                                ),
16442                                cx,
16443                            )
16444                        })
16445                        .ok();
16446                }
16447            }
16448        })
16449        .detach();
16450    }
16451
16452    pub fn copy_file_location(
16453        &mut self,
16454        _: &CopyFileLocation,
16455        _: &mut Window,
16456        cx: &mut Context<Self>,
16457    ) {
16458        let selection = self.selections.newest::<Point>(cx).start.row + 1;
16459        if let Some(file) = self.target_file(cx) {
16460            if let Some(path) = file.path().to_str() {
16461                cx.write_to_clipboard(ClipboardItem::new_string(format!("{path}:{selection}")));
16462            }
16463        }
16464    }
16465
16466    pub fn open_permalink_to_line(
16467        &mut self,
16468        _: &OpenPermalinkToLine,
16469        window: &mut Window,
16470        cx: &mut Context<Self>,
16471    ) {
16472        let permalink_task = self.get_permalink_to_line(cx);
16473        let workspace = self.workspace();
16474
16475        cx.spawn_in(window, async move |_, cx| match permalink_task.await {
16476            Ok(permalink) => {
16477                cx.update(|_, cx| {
16478                    cx.open_url(permalink.as_ref());
16479                })
16480                .ok();
16481            }
16482            Err(err) => {
16483                let message = format!("Failed to open permalink: {err}");
16484
16485                Err::<(), anyhow::Error>(err).log_err();
16486
16487                if let Some(workspace) = workspace {
16488                    workspace
16489                        .update(cx, |workspace, cx| {
16490                            struct OpenPermalinkToLine;
16491
16492                            workspace.show_toast(
16493                                Toast::new(
16494                                    NotificationId::unique::<OpenPermalinkToLine>(),
16495                                    message,
16496                                ),
16497                                cx,
16498                            )
16499                        })
16500                        .ok();
16501                }
16502            }
16503        })
16504        .detach();
16505    }
16506
16507    pub fn insert_uuid_v4(
16508        &mut self,
16509        _: &InsertUuidV4,
16510        window: &mut Window,
16511        cx: &mut Context<Self>,
16512    ) {
16513        self.insert_uuid(UuidVersion::V4, window, cx);
16514    }
16515
16516    pub fn insert_uuid_v7(
16517        &mut self,
16518        _: &InsertUuidV7,
16519        window: &mut Window,
16520        cx: &mut Context<Self>,
16521    ) {
16522        self.insert_uuid(UuidVersion::V7, window, cx);
16523    }
16524
16525    fn insert_uuid(&mut self, version: UuidVersion, window: &mut Window, cx: &mut Context<Self>) {
16526        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
16527        self.transact(window, cx, |this, window, cx| {
16528            let edits = this
16529                .selections
16530                .all::<Point>(cx)
16531                .into_iter()
16532                .map(|selection| {
16533                    let uuid = match version {
16534                        UuidVersion::V4 => uuid::Uuid::new_v4(),
16535                        UuidVersion::V7 => uuid::Uuid::now_v7(),
16536                    };
16537
16538                    (selection.range(), uuid.to_string())
16539                });
16540            this.edit(edits, cx);
16541            this.refresh_inline_completion(true, false, window, cx);
16542        });
16543    }
16544
16545    pub fn open_selections_in_multibuffer(
16546        &mut self,
16547        _: &OpenSelectionsInMultibuffer,
16548        window: &mut Window,
16549        cx: &mut Context<Self>,
16550    ) {
16551        let multibuffer = self.buffer.read(cx);
16552
16553        let Some(buffer) = multibuffer.as_singleton() else {
16554            return;
16555        };
16556
16557        let Some(workspace) = self.workspace() else {
16558            return;
16559        };
16560
16561        let locations = self
16562            .selections
16563            .disjoint_anchors()
16564            .iter()
16565            .map(|range| Location {
16566                buffer: buffer.clone(),
16567                range: range.start.text_anchor..range.end.text_anchor,
16568            })
16569            .collect::<Vec<_>>();
16570
16571        let title = multibuffer.title(cx).to_string();
16572
16573        cx.spawn_in(window, async move |_, cx| {
16574            workspace.update_in(cx, |workspace, window, cx| {
16575                Self::open_locations_in_multibuffer(
16576                    workspace,
16577                    locations,
16578                    format!("Selections for '{title}'"),
16579                    false,
16580                    MultibufferSelectionMode::All,
16581                    window,
16582                    cx,
16583                );
16584            })
16585        })
16586        .detach();
16587    }
16588
16589    /// Adds a row highlight for the given range. If a row has multiple highlights, the
16590    /// last highlight added will be used.
16591    ///
16592    /// If the range ends at the beginning of a line, then that line will not be highlighted.
16593    pub fn highlight_rows<T: 'static>(
16594        &mut self,
16595        range: Range<Anchor>,
16596        color: Hsla,
16597        should_autoscroll: bool,
16598        cx: &mut Context<Self>,
16599    ) {
16600        let snapshot = self.buffer().read(cx).snapshot(cx);
16601        let row_highlights = self.highlighted_rows.entry(TypeId::of::<T>()).or_default();
16602        let ix = row_highlights.binary_search_by(|highlight| {
16603            Ordering::Equal
16604                .then_with(|| highlight.range.start.cmp(&range.start, &snapshot))
16605                .then_with(|| highlight.range.end.cmp(&range.end, &snapshot))
16606        });
16607
16608        if let Err(mut ix) = ix {
16609            let index = post_inc(&mut self.highlight_order);
16610
16611            // If this range intersects with the preceding highlight, then merge it with
16612            // the preceding highlight. Otherwise insert a new highlight.
16613            let mut merged = false;
16614            if ix > 0 {
16615                let prev_highlight = &mut row_highlights[ix - 1];
16616                if prev_highlight
16617                    .range
16618                    .end
16619                    .cmp(&range.start, &snapshot)
16620                    .is_ge()
16621                {
16622                    ix -= 1;
16623                    if prev_highlight.range.end.cmp(&range.end, &snapshot).is_lt() {
16624                        prev_highlight.range.end = range.end;
16625                    }
16626                    merged = true;
16627                    prev_highlight.index = index;
16628                    prev_highlight.color = color;
16629                    prev_highlight.should_autoscroll = should_autoscroll;
16630                }
16631            }
16632
16633            if !merged {
16634                row_highlights.insert(
16635                    ix,
16636                    RowHighlight {
16637                        range: range.clone(),
16638                        index,
16639                        color,
16640                        should_autoscroll,
16641                    },
16642                );
16643            }
16644
16645            // If any of the following highlights intersect with this one, merge them.
16646            while let Some(next_highlight) = row_highlights.get(ix + 1) {
16647                let highlight = &row_highlights[ix];
16648                if next_highlight
16649                    .range
16650                    .start
16651                    .cmp(&highlight.range.end, &snapshot)
16652                    .is_le()
16653                {
16654                    if next_highlight
16655                        .range
16656                        .end
16657                        .cmp(&highlight.range.end, &snapshot)
16658                        .is_gt()
16659                    {
16660                        row_highlights[ix].range.end = next_highlight.range.end;
16661                    }
16662                    row_highlights.remove(ix + 1);
16663                } else {
16664                    break;
16665                }
16666            }
16667        }
16668    }
16669
16670    /// Remove any highlighted row ranges of the given type that intersect the
16671    /// given ranges.
16672    pub fn remove_highlighted_rows<T: 'static>(
16673        &mut self,
16674        ranges_to_remove: Vec<Range<Anchor>>,
16675        cx: &mut Context<Self>,
16676    ) {
16677        let snapshot = self.buffer().read(cx).snapshot(cx);
16678        let row_highlights = self.highlighted_rows.entry(TypeId::of::<T>()).or_default();
16679        let mut ranges_to_remove = ranges_to_remove.iter().peekable();
16680        row_highlights.retain(|highlight| {
16681            while let Some(range_to_remove) = ranges_to_remove.peek() {
16682                match range_to_remove.end.cmp(&highlight.range.start, &snapshot) {
16683                    Ordering::Less | Ordering::Equal => {
16684                        ranges_to_remove.next();
16685                    }
16686                    Ordering::Greater => {
16687                        match range_to_remove.start.cmp(&highlight.range.end, &snapshot) {
16688                            Ordering::Less | Ordering::Equal => {
16689                                return false;
16690                            }
16691                            Ordering::Greater => break,
16692                        }
16693                    }
16694                }
16695            }
16696
16697            true
16698        })
16699    }
16700
16701    /// Clear all anchor ranges for a certain highlight context type, so no corresponding rows will be highlighted.
16702    pub fn clear_row_highlights<T: 'static>(&mut self) {
16703        self.highlighted_rows.remove(&TypeId::of::<T>());
16704    }
16705
16706    /// For a highlight given context type, gets all anchor ranges that will be used for row highlighting.
16707    pub fn highlighted_rows<T: 'static>(&self) -> impl '_ + Iterator<Item = (Range<Anchor>, Hsla)> {
16708        self.highlighted_rows
16709            .get(&TypeId::of::<T>())
16710            .map_or(&[] as &[_], |vec| vec.as_slice())
16711            .iter()
16712            .map(|highlight| (highlight.range.clone(), highlight.color))
16713    }
16714
16715    /// Merges all anchor ranges for all context types ever set, picking the last highlight added in case of a row conflict.
16716    /// Returns a map of display rows that are highlighted and their corresponding highlight color.
16717    /// Allows to ignore certain kinds of highlights.
16718    pub fn highlighted_display_rows(
16719        &self,
16720        window: &mut Window,
16721        cx: &mut App,
16722    ) -> BTreeMap<DisplayRow, LineHighlight> {
16723        let snapshot = self.snapshot(window, cx);
16724        let mut used_highlight_orders = HashMap::default();
16725        self.highlighted_rows
16726            .iter()
16727            .flat_map(|(_, highlighted_rows)| highlighted_rows.iter())
16728            .fold(
16729                BTreeMap::<DisplayRow, LineHighlight>::new(),
16730                |mut unique_rows, highlight| {
16731                    let start = highlight.range.start.to_display_point(&snapshot);
16732                    let end = highlight.range.end.to_display_point(&snapshot);
16733                    let start_row = start.row().0;
16734                    let end_row = if highlight.range.end.text_anchor != text::Anchor::MAX
16735                        && end.column() == 0
16736                    {
16737                        end.row().0.saturating_sub(1)
16738                    } else {
16739                        end.row().0
16740                    };
16741                    for row in start_row..=end_row {
16742                        let used_index =
16743                            used_highlight_orders.entry(row).or_insert(highlight.index);
16744                        if highlight.index >= *used_index {
16745                            *used_index = highlight.index;
16746                            unique_rows.insert(DisplayRow(row), highlight.color.into());
16747                        }
16748                    }
16749                    unique_rows
16750                },
16751            )
16752    }
16753
16754    pub fn highlighted_display_row_for_autoscroll(
16755        &self,
16756        snapshot: &DisplaySnapshot,
16757    ) -> Option<DisplayRow> {
16758        self.highlighted_rows
16759            .values()
16760            .flat_map(|highlighted_rows| highlighted_rows.iter())
16761            .filter_map(|highlight| {
16762                if highlight.should_autoscroll {
16763                    Some(highlight.range.start.to_display_point(snapshot).row())
16764                } else {
16765                    None
16766                }
16767            })
16768            .min()
16769    }
16770
16771    pub fn set_search_within_ranges(&mut self, ranges: &[Range<Anchor>], cx: &mut Context<Self>) {
16772        self.highlight_background::<SearchWithinRange>(
16773            ranges,
16774            |colors| colors.editor_document_highlight_read_background,
16775            cx,
16776        )
16777    }
16778
16779    pub fn set_breadcrumb_header(&mut self, new_header: String) {
16780        self.breadcrumb_header = Some(new_header);
16781    }
16782
16783    pub fn clear_search_within_ranges(&mut self, cx: &mut Context<Self>) {
16784        self.clear_background_highlights::<SearchWithinRange>(cx);
16785    }
16786
16787    pub fn highlight_background<T: 'static>(
16788        &mut self,
16789        ranges: &[Range<Anchor>],
16790        color_fetcher: fn(&ThemeColors) -> Hsla,
16791        cx: &mut Context<Self>,
16792    ) {
16793        self.background_highlights
16794            .insert(TypeId::of::<T>(), (color_fetcher, Arc::from(ranges)));
16795        self.scrollbar_marker_state.dirty = true;
16796        cx.notify();
16797    }
16798
16799    pub fn clear_background_highlights<T: 'static>(
16800        &mut self,
16801        cx: &mut Context<Self>,
16802    ) -> Option<BackgroundHighlight> {
16803        let text_highlights = self.background_highlights.remove(&TypeId::of::<T>())?;
16804        if !text_highlights.1.is_empty() {
16805            self.scrollbar_marker_state.dirty = true;
16806            cx.notify();
16807        }
16808        Some(text_highlights)
16809    }
16810
16811    pub fn highlight_gutter<T: 'static>(
16812        &mut self,
16813        ranges: &[Range<Anchor>],
16814        color_fetcher: fn(&App) -> Hsla,
16815        cx: &mut Context<Self>,
16816    ) {
16817        self.gutter_highlights
16818            .insert(TypeId::of::<T>(), (color_fetcher, Arc::from(ranges)));
16819        cx.notify();
16820    }
16821
16822    pub fn clear_gutter_highlights<T: 'static>(
16823        &mut self,
16824        cx: &mut Context<Self>,
16825    ) -> Option<GutterHighlight> {
16826        cx.notify();
16827        self.gutter_highlights.remove(&TypeId::of::<T>())
16828    }
16829
16830    #[cfg(feature = "test-support")]
16831    pub fn all_text_background_highlights(
16832        &self,
16833        window: &mut Window,
16834        cx: &mut Context<Self>,
16835    ) -> Vec<(Range<DisplayPoint>, Hsla)> {
16836        let snapshot = self.snapshot(window, cx);
16837        let buffer = &snapshot.buffer_snapshot;
16838        let start = buffer.anchor_before(0);
16839        let end = buffer.anchor_after(buffer.len());
16840        let theme = cx.theme().colors();
16841        self.background_highlights_in_range(start..end, &snapshot, theme)
16842    }
16843
16844    #[cfg(feature = "test-support")]
16845    pub fn search_background_highlights(&mut self, cx: &mut Context<Self>) -> Vec<Range<Point>> {
16846        let snapshot = self.buffer().read(cx).snapshot(cx);
16847
16848        let highlights = self
16849            .background_highlights
16850            .get(&TypeId::of::<items::BufferSearchHighlights>());
16851
16852        if let Some((_color, ranges)) = highlights {
16853            ranges
16854                .iter()
16855                .map(|range| range.start.to_point(&snapshot)..range.end.to_point(&snapshot))
16856                .collect_vec()
16857        } else {
16858            vec![]
16859        }
16860    }
16861
16862    fn document_highlights_for_position<'a>(
16863        &'a self,
16864        position: Anchor,
16865        buffer: &'a MultiBufferSnapshot,
16866    ) -> impl 'a + Iterator<Item = &'a Range<Anchor>> {
16867        let read_highlights = self
16868            .background_highlights
16869            .get(&TypeId::of::<DocumentHighlightRead>())
16870            .map(|h| &h.1);
16871        let write_highlights = self
16872            .background_highlights
16873            .get(&TypeId::of::<DocumentHighlightWrite>())
16874            .map(|h| &h.1);
16875        let left_position = position.bias_left(buffer);
16876        let right_position = position.bias_right(buffer);
16877        read_highlights
16878            .into_iter()
16879            .chain(write_highlights)
16880            .flat_map(move |ranges| {
16881                let start_ix = match ranges.binary_search_by(|probe| {
16882                    let cmp = probe.end.cmp(&left_position, buffer);
16883                    if cmp.is_ge() {
16884                        Ordering::Greater
16885                    } else {
16886                        Ordering::Less
16887                    }
16888                }) {
16889                    Ok(i) | Err(i) => i,
16890                };
16891
16892                ranges[start_ix..]
16893                    .iter()
16894                    .take_while(move |range| range.start.cmp(&right_position, buffer).is_le())
16895            })
16896    }
16897
16898    pub fn has_background_highlights<T: 'static>(&self) -> bool {
16899        self.background_highlights
16900            .get(&TypeId::of::<T>())
16901            .map_or(false, |(_, highlights)| !highlights.is_empty())
16902    }
16903
16904    pub fn background_highlights_in_range(
16905        &self,
16906        search_range: Range<Anchor>,
16907        display_snapshot: &DisplaySnapshot,
16908        theme: &ThemeColors,
16909    ) -> Vec<(Range<DisplayPoint>, Hsla)> {
16910        let mut results = Vec::new();
16911        for (color_fetcher, ranges) in self.background_highlights.values() {
16912            let color = color_fetcher(theme);
16913            let start_ix = match ranges.binary_search_by(|probe| {
16914                let cmp = probe
16915                    .end
16916                    .cmp(&search_range.start, &display_snapshot.buffer_snapshot);
16917                if cmp.is_gt() {
16918                    Ordering::Greater
16919                } else {
16920                    Ordering::Less
16921                }
16922            }) {
16923                Ok(i) | Err(i) => i,
16924            };
16925            for range in &ranges[start_ix..] {
16926                if range
16927                    .start
16928                    .cmp(&search_range.end, &display_snapshot.buffer_snapshot)
16929                    .is_ge()
16930                {
16931                    break;
16932                }
16933
16934                let start = range.start.to_display_point(display_snapshot);
16935                let end = range.end.to_display_point(display_snapshot);
16936                results.push((start..end, color))
16937            }
16938        }
16939        results
16940    }
16941
16942    pub fn background_highlight_row_ranges<T: 'static>(
16943        &self,
16944        search_range: Range<Anchor>,
16945        display_snapshot: &DisplaySnapshot,
16946        count: usize,
16947    ) -> Vec<RangeInclusive<DisplayPoint>> {
16948        let mut results = Vec::new();
16949        let Some((_, ranges)) = self.background_highlights.get(&TypeId::of::<T>()) else {
16950            return vec![];
16951        };
16952
16953        let start_ix = match ranges.binary_search_by(|probe| {
16954            let cmp = probe
16955                .end
16956                .cmp(&search_range.start, &display_snapshot.buffer_snapshot);
16957            if cmp.is_gt() {
16958                Ordering::Greater
16959            } else {
16960                Ordering::Less
16961            }
16962        }) {
16963            Ok(i) | Err(i) => i,
16964        };
16965        let mut push_region = |start: Option<Point>, end: Option<Point>| {
16966            if let (Some(start_display), Some(end_display)) = (start, end) {
16967                results.push(
16968                    start_display.to_display_point(display_snapshot)
16969                        ..=end_display.to_display_point(display_snapshot),
16970                );
16971            }
16972        };
16973        let mut start_row: Option<Point> = None;
16974        let mut end_row: Option<Point> = None;
16975        if ranges.len() > count {
16976            return Vec::new();
16977        }
16978        for range in &ranges[start_ix..] {
16979            if range
16980                .start
16981                .cmp(&search_range.end, &display_snapshot.buffer_snapshot)
16982                .is_ge()
16983            {
16984                break;
16985            }
16986            let end = range.end.to_point(&display_snapshot.buffer_snapshot);
16987            if let Some(current_row) = &end_row {
16988                if end.row == current_row.row {
16989                    continue;
16990                }
16991            }
16992            let start = range.start.to_point(&display_snapshot.buffer_snapshot);
16993            if start_row.is_none() {
16994                assert_eq!(end_row, None);
16995                start_row = Some(start);
16996                end_row = Some(end);
16997                continue;
16998            }
16999            if let Some(current_end) = end_row.as_mut() {
17000                if start.row > current_end.row + 1 {
17001                    push_region(start_row, end_row);
17002                    start_row = Some(start);
17003                    end_row = Some(end);
17004                } else {
17005                    // Merge two hunks.
17006                    *current_end = end;
17007                }
17008            } else {
17009                unreachable!();
17010            }
17011        }
17012        // We might still have a hunk that was not rendered (if there was a search hit on the last line)
17013        push_region(start_row, end_row);
17014        results
17015    }
17016
17017    pub fn gutter_highlights_in_range(
17018        &self,
17019        search_range: Range<Anchor>,
17020        display_snapshot: &DisplaySnapshot,
17021        cx: &App,
17022    ) -> Vec<(Range<DisplayPoint>, Hsla)> {
17023        let mut results = Vec::new();
17024        for (color_fetcher, ranges) in self.gutter_highlights.values() {
17025            let color = color_fetcher(cx);
17026            let start_ix = match ranges.binary_search_by(|probe| {
17027                let cmp = probe
17028                    .end
17029                    .cmp(&search_range.start, &display_snapshot.buffer_snapshot);
17030                if cmp.is_gt() {
17031                    Ordering::Greater
17032                } else {
17033                    Ordering::Less
17034                }
17035            }) {
17036                Ok(i) | Err(i) => i,
17037            };
17038            for range in &ranges[start_ix..] {
17039                if range
17040                    .start
17041                    .cmp(&search_range.end, &display_snapshot.buffer_snapshot)
17042                    .is_ge()
17043                {
17044                    break;
17045                }
17046
17047                let start = range.start.to_display_point(display_snapshot);
17048                let end = range.end.to_display_point(display_snapshot);
17049                results.push((start..end, color))
17050            }
17051        }
17052        results
17053    }
17054
17055    /// Get the text ranges corresponding to the redaction query
17056    pub fn redacted_ranges(
17057        &self,
17058        search_range: Range<Anchor>,
17059        display_snapshot: &DisplaySnapshot,
17060        cx: &App,
17061    ) -> Vec<Range<DisplayPoint>> {
17062        display_snapshot
17063            .buffer_snapshot
17064            .redacted_ranges(search_range, |file| {
17065                if let Some(file) = file {
17066                    file.is_private()
17067                        && EditorSettings::get(
17068                            Some(SettingsLocation {
17069                                worktree_id: file.worktree_id(cx),
17070                                path: file.path().as_ref(),
17071                            }),
17072                            cx,
17073                        )
17074                        .redact_private_values
17075                } else {
17076                    false
17077                }
17078            })
17079            .map(|range| {
17080                range.start.to_display_point(display_snapshot)
17081                    ..range.end.to_display_point(display_snapshot)
17082            })
17083            .collect()
17084    }
17085
17086    pub fn highlight_text<T: 'static>(
17087        &mut self,
17088        ranges: Vec<Range<Anchor>>,
17089        style: HighlightStyle,
17090        cx: &mut Context<Self>,
17091    ) {
17092        self.display_map.update(cx, |map, _| {
17093            map.highlight_text(TypeId::of::<T>(), ranges, style)
17094        });
17095        cx.notify();
17096    }
17097
17098    pub(crate) fn highlight_inlays<T: 'static>(
17099        &mut self,
17100        highlights: Vec<InlayHighlight>,
17101        style: HighlightStyle,
17102        cx: &mut Context<Self>,
17103    ) {
17104        self.display_map.update(cx, |map, _| {
17105            map.highlight_inlays(TypeId::of::<T>(), highlights, style)
17106        });
17107        cx.notify();
17108    }
17109
17110    pub fn text_highlights<'a, T: 'static>(
17111        &'a self,
17112        cx: &'a App,
17113    ) -> Option<(HighlightStyle, &'a [Range<Anchor>])> {
17114        self.display_map.read(cx).text_highlights(TypeId::of::<T>())
17115    }
17116
17117    pub fn clear_highlights<T: 'static>(&mut self, cx: &mut Context<Self>) {
17118        let cleared = self
17119            .display_map
17120            .update(cx, |map, _| map.clear_highlights(TypeId::of::<T>()));
17121        if cleared {
17122            cx.notify();
17123        }
17124    }
17125
17126    pub fn show_local_cursors(&self, window: &mut Window, cx: &mut App) -> bool {
17127        (self.read_only(cx) || self.blink_manager.read(cx).visible())
17128            && self.focus_handle.is_focused(window)
17129    }
17130
17131    pub fn set_show_cursor_when_unfocused(&mut self, is_enabled: bool, cx: &mut Context<Self>) {
17132        self.show_cursor_when_unfocused = is_enabled;
17133        cx.notify();
17134    }
17135
17136    fn on_buffer_changed(&mut self, _: Entity<MultiBuffer>, cx: &mut Context<Self>) {
17137        cx.notify();
17138    }
17139
17140    fn on_buffer_event(
17141        &mut self,
17142        multibuffer: &Entity<MultiBuffer>,
17143        event: &multi_buffer::Event,
17144        window: &mut Window,
17145        cx: &mut Context<Self>,
17146    ) {
17147        match event {
17148            multi_buffer::Event::Edited {
17149                singleton_buffer_edited,
17150                edited_buffer: buffer_edited,
17151            } => {
17152                self.scrollbar_marker_state.dirty = true;
17153                self.active_indent_guides_state.dirty = true;
17154                self.refresh_active_diagnostics(cx);
17155                self.refresh_code_actions(window, cx);
17156                if self.has_active_inline_completion() {
17157                    self.update_visible_inline_completion(window, cx);
17158                }
17159                if let Some(buffer) = buffer_edited {
17160                    let buffer_id = buffer.read(cx).remote_id();
17161                    if !self.registered_buffers.contains_key(&buffer_id) {
17162                        if let Some(project) = self.project.as_ref() {
17163                            project.update(cx, |project, cx| {
17164                                self.registered_buffers.insert(
17165                                    buffer_id,
17166                                    project.register_buffer_with_language_servers(&buffer, cx),
17167                                );
17168                            })
17169                        }
17170                    }
17171                }
17172                cx.emit(EditorEvent::BufferEdited);
17173                cx.emit(SearchEvent::MatchesInvalidated);
17174                if *singleton_buffer_edited {
17175                    if let Some(project) = &self.project {
17176                        #[allow(clippy::mutable_key_type)]
17177                        let languages_affected = multibuffer.update(cx, |multibuffer, cx| {
17178                            multibuffer
17179                                .all_buffers()
17180                                .into_iter()
17181                                .filter_map(|buffer| {
17182                                    buffer.update(cx, |buffer, cx| {
17183                                        let language = buffer.language()?;
17184                                        let should_discard = project.update(cx, |project, cx| {
17185                                            project.is_local()
17186                                                && !project.has_language_servers_for(buffer, cx)
17187                                        });
17188                                        should_discard.not().then_some(language.clone())
17189                                    })
17190                                })
17191                                .collect::<HashSet<_>>()
17192                        });
17193                        if !languages_affected.is_empty() {
17194                            self.refresh_inlay_hints(
17195                                InlayHintRefreshReason::BufferEdited(languages_affected),
17196                                cx,
17197                            );
17198                        }
17199                    }
17200                }
17201
17202                let Some(project) = &self.project else { return };
17203                let (telemetry, is_via_ssh) = {
17204                    let project = project.read(cx);
17205                    let telemetry = project.client().telemetry().clone();
17206                    let is_via_ssh = project.is_via_ssh();
17207                    (telemetry, is_via_ssh)
17208                };
17209                refresh_linked_ranges(self, window, cx);
17210                telemetry.log_edit_event("editor", is_via_ssh);
17211            }
17212            multi_buffer::Event::ExcerptsAdded {
17213                buffer,
17214                predecessor,
17215                excerpts,
17216            } => {
17217                self.tasks_update_task = Some(self.refresh_runnables(window, cx));
17218                let buffer_id = buffer.read(cx).remote_id();
17219                if self.buffer.read(cx).diff_for(buffer_id).is_none() {
17220                    if let Some(project) = &self.project {
17221                        get_uncommitted_diff_for_buffer(
17222                            project,
17223                            [buffer.clone()],
17224                            self.buffer.clone(),
17225                            cx,
17226                        )
17227                        .detach();
17228                    }
17229                }
17230                cx.emit(EditorEvent::ExcerptsAdded {
17231                    buffer: buffer.clone(),
17232                    predecessor: *predecessor,
17233                    excerpts: excerpts.clone(),
17234                });
17235                self.refresh_inlay_hints(InlayHintRefreshReason::NewLinesShown, cx);
17236            }
17237            multi_buffer::Event::ExcerptsRemoved { ids } => {
17238                self.refresh_inlay_hints(InlayHintRefreshReason::ExcerptsRemoved(ids.clone()), cx);
17239                let buffer = self.buffer.read(cx);
17240                self.registered_buffers
17241                    .retain(|buffer_id, _| buffer.buffer(*buffer_id).is_some());
17242                jsx_tag_auto_close::refresh_enabled_in_any_buffer(self, multibuffer, cx);
17243                cx.emit(EditorEvent::ExcerptsRemoved { ids: ids.clone() })
17244            }
17245            multi_buffer::Event::ExcerptsEdited {
17246                excerpt_ids,
17247                buffer_ids,
17248            } => {
17249                self.display_map.update(cx, |map, cx| {
17250                    map.unfold_buffers(buffer_ids.iter().copied(), cx)
17251                });
17252                cx.emit(EditorEvent::ExcerptsEdited {
17253                    ids: excerpt_ids.clone(),
17254                })
17255            }
17256            multi_buffer::Event::ExcerptsExpanded { ids } => {
17257                self.refresh_inlay_hints(InlayHintRefreshReason::NewLinesShown, cx);
17258                cx.emit(EditorEvent::ExcerptsExpanded { ids: ids.clone() })
17259            }
17260            multi_buffer::Event::Reparsed(buffer_id) => {
17261                self.tasks_update_task = Some(self.refresh_runnables(window, cx));
17262                jsx_tag_auto_close::refresh_enabled_in_any_buffer(self, multibuffer, cx);
17263
17264                cx.emit(EditorEvent::Reparsed(*buffer_id));
17265            }
17266            multi_buffer::Event::DiffHunksToggled => {
17267                self.tasks_update_task = Some(self.refresh_runnables(window, cx));
17268            }
17269            multi_buffer::Event::LanguageChanged(buffer_id) => {
17270                linked_editing_ranges::refresh_linked_ranges(self, window, cx);
17271                jsx_tag_auto_close::refresh_enabled_in_any_buffer(self, multibuffer, cx);
17272                cx.emit(EditorEvent::Reparsed(*buffer_id));
17273                cx.notify();
17274            }
17275            multi_buffer::Event::DirtyChanged => cx.emit(EditorEvent::DirtyChanged),
17276            multi_buffer::Event::Saved => cx.emit(EditorEvent::Saved),
17277            multi_buffer::Event::FileHandleChanged
17278            | multi_buffer::Event::Reloaded
17279            | multi_buffer::Event::BufferDiffChanged => cx.emit(EditorEvent::TitleChanged),
17280            multi_buffer::Event::Closed => cx.emit(EditorEvent::Closed),
17281            multi_buffer::Event::DiagnosticsUpdated => {
17282                self.refresh_active_diagnostics(cx);
17283                self.refresh_inline_diagnostics(true, window, cx);
17284                self.scrollbar_marker_state.dirty = true;
17285                cx.notify();
17286            }
17287            _ => {}
17288        };
17289    }
17290
17291    fn on_display_map_changed(
17292        &mut self,
17293        _: Entity<DisplayMap>,
17294        _: &mut Window,
17295        cx: &mut Context<Self>,
17296    ) {
17297        cx.notify();
17298    }
17299
17300    fn settings_changed(&mut self, window: &mut Window, cx: &mut Context<Self>) {
17301        self.tasks_update_task = Some(self.refresh_runnables(window, cx));
17302        self.update_edit_prediction_settings(cx);
17303        self.refresh_inline_completion(true, false, window, cx);
17304        self.refresh_inlay_hints(
17305            InlayHintRefreshReason::SettingsChange(inlay_hint_settings(
17306                self.selections.newest_anchor().head(),
17307                &self.buffer.read(cx).snapshot(cx),
17308                cx,
17309            )),
17310            cx,
17311        );
17312
17313        let old_cursor_shape = self.cursor_shape;
17314
17315        {
17316            let editor_settings = EditorSettings::get_global(cx);
17317            self.scroll_manager.vertical_scroll_margin = editor_settings.vertical_scroll_margin;
17318            self.show_breadcrumbs = editor_settings.toolbar.breadcrumbs;
17319            self.cursor_shape = editor_settings.cursor_shape.unwrap_or_default();
17320            self.hide_mouse_mode = editor_settings.hide_mouse.unwrap_or_default();
17321        }
17322
17323        if old_cursor_shape != self.cursor_shape {
17324            cx.emit(EditorEvent::CursorShapeChanged);
17325        }
17326
17327        let project_settings = ProjectSettings::get_global(cx);
17328        self.serialize_dirty_buffers = project_settings.session.restore_unsaved_buffers;
17329
17330        if self.mode.is_full() {
17331            let show_inline_diagnostics = project_settings.diagnostics.inline.enabled;
17332            let inline_blame_enabled = project_settings.git.inline_blame_enabled();
17333            if self.show_inline_diagnostics != show_inline_diagnostics {
17334                self.show_inline_diagnostics = show_inline_diagnostics;
17335                self.refresh_inline_diagnostics(false, window, cx);
17336            }
17337
17338            if self.git_blame_inline_enabled != inline_blame_enabled {
17339                self.toggle_git_blame_inline_internal(false, window, cx);
17340            }
17341        }
17342
17343        cx.notify();
17344    }
17345
17346    pub fn set_searchable(&mut self, searchable: bool) {
17347        self.searchable = searchable;
17348    }
17349
17350    pub fn searchable(&self) -> bool {
17351        self.searchable
17352    }
17353
17354    fn open_proposed_changes_editor(
17355        &mut self,
17356        _: &OpenProposedChangesEditor,
17357        window: &mut Window,
17358        cx: &mut Context<Self>,
17359    ) {
17360        let Some(workspace) = self.workspace() else {
17361            cx.propagate();
17362            return;
17363        };
17364
17365        let selections = self.selections.all::<usize>(cx);
17366        let multi_buffer = self.buffer.read(cx);
17367        let multi_buffer_snapshot = multi_buffer.snapshot(cx);
17368        let mut new_selections_by_buffer = HashMap::default();
17369        for selection in selections {
17370            for (buffer, range, _) in
17371                multi_buffer_snapshot.range_to_buffer_ranges(selection.start..selection.end)
17372            {
17373                let mut range = range.to_point(buffer);
17374                range.start.column = 0;
17375                range.end.column = buffer.line_len(range.end.row);
17376                new_selections_by_buffer
17377                    .entry(multi_buffer.buffer(buffer.remote_id()).unwrap())
17378                    .or_insert(Vec::new())
17379                    .push(range)
17380            }
17381        }
17382
17383        let proposed_changes_buffers = new_selections_by_buffer
17384            .into_iter()
17385            .map(|(buffer, ranges)| ProposedChangeLocation { buffer, ranges })
17386            .collect::<Vec<_>>();
17387        let proposed_changes_editor = cx.new(|cx| {
17388            ProposedChangesEditor::new(
17389                "Proposed changes",
17390                proposed_changes_buffers,
17391                self.project.clone(),
17392                window,
17393                cx,
17394            )
17395        });
17396
17397        window.defer(cx, move |window, cx| {
17398            workspace.update(cx, |workspace, cx| {
17399                workspace.active_pane().update(cx, |pane, cx| {
17400                    pane.add_item(
17401                        Box::new(proposed_changes_editor),
17402                        true,
17403                        true,
17404                        None,
17405                        window,
17406                        cx,
17407                    );
17408                });
17409            });
17410        });
17411    }
17412
17413    pub fn open_excerpts_in_split(
17414        &mut self,
17415        _: &OpenExcerptsSplit,
17416        window: &mut Window,
17417        cx: &mut Context<Self>,
17418    ) {
17419        self.open_excerpts_common(None, true, window, cx)
17420    }
17421
17422    pub fn open_excerpts(&mut self, _: &OpenExcerpts, window: &mut Window, cx: &mut Context<Self>) {
17423        self.open_excerpts_common(None, false, window, cx)
17424    }
17425
17426    fn open_excerpts_common(
17427        &mut self,
17428        jump_data: Option<JumpData>,
17429        split: bool,
17430        window: &mut Window,
17431        cx: &mut Context<Self>,
17432    ) {
17433        let Some(workspace) = self.workspace() else {
17434            cx.propagate();
17435            return;
17436        };
17437
17438        if self.buffer.read(cx).is_singleton() {
17439            cx.propagate();
17440            return;
17441        }
17442
17443        let mut new_selections_by_buffer = HashMap::default();
17444        match &jump_data {
17445            Some(JumpData::MultiBufferPoint {
17446                excerpt_id,
17447                position,
17448                anchor,
17449                line_offset_from_top,
17450            }) => {
17451                let multi_buffer_snapshot = self.buffer.read(cx).snapshot(cx);
17452                if let Some(buffer) = multi_buffer_snapshot
17453                    .buffer_id_for_excerpt(*excerpt_id)
17454                    .and_then(|buffer_id| self.buffer.read(cx).buffer(buffer_id))
17455                {
17456                    let buffer_snapshot = buffer.read(cx).snapshot();
17457                    let jump_to_point = if buffer_snapshot.can_resolve(anchor) {
17458                        language::ToPoint::to_point(anchor, &buffer_snapshot)
17459                    } else {
17460                        buffer_snapshot.clip_point(*position, Bias::Left)
17461                    };
17462                    let jump_to_offset = buffer_snapshot.point_to_offset(jump_to_point);
17463                    new_selections_by_buffer.insert(
17464                        buffer,
17465                        (
17466                            vec![jump_to_offset..jump_to_offset],
17467                            Some(*line_offset_from_top),
17468                        ),
17469                    );
17470                }
17471            }
17472            Some(JumpData::MultiBufferRow {
17473                row,
17474                line_offset_from_top,
17475            }) => {
17476                let point = MultiBufferPoint::new(row.0, 0);
17477                if let Some((buffer, buffer_point, _)) =
17478                    self.buffer.read(cx).point_to_buffer_point(point, cx)
17479                {
17480                    let buffer_offset = buffer.read(cx).point_to_offset(buffer_point);
17481                    new_selections_by_buffer
17482                        .entry(buffer)
17483                        .or_insert((Vec::new(), Some(*line_offset_from_top)))
17484                        .0
17485                        .push(buffer_offset..buffer_offset)
17486                }
17487            }
17488            None => {
17489                let selections = self.selections.all::<usize>(cx);
17490                let multi_buffer = self.buffer.read(cx);
17491                for selection in selections {
17492                    for (snapshot, range, _, anchor) in multi_buffer
17493                        .snapshot(cx)
17494                        .range_to_buffer_ranges_with_deleted_hunks(selection.range())
17495                    {
17496                        if let Some(anchor) = anchor {
17497                            // selection is in a deleted hunk
17498                            let Some(buffer_id) = anchor.buffer_id else {
17499                                continue;
17500                            };
17501                            let Some(buffer_handle) = multi_buffer.buffer(buffer_id) else {
17502                                continue;
17503                            };
17504                            let offset = text::ToOffset::to_offset(
17505                                &anchor.text_anchor,
17506                                &buffer_handle.read(cx).snapshot(),
17507                            );
17508                            let range = offset..offset;
17509                            new_selections_by_buffer
17510                                .entry(buffer_handle)
17511                                .or_insert((Vec::new(), None))
17512                                .0
17513                                .push(range)
17514                        } else {
17515                            let Some(buffer_handle) = multi_buffer.buffer(snapshot.remote_id())
17516                            else {
17517                                continue;
17518                            };
17519                            new_selections_by_buffer
17520                                .entry(buffer_handle)
17521                                .or_insert((Vec::new(), None))
17522                                .0
17523                                .push(range)
17524                        }
17525                    }
17526                }
17527            }
17528        }
17529
17530        new_selections_by_buffer
17531            .retain(|buffer, _| Self::can_open_excerpts_in_file(buffer.read(cx).file()));
17532
17533        if new_selections_by_buffer.is_empty() {
17534            return;
17535        }
17536
17537        // We defer the pane interaction because we ourselves are a workspace item
17538        // and activating a new item causes the pane to call a method on us reentrantly,
17539        // which panics if we're on the stack.
17540        window.defer(cx, move |window, cx| {
17541            workspace.update(cx, |workspace, cx| {
17542                let pane = if split {
17543                    workspace.adjacent_pane(window, cx)
17544                } else {
17545                    workspace.active_pane().clone()
17546                };
17547
17548                for (buffer, (ranges, scroll_offset)) in new_selections_by_buffer {
17549                    let editor = buffer
17550                        .read(cx)
17551                        .file()
17552                        .is_none()
17553                        .then(|| {
17554                            // Handle file-less buffers separately: those are not really the project items, so won't have a project path or entity id,
17555                            // so `workspace.open_project_item` will never find them, always opening a new editor.
17556                            // Instead, we try to activate the existing editor in the pane first.
17557                            let (editor, pane_item_index) =
17558                                pane.read(cx).items().enumerate().find_map(|(i, item)| {
17559                                    let editor = item.downcast::<Editor>()?;
17560                                    let singleton_buffer =
17561                                        editor.read(cx).buffer().read(cx).as_singleton()?;
17562                                    if singleton_buffer == buffer {
17563                                        Some((editor, i))
17564                                    } else {
17565                                        None
17566                                    }
17567                                })?;
17568                            pane.update(cx, |pane, cx| {
17569                                pane.activate_item(pane_item_index, true, true, window, cx)
17570                            });
17571                            Some(editor)
17572                        })
17573                        .flatten()
17574                        .unwrap_or_else(|| {
17575                            workspace.open_project_item::<Self>(
17576                                pane.clone(),
17577                                buffer,
17578                                true,
17579                                true,
17580                                window,
17581                                cx,
17582                            )
17583                        });
17584
17585                    editor.update(cx, |editor, cx| {
17586                        let autoscroll = match scroll_offset {
17587                            Some(scroll_offset) => Autoscroll::top_relative(scroll_offset as usize),
17588                            None => Autoscroll::newest(),
17589                        };
17590                        let nav_history = editor.nav_history.take();
17591                        editor.change_selections(Some(autoscroll), window, cx, |s| {
17592                            s.select_ranges(ranges);
17593                        });
17594                        editor.nav_history = nav_history;
17595                    });
17596                }
17597            })
17598        });
17599    }
17600
17601    // For now, don't allow opening excerpts in buffers that aren't backed by
17602    // regular project files.
17603    fn can_open_excerpts_in_file(file: Option<&Arc<dyn language::File>>) -> bool {
17604        file.map_or(true, |file| project::File::from_dyn(Some(file)).is_some())
17605    }
17606
17607    fn marked_text_ranges(&self, cx: &App) -> Option<Vec<Range<OffsetUtf16>>> {
17608        let snapshot = self.buffer.read(cx).read(cx);
17609        let (_, ranges) = self.text_highlights::<InputComposition>(cx)?;
17610        Some(
17611            ranges
17612                .iter()
17613                .map(move |range| {
17614                    range.start.to_offset_utf16(&snapshot)..range.end.to_offset_utf16(&snapshot)
17615                })
17616                .collect(),
17617        )
17618    }
17619
17620    fn selection_replacement_ranges(
17621        &self,
17622        range: Range<OffsetUtf16>,
17623        cx: &mut App,
17624    ) -> Vec<Range<OffsetUtf16>> {
17625        let selections = self.selections.all::<OffsetUtf16>(cx);
17626        let newest_selection = selections
17627            .iter()
17628            .max_by_key(|selection| selection.id)
17629            .unwrap();
17630        let start_delta = range.start.0 as isize - newest_selection.start.0 as isize;
17631        let end_delta = range.end.0 as isize - newest_selection.end.0 as isize;
17632        let snapshot = self.buffer.read(cx).read(cx);
17633        selections
17634            .into_iter()
17635            .map(|mut selection| {
17636                selection.start.0 =
17637                    (selection.start.0 as isize).saturating_add(start_delta) as usize;
17638                selection.end.0 = (selection.end.0 as isize).saturating_add(end_delta) as usize;
17639                snapshot.clip_offset_utf16(selection.start, Bias::Left)
17640                    ..snapshot.clip_offset_utf16(selection.end, Bias::Right)
17641            })
17642            .collect()
17643    }
17644
17645    fn report_editor_event(
17646        &self,
17647        event_type: &'static str,
17648        file_extension: Option<String>,
17649        cx: &App,
17650    ) {
17651        if cfg!(any(test, feature = "test-support")) {
17652            return;
17653        }
17654
17655        let Some(project) = &self.project else { return };
17656
17657        // If None, we are in a file without an extension
17658        let file = self
17659            .buffer
17660            .read(cx)
17661            .as_singleton()
17662            .and_then(|b| b.read(cx).file());
17663        let file_extension = file_extension.or(file
17664            .as_ref()
17665            .and_then(|file| Path::new(file.file_name(cx)).extension())
17666            .and_then(|e| e.to_str())
17667            .map(|a| a.to_string()));
17668
17669        let vim_mode = cx
17670            .global::<SettingsStore>()
17671            .raw_user_settings()
17672            .get("vim_mode")
17673            == Some(&serde_json::Value::Bool(true));
17674
17675        let edit_predictions_provider = all_language_settings(file, cx).edit_predictions.provider;
17676        let copilot_enabled = edit_predictions_provider
17677            == language::language_settings::EditPredictionProvider::Copilot;
17678        let copilot_enabled_for_language = self
17679            .buffer
17680            .read(cx)
17681            .language_settings(cx)
17682            .show_edit_predictions;
17683
17684        let project = project.read(cx);
17685        telemetry::event!(
17686            event_type,
17687            file_extension,
17688            vim_mode,
17689            copilot_enabled,
17690            copilot_enabled_for_language,
17691            edit_predictions_provider,
17692            is_via_ssh = project.is_via_ssh(),
17693        );
17694    }
17695
17696    /// Copy the highlighted chunks to the clipboard as JSON. The format is an array of lines,
17697    /// with each line being an array of {text, highlight} objects.
17698    fn copy_highlight_json(
17699        &mut self,
17700        _: &CopyHighlightJson,
17701        window: &mut Window,
17702        cx: &mut Context<Self>,
17703    ) {
17704        #[derive(Serialize)]
17705        struct Chunk<'a> {
17706            text: String,
17707            highlight: Option<&'a str>,
17708        }
17709
17710        let snapshot = self.buffer.read(cx).snapshot(cx);
17711        let range = self
17712            .selected_text_range(false, window, cx)
17713            .and_then(|selection| {
17714                if selection.range.is_empty() {
17715                    None
17716                } else {
17717                    Some(selection.range)
17718                }
17719            })
17720            .unwrap_or_else(|| 0..snapshot.len());
17721
17722        let chunks = snapshot.chunks(range, true);
17723        let mut lines = Vec::new();
17724        let mut line: VecDeque<Chunk> = VecDeque::new();
17725
17726        let Some(style) = self.style.as_ref() else {
17727            return;
17728        };
17729
17730        for chunk in chunks {
17731            let highlight = chunk
17732                .syntax_highlight_id
17733                .and_then(|id| id.name(&style.syntax));
17734            let mut chunk_lines = chunk.text.split('\n').peekable();
17735            while let Some(text) = chunk_lines.next() {
17736                let mut merged_with_last_token = false;
17737                if let Some(last_token) = line.back_mut() {
17738                    if last_token.highlight == highlight {
17739                        last_token.text.push_str(text);
17740                        merged_with_last_token = true;
17741                    }
17742                }
17743
17744                if !merged_with_last_token {
17745                    line.push_back(Chunk {
17746                        text: text.into(),
17747                        highlight,
17748                    });
17749                }
17750
17751                if chunk_lines.peek().is_some() {
17752                    if line.len() > 1 && line.front().unwrap().text.is_empty() {
17753                        line.pop_front();
17754                    }
17755                    if line.len() > 1 && line.back().unwrap().text.is_empty() {
17756                        line.pop_back();
17757                    }
17758
17759                    lines.push(mem::take(&mut line));
17760                }
17761            }
17762        }
17763
17764        let Some(lines) = serde_json::to_string_pretty(&lines).log_err() else {
17765            return;
17766        };
17767        cx.write_to_clipboard(ClipboardItem::new_string(lines));
17768    }
17769
17770    pub fn open_context_menu(
17771        &mut self,
17772        _: &OpenContextMenu,
17773        window: &mut Window,
17774        cx: &mut Context<Self>,
17775    ) {
17776        self.request_autoscroll(Autoscroll::newest(), cx);
17777        let position = self.selections.newest_display(cx).start;
17778        mouse_context_menu::deploy_context_menu(self, None, position, window, cx);
17779    }
17780
17781    pub fn inlay_hint_cache(&self) -> &InlayHintCache {
17782        &self.inlay_hint_cache
17783    }
17784
17785    pub fn replay_insert_event(
17786        &mut self,
17787        text: &str,
17788        relative_utf16_range: Option<Range<isize>>,
17789        window: &mut Window,
17790        cx: &mut Context<Self>,
17791    ) {
17792        if !self.input_enabled {
17793            cx.emit(EditorEvent::InputIgnored { text: text.into() });
17794            return;
17795        }
17796        if let Some(relative_utf16_range) = relative_utf16_range {
17797            let selections = self.selections.all::<OffsetUtf16>(cx);
17798            self.change_selections(None, window, cx, |s| {
17799                let new_ranges = selections.into_iter().map(|range| {
17800                    let start = OffsetUtf16(
17801                        range
17802                            .head()
17803                            .0
17804                            .saturating_add_signed(relative_utf16_range.start),
17805                    );
17806                    let end = OffsetUtf16(
17807                        range
17808                            .head()
17809                            .0
17810                            .saturating_add_signed(relative_utf16_range.end),
17811                    );
17812                    start..end
17813                });
17814                s.select_ranges(new_ranges);
17815            });
17816        }
17817
17818        self.handle_input(text, window, cx);
17819    }
17820
17821    pub fn supports_inlay_hints(&self, cx: &mut App) -> bool {
17822        let Some(provider) = self.semantics_provider.as_ref() else {
17823            return false;
17824        };
17825
17826        let mut supports = false;
17827        self.buffer().update(cx, |this, cx| {
17828            this.for_each_buffer(|buffer| {
17829                supports |= provider.supports_inlay_hints(buffer, cx);
17830            });
17831        });
17832
17833        supports
17834    }
17835
17836    pub fn is_focused(&self, window: &Window) -> bool {
17837        self.focus_handle.is_focused(window)
17838    }
17839
17840    fn handle_focus(&mut self, window: &mut Window, cx: &mut Context<Self>) {
17841        cx.emit(EditorEvent::Focused);
17842
17843        if let Some(descendant) = self
17844            .last_focused_descendant
17845            .take()
17846            .and_then(|descendant| descendant.upgrade())
17847        {
17848            window.focus(&descendant);
17849        } else {
17850            if let Some(blame) = self.blame.as_ref() {
17851                blame.update(cx, GitBlame::focus)
17852            }
17853
17854            self.blink_manager.update(cx, BlinkManager::enable);
17855            self.show_cursor_names(window, cx);
17856            self.buffer.update(cx, |buffer, cx| {
17857                buffer.finalize_last_transaction(cx);
17858                if self.leader_peer_id.is_none() {
17859                    buffer.set_active_selections(
17860                        &self.selections.disjoint_anchors(),
17861                        self.selections.line_mode,
17862                        self.cursor_shape,
17863                        cx,
17864                    );
17865                }
17866            });
17867        }
17868    }
17869
17870    fn handle_focus_in(&mut self, _: &mut Window, cx: &mut Context<Self>) {
17871        cx.emit(EditorEvent::FocusedIn)
17872    }
17873
17874    fn handle_focus_out(
17875        &mut self,
17876        event: FocusOutEvent,
17877        _window: &mut Window,
17878        cx: &mut Context<Self>,
17879    ) {
17880        if event.blurred != self.focus_handle {
17881            self.last_focused_descendant = Some(event.blurred);
17882        }
17883        self.refresh_inlay_hints(InlayHintRefreshReason::ModifiersChanged(false), cx);
17884    }
17885
17886    pub fn handle_blur(&mut self, window: &mut Window, cx: &mut Context<Self>) {
17887        self.blink_manager.update(cx, BlinkManager::disable);
17888        self.buffer
17889            .update(cx, |buffer, cx| buffer.remove_active_selections(cx));
17890
17891        if let Some(blame) = self.blame.as_ref() {
17892            blame.update(cx, GitBlame::blur)
17893        }
17894        if !self.hover_state.focused(window, cx) {
17895            hide_hover(self, cx);
17896        }
17897        if !self
17898            .context_menu
17899            .borrow()
17900            .as_ref()
17901            .is_some_and(|context_menu| context_menu.focused(window, cx))
17902        {
17903            self.hide_context_menu(window, cx);
17904        }
17905        self.discard_inline_completion(false, cx);
17906        cx.emit(EditorEvent::Blurred);
17907        cx.notify();
17908    }
17909
17910    pub fn register_action<A: Action>(
17911        &mut self,
17912        listener: impl Fn(&A, &mut Window, &mut App) + 'static,
17913    ) -> Subscription {
17914        let id = self.next_editor_action_id.post_inc();
17915        let listener = Arc::new(listener);
17916        self.editor_actions.borrow_mut().insert(
17917            id,
17918            Box::new(move |window, _| {
17919                let listener = listener.clone();
17920                window.on_action(TypeId::of::<A>(), move |action, phase, window, cx| {
17921                    let action = action.downcast_ref().unwrap();
17922                    if phase == DispatchPhase::Bubble {
17923                        listener(action, window, cx)
17924                    }
17925                })
17926            }),
17927        );
17928
17929        let editor_actions = self.editor_actions.clone();
17930        Subscription::new(move || {
17931            editor_actions.borrow_mut().remove(&id);
17932        })
17933    }
17934
17935    pub fn file_header_size(&self) -> u32 {
17936        FILE_HEADER_HEIGHT
17937    }
17938
17939    pub fn restore(
17940        &mut self,
17941        revert_changes: HashMap<BufferId, Vec<(Range<text::Anchor>, Rope)>>,
17942        window: &mut Window,
17943        cx: &mut Context<Self>,
17944    ) {
17945        let workspace = self.workspace();
17946        let project = self.project.as_ref();
17947        let save_tasks = self.buffer().update(cx, |multi_buffer, cx| {
17948            let mut tasks = Vec::new();
17949            for (buffer_id, changes) in revert_changes {
17950                if let Some(buffer) = multi_buffer.buffer(buffer_id) {
17951                    buffer.update(cx, |buffer, cx| {
17952                        buffer.edit(
17953                            changes
17954                                .into_iter()
17955                                .map(|(range, text)| (range, text.to_string())),
17956                            None,
17957                            cx,
17958                        );
17959                    });
17960
17961                    if let Some(project) =
17962                        project.filter(|_| multi_buffer.all_diff_hunks_expanded())
17963                    {
17964                        project.update(cx, |project, cx| {
17965                            tasks.push((buffer.clone(), project.save_buffer(buffer, cx)));
17966                        })
17967                    }
17968                }
17969            }
17970            tasks
17971        });
17972        cx.spawn_in(window, async move |_, cx| {
17973            for (buffer, task) in save_tasks {
17974                let result = task.await;
17975                if result.is_err() {
17976                    let Some(path) = buffer
17977                        .read_with(cx, |buffer, cx| buffer.project_path(cx))
17978                        .ok()
17979                    else {
17980                        continue;
17981                    };
17982                    if let Some((workspace, path)) = workspace.as_ref().zip(path) {
17983                        let Some(task) = cx
17984                            .update_window_entity(&workspace, |workspace, window, cx| {
17985                                workspace
17986                                    .open_path_preview(path, None, false, false, false, window, cx)
17987                            })
17988                            .ok()
17989                        else {
17990                            continue;
17991                        };
17992                        task.await.log_err();
17993                    }
17994                }
17995            }
17996        })
17997        .detach();
17998        self.change_selections(None, window, cx, |selections| selections.refresh());
17999    }
18000
18001    pub fn to_pixel_point(
18002        &self,
18003        source: multi_buffer::Anchor,
18004        editor_snapshot: &EditorSnapshot,
18005        window: &mut Window,
18006    ) -> Option<gpui::Point<Pixels>> {
18007        let source_point = source.to_display_point(editor_snapshot);
18008        self.display_to_pixel_point(source_point, editor_snapshot, window)
18009    }
18010
18011    pub fn display_to_pixel_point(
18012        &self,
18013        source: DisplayPoint,
18014        editor_snapshot: &EditorSnapshot,
18015        window: &mut Window,
18016    ) -> Option<gpui::Point<Pixels>> {
18017        let line_height = self.style()?.text.line_height_in_pixels(window.rem_size());
18018        let text_layout_details = self.text_layout_details(window);
18019        let scroll_top = text_layout_details
18020            .scroll_anchor
18021            .scroll_position(editor_snapshot)
18022            .y;
18023
18024        if source.row().as_f32() < scroll_top.floor() {
18025            return None;
18026        }
18027        let source_x = editor_snapshot.x_for_display_point(source, &text_layout_details);
18028        let source_y = line_height * (source.row().as_f32() - scroll_top);
18029        Some(gpui::Point::new(source_x, source_y))
18030    }
18031
18032    pub fn has_visible_completions_menu(&self) -> bool {
18033        !self.edit_prediction_preview_is_active()
18034            && self.context_menu.borrow().as_ref().map_or(false, |menu| {
18035                menu.visible() && matches!(menu, CodeContextMenu::Completions(_))
18036            })
18037    }
18038
18039    pub fn register_addon<T: Addon>(&mut self, instance: T) {
18040        self.addons
18041            .insert(std::any::TypeId::of::<T>(), Box::new(instance));
18042    }
18043
18044    pub fn unregister_addon<T: Addon>(&mut self) {
18045        self.addons.remove(&std::any::TypeId::of::<T>());
18046    }
18047
18048    pub fn addon<T: Addon>(&self) -> Option<&T> {
18049        let type_id = std::any::TypeId::of::<T>();
18050        self.addons
18051            .get(&type_id)
18052            .and_then(|item| item.to_any().downcast_ref::<T>())
18053    }
18054
18055    fn character_size(&self, window: &mut Window) -> gpui::Size<Pixels> {
18056        let text_layout_details = self.text_layout_details(window);
18057        let style = &text_layout_details.editor_style;
18058        let font_id = window.text_system().resolve_font(&style.text.font());
18059        let font_size = style.text.font_size.to_pixels(window.rem_size());
18060        let line_height = style.text.line_height_in_pixels(window.rem_size());
18061        let em_width = window.text_system().em_width(font_id, font_size).unwrap();
18062
18063        gpui::Size::new(em_width, line_height)
18064    }
18065
18066    pub fn wait_for_diff_to_load(&self) -> Option<Shared<Task<()>>> {
18067        self.load_diff_task.clone()
18068    }
18069
18070    fn read_metadata_from_db(
18071        &mut self,
18072        item_id: u64,
18073        workspace_id: WorkspaceId,
18074        window: &mut Window,
18075        cx: &mut Context<Editor>,
18076    ) {
18077        if self.is_singleton(cx)
18078            && WorkspaceSettings::get(None, cx).restore_on_startup != RestoreOnStartupBehavior::None
18079        {
18080            let buffer_snapshot = OnceCell::new();
18081
18082            if let Some(folds) = DB.get_editor_folds(item_id, workspace_id).log_err() {
18083                if !folds.is_empty() {
18084                    let snapshot =
18085                        buffer_snapshot.get_or_init(|| self.buffer.read(cx).snapshot(cx));
18086                    self.fold_ranges(
18087                        folds
18088                            .into_iter()
18089                            .map(|(start, end)| {
18090                                snapshot.clip_offset(start, Bias::Left)
18091                                    ..snapshot.clip_offset(end, Bias::Right)
18092                            })
18093                            .collect(),
18094                        false,
18095                        window,
18096                        cx,
18097                    );
18098                }
18099            }
18100
18101            if let Some(selections) = DB.get_editor_selections(item_id, workspace_id).log_err() {
18102                if !selections.is_empty() {
18103                    let snapshot =
18104                        buffer_snapshot.get_or_init(|| self.buffer.read(cx).snapshot(cx));
18105                    self.change_selections(None, window, cx, |s| {
18106                        s.select_ranges(selections.into_iter().map(|(start, end)| {
18107                            snapshot.clip_offset(start, Bias::Left)
18108                                ..snapshot.clip_offset(end, Bias::Right)
18109                        }));
18110                    });
18111                }
18112            };
18113        }
18114
18115        self.read_scroll_position_from_db(item_id, workspace_id, window, cx);
18116    }
18117}
18118
18119// Consider user intent and default settings
18120fn choose_completion_range(
18121    completion: &Completion,
18122    intent: CompletionIntent,
18123    buffer: &Entity<Buffer>,
18124    cx: &mut Context<Editor>,
18125) -> Range<usize> {
18126    fn should_replace(
18127        completion: &Completion,
18128        insert_range: &Range<text::Anchor>,
18129        intent: CompletionIntent,
18130        completion_mode_setting: LspInsertMode,
18131        buffer: &Buffer,
18132    ) -> bool {
18133        // specific actions take precedence over settings
18134        match intent {
18135            CompletionIntent::CompleteWithInsert => return false,
18136            CompletionIntent::CompleteWithReplace => return true,
18137            CompletionIntent::Complete | CompletionIntent::Compose => {}
18138        }
18139
18140        match completion_mode_setting {
18141            LspInsertMode::Insert => false,
18142            LspInsertMode::Replace => true,
18143            LspInsertMode::ReplaceSubsequence => {
18144                let mut text_to_replace = buffer.chars_for_range(
18145                    buffer.anchor_before(completion.replace_range.start)
18146                        ..buffer.anchor_after(completion.replace_range.end),
18147                );
18148                let mut completion_text = completion.new_text.chars();
18149
18150                // is `text_to_replace` a subsequence of `completion_text`
18151                text_to_replace
18152                    .all(|needle_ch| completion_text.any(|haystack_ch| haystack_ch == needle_ch))
18153            }
18154            LspInsertMode::ReplaceSuffix => {
18155                let range_after_cursor = insert_range.end..completion.replace_range.end;
18156
18157                let text_after_cursor = buffer
18158                    .text_for_range(
18159                        buffer.anchor_before(range_after_cursor.start)
18160                            ..buffer.anchor_after(range_after_cursor.end),
18161                    )
18162                    .collect::<String>();
18163                completion.new_text.ends_with(&text_after_cursor)
18164            }
18165        }
18166    }
18167
18168    let buffer = buffer.read(cx);
18169
18170    if let CompletionSource::Lsp {
18171        insert_range: Some(insert_range),
18172        ..
18173    } = &completion.source
18174    {
18175        let completion_mode_setting =
18176            language_settings(buffer.language().map(|l| l.name()), buffer.file(), cx)
18177                .completions
18178                .lsp_insert_mode;
18179
18180        if !should_replace(
18181            completion,
18182            &insert_range,
18183            intent,
18184            completion_mode_setting,
18185            buffer,
18186        ) {
18187            return insert_range.to_offset(buffer);
18188        }
18189    }
18190
18191    completion.replace_range.to_offset(buffer)
18192}
18193
18194fn insert_extra_newline_brackets(
18195    buffer: &MultiBufferSnapshot,
18196    range: Range<usize>,
18197    language: &language::LanguageScope,
18198) -> bool {
18199    let leading_whitespace_len = buffer
18200        .reversed_chars_at(range.start)
18201        .take_while(|c| c.is_whitespace() && *c != '\n')
18202        .map(|c| c.len_utf8())
18203        .sum::<usize>();
18204    let trailing_whitespace_len = buffer
18205        .chars_at(range.end)
18206        .take_while(|c| c.is_whitespace() && *c != '\n')
18207        .map(|c| c.len_utf8())
18208        .sum::<usize>();
18209    let range = range.start - leading_whitespace_len..range.end + trailing_whitespace_len;
18210
18211    language.brackets().any(|(pair, enabled)| {
18212        let pair_start = pair.start.trim_end();
18213        let pair_end = pair.end.trim_start();
18214
18215        enabled
18216            && pair.newline
18217            && buffer.contains_str_at(range.end, pair_end)
18218            && buffer.contains_str_at(range.start.saturating_sub(pair_start.len()), pair_start)
18219    })
18220}
18221
18222fn insert_extra_newline_tree_sitter(buffer: &MultiBufferSnapshot, range: Range<usize>) -> bool {
18223    let (buffer, range) = match buffer.range_to_buffer_ranges(range).as_slice() {
18224        [(buffer, range, _)] => (*buffer, range.clone()),
18225        _ => return false,
18226    };
18227    let pair = {
18228        let mut result: Option<BracketMatch> = None;
18229
18230        for pair in buffer
18231            .all_bracket_ranges(range.clone())
18232            .filter(move |pair| {
18233                pair.open_range.start <= range.start && pair.close_range.end >= range.end
18234            })
18235        {
18236            let len = pair.close_range.end - pair.open_range.start;
18237
18238            if let Some(existing) = &result {
18239                let existing_len = existing.close_range.end - existing.open_range.start;
18240                if len > existing_len {
18241                    continue;
18242                }
18243            }
18244
18245            result = Some(pair);
18246        }
18247
18248        result
18249    };
18250    let Some(pair) = pair else {
18251        return false;
18252    };
18253    pair.newline_only
18254        && buffer
18255            .chars_for_range(pair.open_range.end..range.start)
18256            .chain(buffer.chars_for_range(range.end..pair.close_range.start))
18257            .all(|c| c.is_whitespace() && c != '\n')
18258}
18259
18260fn get_uncommitted_diff_for_buffer(
18261    project: &Entity<Project>,
18262    buffers: impl IntoIterator<Item = Entity<Buffer>>,
18263    buffer: Entity<MultiBuffer>,
18264    cx: &mut App,
18265) -> Task<()> {
18266    let mut tasks = Vec::new();
18267    project.update(cx, |project, cx| {
18268        for buffer in buffers {
18269            if project::File::from_dyn(buffer.read(cx).file()).is_some() {
18270                tasks.push(project.open_uncommitted_diff(buffer.clone(), cx))
18271            }
18272        }
18273    });
18274    cx.spawn(async move |cx| {
18275        let diffs = future::join_all(tasks).await;
18276        buffer
18277            .update(cx, |buffer, cx| {
18278                for diff in diffs.into_iter().flatten() {
18279                    buffer.add_diff(diff, cx);
18280                }
18281            })
18282            .ok();
18283    })
18284}
18285
18286fn char_len_with_expanded_tabs(offset: usize, text: &str, tab_size: NonZeroU32) -> usize {
18287    let tab_size = tab_size.get() as usize;
18288    let mut width = offset;
18289
18290    for ch in text.chars() {
18291        width += if ch == '\t' {
18292            tab_size - (width % tab_size)
18293        } else {
18294            1
18295        };
18296    }
18297
18298    width - offset
18299}
18300
18301#[cfg(test)]
18302mod tests {
18303    use super::*;
18304
18305    #[test]
18306    fn test_string_size_with_expanded_tabs() {
18307        let nz = |val| NonZeroU32::new(val).unwrap();
18308        assert_eq!(char_len_with_expanded_tabs(0, "", nz(4)), 0);
18309        assert_eq!(char_len_with_expanded_tabs(0, "hello", nz(4)), 5);
18310        assert_eq!(char_len_with_expanded_tabs(0, "\thello", nz(4)), 9);
18311        assert_eq!(char_len_with_expanded_tabs(0, "abc\tab", nz(4)), 6);
18312        assert_eq!(char_len_with_expanded_tabs(0, "hello\t", nz(4)), 8);
18313        assert_eq!(char_len_with_expanded_tabs(0, "\t\t", nz(8)), 16);
18314        assert_eq!(char_len_with_expanded_tabs(0, "x\t", nz(8)), 8);
18315        assert_eq!(char_len_with_expanded_tabs(7, "x\t", nz(8)), 9);
18316    }
18317}
18318
18319/// Tokenizes a string into runs of text that should stick together, or that is whitespace.
18320struct WordBreakingTokenizer<'a> {
18321    input: &'a str,
18322}
18323
18324impl<'a> WordBreakingTokenizer<'a> {
18325    fn new(input: &'a str) -> Self {
18326        Self { input }
18327    }
18328}
18329
18330fn is_char_ideographic(ch: char) -> bool {
18331    use unicode_script::Script::*;
18332    use unicode_script::UnicodeScript;
18333    matches!(ch.script(), Han | Tangut | Yi)
18334}
18335
18336fn is_grapheme_ideographic(text: &str) -> bool {
18337    text.chars().any(is_char_ideographic)
18338}
18339
18340fn is_grapheme_whitespace(text: &str) -> bool {
18341    text.chars().any(|x| x.is_whitespace())
18342}
18343
18344fn should_stay_with_preceding_ideograph(text: &str) -> bool {
18345    text.chars().next().map_or(false, |ch| {
18346        matches!(ch, '。' | '、' | ',' | '?' | '!' | ':' | ';' | '…')
18347    })
18348}
18349
18350#[derive(PartialEq, Eq, Debug, Clone, Copy)]
18351enum WordBreakToken<'a> {
18352    Word { token: &'a str, grapheme_len: usize },
18353    InlineWhitespace { token: &'a str, grapheme_len: usize },
18354    Newline,
18355}
18356
18357impl<'a> Iterator for WordBreakingTokenizer<'a> {
18358    /// Yields a span, the count of graphemes in the token, and whether it was
18359    /// whitespace. Note that it also breaks at word boundaries.
18360    type Item = WordBreakToken<'a>;
18361
18362    fn next(&mut self) -> Option<Self::Item> {
18363        use unicode_segmentation::UnicodeSegmentation;
18364        if self.input.is_empty() {
18365            return None;
18366        }
18367
18368        let mut iter = self.input.graphemes(true).peekable();
18369        let mut offset = 0;
18370        let mut grapheme_len = 0;
18371        if let Some(first_grapheme) = iter.next() {
18372            let is_newline = first_grapheme == "\n";
18373            let is_whitespace = is_grapheme_whitespace(first_grapheme);
18374            offset += first_grapheme.len();
18375            grapheme_len += 1;
18376            if is_grapheme_ideographic(first_grapheme) && !is_whitespace {
18377                if let Some(grapheme) = iter.peek().copied() {
18378                    if should_stay_with_preceding_ideograph(grapheme) {
18379                        offset += grapheme.len();
18380                        grapheme_len += 1;
18381                    }
18382                }
18383            } else {
18384                let mut words = self.input[offset..].split_word_bound_indices().peekable();
18385                let mut next_word_bound = words.peek().copied();
18386                if next_word_bound.map_or(false, |(i, _)| i == 0) {
18387                    next_word_bound = words.next();
18388                }
18389                while let Some(grapheme) = iter.peek().copied() {
18390                    if next_word_bound.map_or(false, |(i, _)| i == offset) {
18391                        break;
18392                    };
18393                    if is_grapheme_whitespace(grapheme) != is_whitespace
18394                        || (grapheme == "\n") != is_newline
18395                    {
18396                        break;
18397                    };
18398                    offset += grapheme.len();
18399                    grapheme_len += 1;
18400                    iter.next();
18401                }
18402            }
18403            let token = &self.input[..offset];
18404            self.input = &self.input[offset..];
18405            if token == "\n" {
18406                Some(WordBreakToken::Newline)
18407            } else if is_whitespace {
18408                Some(WordBreakToken::InlineWhitespace {
18409                    token,
18410                    grapheme_len,
18411                })
18412            } else {
18413                Some(WordBreakToken::Word {
18414                    token,
18415                    grapheme_len,
18416                })
18417            }
18418        } else {
18419            None
18420        }
18421    }
18422}
18423
18424#[test]
18425fn test_word_breaking_tokenizer() {
18426    let tests: &[(&str, &[WordBreakToken<'static>])] = &[
18427        ("", &[]),
18428        ("  ", &[whitespace("  ", 2)]),
18429        ("Ʒ", &[word("Ʒ", 1)]),
18430        ("Ǽ", &[word("Ǽ", 1)]),
18431        ("", &[word("", 1)]),
18432        ("⋑⋑", &[word("⋑⋑", 2)]),
18433        (
18434            "原理,进而",
18435            &[word("", 1), word("理,", 2), word("", 1), word("", 1)],
18436        ),
18437        (
18438            "hello world",
18439            &[word("hello", 5), whitespace(" ", 1), word("world", 5)],
18440        ),
18441        (
18442            "hello, world",
18443            &[word("hello,", 6), whitespace(" ", 1), word("world", 5)],
18444        ),
18445        (
18446            "  hello world",
18447            &[
18448                whitespace("  ", 2),
18449                word("hello", 5),
18450                whitespace(" ", 1),
18451                word("world", 5),
18452            ],
18453        ),
18454        (
18455            "这是什么 \n 钢笔",
18456            &[
18457                word("", 1),
18458                word("", 1),
18459                word("", 1),
18460                word("", 1),
18461                whitespace(" ", 1),
18462                newline(),
18463                whitespace(" ", 1),
18464                word("", 1),
18465                word("", 1),
18466            ],
18467        ),
18468        (" mutton", &[whitespace("", 1), word("mutton", 6)]),
18469    ];
18470
18471    fn word(token: &'static str, grapheme_len: usize) -> WordBreakToken<'static> {
18472        WordBreakToken::Word {
18473            token,
18474            grapheme_len,
18475        }
18476    }
18477
18478    fn whitespace(token: &'static str, grapheme_len: usize) -> WordBreakToken<'static> {
18479        WordBreakToken::InlineWhitespace {
18480            token,
18481            grapheme_len,
18482        }
18483    }
18484
18485    fn newline() -> WordBreakToken<'static> {
18486        WordBreakToken::Newline
18487    }
18488
18489    for (input, result) in tests {
18490        assert_eq!(
18491            WordBreakingTokenizer::new(input)
18492                .collect::<Vec<_>>()
18493                .as_slice(),
18494            *result,
18495        );
18496    }
18497}
18498
18499fn wrap_with_prefix(
18500    line_prefix: String,
18501    unwrapped_text: String,
18502    wrap_column: usize,
18503    tab_size: NonZeroU32,
18504    preserve_existing_whitespace: bool,
18505) -> String {
18506    let line_prefix_len = char_len_with_expanded_tabs(0, &line_prefix, tab_size);
18507    let mut wrapped_text = String::new();
18508    let mut current_line = line_prefix.clone();
18509
18510    let tokenizer = WordBreakingTokenizer::new(&unwrapped_text);
18511    let mut current_line_len = line_prefix_len;
18512    let mut in_whitespace = false;
18513    for token in tokenizer {
18514        let have_preceding_whitespace = in_whitespace;
18515        match token {
18516            WordBreakToken::Word {
18517                token,
18518                grapheme_len,
18519            } => {
18520                in_whitespace = false;
18521                if current_line_len + grapheme_len > wrap_column
18522                    && current_line_len != line_prefix_len
18523                {
18524                    wrapped_text.push_str(current_line.trim_end());
18525                    wrapped_text.push('\n');
18526                    current_line.truncate(line_prefix.len());
18527                    current_line_len = line_prefix_len;
18528                }
18529                current_line.push_str(token);
18530                current_line_len += grapheme_len;
18531            }
18532            WordBreakToken::InlineWhitespace {
18533                mut token,
18534                mut grapheme_len,
18535            } => {
18536                in_whitespace = true;
18537                if have_preceding_whitespace && !preserve_existing_whitespace {
18538                    continue;
18539                }
18540                if !preserve_existing_whitespace {
18541                    token = " ";
18542                    grapheme_len = 1;
18543                }
18544                if current_line_len + grapheme_len > wrap_column {
18545                    wrapped_text.push_str(current_line.trim_end());
18546                    wrapped_text.push('\n');
18547                    current_line.truncate(line_prefix.len());
18548                    current_line_len = line_prefix_len;
18549                } else if current_line_len != line_prefix_len || preserve_existing_whitespace {
18550                    current_line.push_str(token);
18551                    current_line_len += grapheme_len;
18552                }
18553            }
18554            WordBreakToken::Newline => {
18555                in_whitespace = true;
18556                if preserve_existing_whitespace {
18557                    wrapped_text.push_str(current_line.trim_end());
18558                    wrapped_text.push('\n');
18559                    current_line.truncate(line_prefix.len());
18560                    current_line_len = line_prefix_len;
18561                } else if have_preceding_whitespace {
18562                    continue;
18563                } else if current_line_len + 1 > wrap_column && current_line_len != line_prefix_len
18564                {
18565                    wrapped_text.push_str(current_line.trim_end());
18566                    wrapped_text.push('\n');
18567                    current_line.truncate(line_prefix.len());
18568                    current_line_len = line_prefix_len;
18569                } else if current_line_len != line_prefix_len {
18570                    current_line.push(' ');
18571                    current_line_len += 1;
18572                }
18573            }
18574        }
18575    }
18576
18577    if !current_line.is_empty() {
18578        wrapped_text.push_str(&current_line);
18579    }
18580    wrapped_text
18581}
18582
18583#[test]
18584fn test_wrap_with_prefix() {
18585    assert_eq!(
18586        wrap_with_prefix(
18587            "# ".to_string(),
18588            "abcdefg".to_string(),
18589            4,
18590            NonZeroU32::new(4).unwrap(),
18591            false,
18592        ),
18593        "# abcdefg"
18594    );
18595    assert_eq!(
18596        wrap_with_prefix(
18597            "".to_string(),
18598            "\thello world".to_string(),
18599            8,
18600            NonZeroU32::new(4).unwrap(),
18601            false,
18602        ),
18603        "hello\nworld"
18604    );
18605    assert_eq!(
18606        wrap_with_prefix(
18607            "// ".to_string(),
18608            "xx \nyy zz aa bb cc".to_string(),
18609            12,
18610            NonZeroU32::new(4).unwrap(),
18611            false,
18612        ),
18613        "// xx yy zz\n// aa bb cc"
18614    );
18615    assert_eq!(
18616        wrap_with_prefix(
18617            String::new(),
18618            "这是什么 \n 钢笔".to_string(),
18619            3,
18620            NonZeroU32::new(4).unwrap(),
18621            false,
18622        ),
18623        "这是什\n么 钢\n"
18624    );
18625}
18626
18627pub trait CollaborationHub {
18628    fn collaborators<'a>(&self, cx: &'a App) -> &'a HashMap<PeerId, Collaborator>;
18629    fn user_participant_indices<'a>(&self, cx: &'a App) -> &'a HashMap<u64, ParticipantIndex>;
18630    fn user_names(&self, cx: &App) -> HashMap<u64, SharedString>;
18631}
18632
18633impl CollaborationHub for Entity<Project> {
18634    fn collaborators<'a>(&self, cx: &'a App) -> &'a HashMap<PeerId, Collaborator> {
18635        self.read(cx).collaborators()
18636    }
18637
18638    fn user_participant_indices<'a>(&self, cx: &'a App) -> &'a HashMap<u64, ParticipantIndex> {
18639        self.read(cx).user_store().read(cx).participant_indices()
18640    }
18641
18642    fn user_names(&self, cx: &App) -> HashMap<u64, SharedString> {
18643        let this = self.read(cx);
18644        let user_ids = this.collaborators().values().map(|c| c.user_id);
18645        this.user_store().read_with(cx, |user_store, cx| {
18646            user_store.participant_names(user_ids, cx)
18647        })
18648    }
18649}
18650
18651pub trait SemanticsProvider {
18652    fn hover(
18653        &self,
18654        buffer: &Entity<Buffer>,
18655        position: text::Anchor,
18656        cx: &mut App,
18657    ) -> Option<Task<Vec<project::Hover>>>;
18658
18659    fn inlay_hints(
18660        &self,
18661        buffer_handle: Entity<Buffer>,
18662        range: Range<text::Anchor>,
18663        cx: &mut App,
18664    ) -> Option<Task<anyhow::Result<Vec<InlayHint>>>>;
18665
18666    fn resolve_inlay_hint(
18667        &self,
18668        hint: InlayHint,
18669        buffer_handle: Entity<Buffer>,
18670        server_id: LanguageServerId,
18671        cx: &mut App,
18672    ) -> Option<Task<anyhow::Result<InlayHint>>>;
18673
18674    fn supports_inlay_hints(&self, buffer: &Entity<Buffer>, cx: &mut App) -> bool;
18675
18676    fn document_highlights(
18677        &self,
18678        buffer: &Entity<Buffer>,
18679        position: text::Anchor,
18680        cx: &mut App,
18681    ) -> Option<Task<Result<Vec<DocumentHighlight>>>>;
18682
18683    fn definitions(
18684        &self,
18685        buffer: &Entity<Buffer>,
18686        position: text::Anchor,
18687        kind: GotoDefinitionKind,
18688        cx: &mut App,
18689    ) -> Option<Task<Result<Vec<LocationLink>>>>;
18690
18691    fn range_for_rename(
18692        &self,
18693        buffer: &Entity<Buffer>,
18694        position: text::Anchor,
18695        cx: &mut App,
18696    ) -> Option<Task<Result<Option<Range<text::Anchor>>>>>;
18697
18698    fn perform_rename(
18699        &self,
18700        buffer: &Entity<Buffer>,
18701        position: text::Anchor,
18702        new_name: String,
18703        cx: &mut App,
18704    ) -> Option<Task<Result<ProjectTransaction>>>;
18705}
18706
18707pub trait CompletionProvider {
18708    fn completions(
18709        &self,
18710        excerpt_id: ExcerptId,
18711        buffer: &Entity<Buffer>,
18712        buffer_position: text::Anchor,
18713        trigger: CompletionContext,
18714        window: &mut Window,
18715        cx: &mut Context<Editor>,
18716    ) -> Task<Result<Option<Vec<Completion>>>>;
18717
18718    fn resolve_completions(
18719        &self,
18720        buffer: Entity<Buffer>,
18721        completion_indices: Vec<usize>,
18722        completions: Rc<RefCell<Box<[Completion]>>>,
18723        cx: &mut Context<Editor>,
18724    ) -> Task<Result<bool>>;
18725
18726    fn apply_additional_edits_for_completion(
18727        &self,
18728        _buffer: Entity<Buffer>,
18729        _completions: Rc<RefCell<Box<[Completion]>>>,
18730        _completion_index: usize,
18731        _push_to_history: bool,
18732        _cx: &mut Context<Editor>,
18733    ) -> Task<Result<Option<language::Transaction>>> {
18734        Task::ready(Ok(None))
18735    }
18736
18737    fn is_completion_trigger(
18738        &self,
18739        buffer: &Entity<Buffer>,
18740        position: language::Anchor,
18741        text: &str,
18742        trigger_in_words: bool,
18743        cx: &mut Context<Editor>,
18744    ) -> bool;
18745
18746    fn sort_completions(&self) -> bool {
18747        true
18748    }
18749
18750    fn filter_completions(&self) -> bool {
18751        true
18752    }
18753}
18754
18755pub trait CodeActionProvider {
18756    fn id(&self) -> Arc<str>;
18757
18758    fn code_actions(
18759        &self,
18760        buffer: &Entity<Buffer>,
18761        range: Range<text::Anchor>,
18762        window: &mut Window,
18763        cx: &mut App,
18764    ) -> Task<Result<Vec<CodeAction>>>;
18765
18766    fn apply_code_action(
18767        &self,
18768        buffer_handle: Entity<Buffer>,
18769        action: CodeAction,
18770        excerpt_id: ExcerptId,
18771        push_to_history: bool,
18772        window: &mut Window,
18773        cx: &mut App,
18774    ) -> Task<Result<ProjectTransaction>>;
18775}
18776
18777impl CodeActionProvider for Entity<Project> {
18778    fn id(&self) -> Arc<str> {
18779        "project".into()
18780    }
18781
18782    fn code_actions(
18783        &self,
18784        buffer: &Entity<Buffer>,
18785        range: Range<text::Anchor>,
18786        _window: &mut Window,
18787        cx: &mut App,
18788    ) -> Task<Result<Vec<CodeAction>>> {
18789        self.update(cx, |project, cx| {
18790            let code_lens = project.code_lens(buffer, range.clone(), cx);
18791            let code_actions = project.code_actions(buffer, range, None, cx);
18792            cx.background_spawn(async move {
18793                let (code_lens, code_actions) = join(code_lens, code_actions).await;
18794                Ok(code_lens
18795                    .context("code lens fetch")?
18796                    .into_iter()
18797                    .chain(code_actions.context("code action fetch")?)
18798                    .collect())
18799            })
18800        })
18801    }
18802
18803    fn apply_code_action(
18804        &self,
18805        buffer_handle: Entity<Buffer>,
18806        action: CodeAction,
18807        _excerpt_id: ExcerptId,
18808        push_to_history: bool,
18809        _window: &mut Window,
18810        cx: &mut App,
18811    ) -> Task<Result<ProjectTransaction>> {
18812        self.update(cx, |project, cx| {
18813            project.apply_code_action(buffer_handle, action, push_to_history, cx)
18814        })
18815    }
18816}
18817
18818fn snippet_completions(
18819    project: &Project,
18820    buffer: &Entity<Buffer>,
18821    buffer_position: text::Anchor,
18822    cx: &mut App,
18823) -> Task<Result<Vec<Completion>>> {
18824    let languages = buffer.read(cx).languages_at(buffer_position);
18825    let snippet_store = project.snippets().read(cx);
18826
18827    let scopes: Vec<_> = languages
18828        .iter()
18829        .filter_map(|language| {
18830            let language_name = language.lsp_id();
18831            let snippets = snippet_store.snippets_for(Some(language_name), cx);
18832
18833            if snippets.is_empty() {
18834                None
18835            } else {
18836                Some((language.default_scope(), snippets))
18837            }
18838        })
18839        .collect();
18840
18841    if scopes.is_empty() {
18842        return Task::ready(Ok(vec![]));
18843    }
18844
18845    let snapshot = buffer.read(cx).text_snapshot();
18846    let chars: String = snapshot
18847        .reversed_chars_for_range(text::Anchor::MIN..buffer_position)
18848        .collect();
18849    let executor = cx.background_executor().clone();
18850
18851    cx.background_spawn(async move {
18852        let mut all_results: Vec<Completion> = Vec::new();
18853        for (scope, snippets) in scopes.into_iter() {
18854            let classifier = CharClassifier::new(Some(scope)).for_completion(true);
18855            let mut last_word = chars
18856                .chars()
18857                .take_while(|c| classifier.is_word(*c))
18858                .collect::<String>();
18859            last_word = last_word.chars().rev().collect();
18860
18861            if last_word.is_empty() {
18862                return Ok(vec![]);
18863            }
18864
18865            let as_offset = text::ToOffset::to_offset(&buffer_position, &snapshot);
18866            let to_lsp = |point: &text::Anchor| {
18867                let end = text::ToPointUtf16::to_point_utf16(point, &snapshot);
18868                point_to_lsp(end)
18869            };
18870            let lsp_end = to_lsp(&buffer_position);
18871
18872            let candidates = snippets
18873                .iter()
18874                .enumerate()
18875                .flat_map(|(ix, snippet)| {
18876                    snippet
18877                        .prefix
18878                        .iter()
18879                        .map(move |prefix| StringMatchCandidate::new(ix, &prefix))
18880                })
18881                .collect::<Vec<StringMatchCandidate>>();
18882
18883            let mut matches = fuzzy::match_strings(
18884                &candidates,
18885                &last_word,
18886                last_word.chars().any(|c| c.is_uppercase()),
18887                100,
18888                &Default::default(),
18889                executor.clone(),
18890            )
18891            .await;
18892
18893            // Remove all candidates where the query's start does not match the start of any word in the candidate
18894            if let Some(query_start) = last_word.chars().next() {
18895                matches.retain(|string_match| {
18896                    split_words(&string_match.string).any(|word| {
18897                        // Check that the first codepoint of the word as lowercase matches the first
18898                        // codepoint of the query as lowercase
18899                        word.chars()
18900                            .flat_map(|codepoint| codepoint.to_lowercase())
18901                            .zip(query_start.to_lowercase())
18902                            .all(|(word_cp, query_cp)| word_cp == query_cp)
18903                    })
18904                });
18905            }
18906
18907            let matched_strings = matches
18908                .into_iter()
18909                .map(|m| m.string)
18910                .collect::<HashSet<_>>();
18911
18912            let mut result: Vec<Completion> = snippets
18913                .iter()
18914                .filter_map(|snippet| {
18915                    let matching_prefix = snippet
18916                        .prefix
18917                        .iter()
18918                        .find(|prefix| matched_strings.contains(*prefix))?;
18919                    let start = as_offset - last_word.len();
18920                    let start = snapshot.anchor_before(start);
18921                    let range = start..buffer_position;
18922                    let lsp_start = to_lsp(&start);
18923                    let lsp_range = lsp::Range {
18924                        start: lsp_start,
18925                        end: lsp_end,
18926                    };
18927                    Some(Completion {
18928                        replace_range: range,
18929                        new_text: snippet.body.clone(),
18930                        source: CompletionSource::Lsp {
18931                            insert_range: None,
18932                            server_id: LanguageServerId(usize::MAX),
18933                            resolved: true,
18934                            lsp_completion: Box::new(lsp::CompletionItem {
18935                                label: snippet.prefix.first().unwrap().clone(),
18936                                kind: Some(CompletionItemKind::SNIPPET),
18937                                label_details: snippet.description.as_ref().map(|description| {
18938                                    lsp::CompletionItemLabelDetails {
18939                                        detail: Some(description.clone()),
18940                                        description: None,
18941                                    }
18942                                }),
18943                                insert_text_format: Some(InsertTextFormat::SNIPPET),
18944                                text_edit: Some(lsp::CompletionTextEdit::InsertAndReplace(
18945                                    lsp::InsertReplaceEdit {
18946                                        new_text: snippet.body.clone(),
18947                                        insert: lsp_range,
18948                                        replace: lsp_range,
18949                                    },
18950                                )),
18951                                filter_text: Some(snippet.body.clone()),
18952                                sort_text: Some(char::MAX.to_string()),
18953                                ..lsp::CompletionItem::default()
18954                            }),
18955                            lsp_defaults: None,
18956                        },
18957                        label: CodeLabel {
18958                            text: matching_prefix.clone(),
18959                            runs: Vec::new(),
18960                            filter_range: 0..matching_prefix.len(),
18961                        },
18962                        icon_path: None,
18963                        documentation: snippet.description.clone().map(|description| {
18964                            CompletionDocumentation::SingleLine(description.into())
18965                        }),
18966                        insert_text_mode: None,
18967                        confirm: None,
18968                    })
18969                })
18970                .collect();
18971
18972            all_results.append(&mut result);
18973        }
18974
18975        Ok(all_results)
18976    })
18977}
18978
18979impl CompletionProvider for Entity<Project> {
18980    fn completions(
18981        &self,
18982        _excerpt_id: ExcerptId,
18983        buffer: &Entity<Buffer>,
18984        buffer_position: text::Anchor,
18985        options: CompletionContext,
18986        _window: &mut Window,
18987        cx: &mut Context<Editor>,
18988    ) -> Task<Result<Option<Vec<Completion>>>> {
18989        self.update(cx, |project, cx| {
18990            let snippets = snippet_completions(project, buffer, buffer_position, cx);
18991            let project_completions = project.completions(buffer, buffer_position, options, cx);
18992            cx.background_spawn(async move {
18993                let snippets_completions = snippets.await?;
18994                match project_completions.await? {
18995                    Some(mut completions) => {
18996                        completions.extend(snippets_completions);
18997                        Ok(Some(completions))
18998                    }
18999                    None => {
19000                        if snippets_completions.is_empty() {
19001                            Ok(None)
19002                        } else {
19003                            Ok(Some(snippets_completions))
19004                        }
19005                    }
19006                }
19007            })
19008        })
19009    }
19010
19011    fn resolve_completions(
19012        &self,
19013        buffer: Entity<Buffer>,
19014        completion_indices: Vec<usize>,
19015        completions: Rc<RefCell<Box<[Completion]>>>,
19016        cx: &mut Context<Editor>,
19017    ) -> Task<Result<bool>> {
19018        self.update(cx, |project, cx| {
19019            project.lsp_store().update(cx, |lsp_store, cx| {
19020                lsp_store.resolve_completions(buffer, completion_indices, completions, cx)
19021            })
19022        })
19023    }
19024
19025    fn apply_additional_edits_for_completion(
19026        &self,
19027        buffer: Entity<Buffer>,
19028        completions: Rc<RefCell<Box<[Completion]>>>,
19029        completion_index: usize,
19030        push_to_history: bool,
19031        cx: &mut Context<Editor>,
19032    ) -> Task<Result<Option<language::Transaction>>> {
19033        self.update(cx, |project, cx| {
19034            project.lsp_store().update(cx, |lsp_store, cx| {
19035                lsp_store.apply_additional_edits_for_completion(
19036                    buffer,
19037                    completions,
19038                    completion_index,
19039                    push_to_history,
19040                    cx,
19041                )
19042            })
19043        })
19044    }
19045
19046    fn is_completion_trigger(
19047        &self,
19048        buffer: &Entity<Buffer>,
19049        position: language::Anchor,
19050        text: &str,
19051        trigger_in_words: bool,
19052        cx: &mut Context<Editor>,
19053    ) -> bool {
19054        let mut chars = text.chars();
19055        let char = if let Some(char) = chars.next() {
19056            char
19057        } else {
19058            return false;
19059        };
19060        if chars.next().is_some() {
19061            return false;
19062        }
19063
19064        let buffer = buffer.read(cx);
19065        let snapshot = buffer.snapshot();
19066        if !snapshot.settings_at(position, cx).show_completions_on_input {
19067            return false;
19068        }
19069        let classifier = snapshot.char_classifier_at(position).for_completion(true);
19070        if trigger_in_words && classifier.is_word(char) {
19071            return true;
19072        }
19073
19074        buffer.completion_triggers().contains(text)
19075    }
19076}
19077
19078impl SemanticsProvider for Entity<Project> {
19079    fn hover(
19080        &self,
19081        buffer: &Entity<Buffer>,
19082        position: text::Anchor,
19083        cx: &mut App,
19084    ) -> Option<Task<Vec<project::Hover>>> {
19085        Some(self.update(cx, |project, cx| project.hover(buffer, position, cx)))
19086    }
19087
19088    fn document_highlights(
19089        &self,
19090        buffer: &Entity<Buffer>,
19091        position: text::Anchor,
19092        cx: &mut App,
19093    ) -> Option<Task<Result<Vec<DocumentHighlight>>>> {
19094        Some(self.update(cx, |project, cx| {
19095            project.document_highlights(buffer, position, cx)
19096        }))
19097    }
19098
19099    fn definitions(
19100        &self,
19101        buffer: &Entity<Buffer>,
19102        position: text::Anchor,
19103        kind: GotoDefinitionKind,
19104        cx: &mut App,
19105    ) -> Option<Task<Result<Vec<LocationLink>>>> {
19106        Some(self.update(cx, |project, cx| match kind {
19107            GotoDefinitionKind::Symbol => project.definition(&buffer, position, cx),
19108            GotoDefinitionKind::Declaration => project.declaration(&buffer, position, cx),
19109            GotoDefinitionKind::Type => project.type_definition(&buffer, position, cx),
19110            GotoDefinitionKind::Implementation => project.implementation(&buffer, position, cx),
19111        }))
19112    }
19113
19114    fn supports_inlay_hints(&self, buffer: &Entity<Buffer>, cx: &mut App) -> bool {
19115        // TODO: make this work for remote projects
19116        self.update(cx, |this, cx| {
19117            buffer.update(cx, |buffer, cx| {
19118                this.any_language_server_supports_inlay_hints(buffer, cx)
19119            })
19120        })
19121    }
19122
19123    fn inlay_hints(
19124        &self,
19125        buffer_handle: Entity<Buffer>,
19126        range: Range<text::Anchor>,
19127        cx: &mut App,
19128    ) -> Option<Task<anyhow::Result<Vec<InlayHint>>>> {
19129        Some(self.update(cx, |project, cx| {
19130            project.inlay_hints(buffer_handle, range, cx)
19131        }))
19132    }
19133
19134    fn resolve_inlay_hint(
19135        &self,
19136        hint: InlayHint,
19137        buffer_handle: Entity<Buffer>,
19138        server_id: LanguageServerId,
19139        cx: &mut App,
19140    ) -> Option<Task<anyhow::Result<InlayHint>>> {
19141        Some(self.update(cx, |project, cx| {
19142            project.resolve_inlay_hint(hint, buffer_handle, server_id, cx)
19143        }))
19144    }
19145
19146    fn range_for_rename(
19147        &self,
19148        buffer: &Entity<Buffer>,
19149        position: text::Anchor,
19150        cx: &mut App,
19151    ) -> Option<Task<Result<Option<Range<text::Anchor>>>>> {
19152        Some(self.update(cx, |project, cx| {
19153            let buffer = buffer.clone();
19154            let task = project.prepare_rename(buffer.clone(), position, cx);
19155            cx.spawn(async move |_, cx| {
19156                Ok(match task.await? {
19157                    PrepareRenameResponse::Success(range) => Some(range),
19158                    PrepareRenameResponse::InvalidPosition => None,
19159                    PrepareRenameResponse::OnlyUnpreparedRenameSupported => {
19160                        // Fallback on using TreeSitter info to determine identifier range
19161                        buffer.update(cx, |buffer, _| {
19162                            let snapshot = buffer.snapshot();
19163                            let (range, kind) = snapshot.surrounding_word(position);
19164                            if kind != Some(CharKind::Word) {
19165                                return None;
19166                            }
19167                            Some(
19168                                snapshot.anchor_before(range.start)
19169                                    ..snapshot.anchor_after(range.end),
19170                            )
19171                        })?
19172                    }
19173                })
19174            })
19175        }))
19176    }
19177
19178    fn perform_rename(
19179        &self,
19180        buffer: &Entity<Buffer>,
19181        position: text::Anchor,
19182        new_name: String,
19183        cx: &mut App,
19184    ) -> Option<Task<Result<ProjectTransaction>>> {
19185        Some(self.update(cx, |project, cx| {
19186            project.perform_rename(buffer.clone(), position, new_name, cx)
19187        }))
19188    }
19189}
19190
19191fn inlay_hint_settings(
19192    location: Anchor,
19193    snapshot: &MultiBufferSnapshot,
19194    cx: &mut Context<Editor>,
19195) -> InlayHintSettings {
19196    let file = snapshot.file_at(location);
19197    let language = snapshot.language_at(location).map(|l| l.name());
19198    language_settings(language, file, cx).inlay_hints
19199}
19200
19201fn consume_contiguous_rows(
19202    contiguous_row_selections: &mut Vec<Selection<Point>>,
19203    selection: &Selection<Point>,
19204    display_map: &DisplaySnapshot,
19205    selections: &mut Peekable<std::slice::Iter<Selection<Point>>>,
19206) -> (MultiBufferRow, MultiBufferRow) {
19207    contiguous_row_selections.push(selection.clone());
19208    let start_row = MultiBufferRow(selection.start.row);
19209    let mut end_row = ending_row(selection, display_map);
19210
19211    while let Some(next_selection) = selections.peek() {
19212        if next_selection.start.row <= end_row.0 {
19213            end_row = ending_row(next_selection, display_map);
19214            contiguous_row_selections.push(selections.next().unwrap().clone());
19215        } else {
19216            break;
19217        }
19218    }
19219    (start_row, end_row)
19220}
19221
19222fn ending_row(next_selection: &Selection<Point>, display_map: &DisplaySnapshot) -> MultiBufferRow {
19223    if next_selection.end.column > 0 || next_selection.is_empty() {
19224        MultiBufferRow(display_map.next_line_boundary(next_selection.end).0.row + 1)
19225    } else {
19226        MultiBufferRow(next_selection.end.row)
19227    }
19228}
19229
19230impl EditorSnapshot {
19231    pub fn remote_selections_in_range<'a>(
19232        &'a self,
19233        range: &'a Range<Anchor>,
19234        collaboration_hub: &dyn CollaborationHub,
19235        cx: &'a App,
19236    ) -> impl 'a + Iterator<Item = RemoteSelection> {
19237        let participant_names = collaboration_hub.user_names(cx);
19238        let participant_indices = collaboration_hub.user_participant_indices(cx);
19239        let collaborators_by_peer_id = collaboration_hub.collaborators(cx);
19240        let collaborators_by_replica_id = collaborators_by_peer_id
19241            .iter()
19242            .map(|(_, collaborator)| (collaborator.replica_id, collaborator))
19243            .collect::<HashMap<_, _>>();
19244        self.buffer_snapshot
19245            .selections_in_range(range, false)
19246            .filter_map(move |(replica_id, line_mode, cursor_shape, selection)| {
19247                let collaborator = collaborators_by_replica_id.get(&replica_id)?;
19248                let participant_index = participant_indices.get(&collaborator.user_id).copied();
19249                let user_name = participant_names.get(&collaborator.user_id).cloned();
19250                Some(RemoteSelection {
19251                    replica_id,
19252                    selection,
19253                    cursor_shape,
19254                    line_mode,
19255                    participant_index,
19256                    peer_id: collaborator.peer_id,
19257                    user_name,
19258                })
19259            })
19260    }
19261
19262    pub fn hunks_for_ranges(
19263        &self,
19264        ranges: impl IntoIterator<Item = Range<Point>>,
19265    ) -> Vec<MultiBufferDiffHunk> {
19266        let mut hunks = Vec::new();
19267        let mut processed_buffer_rows: HashMap<BufferId, HashSet<Range<text::Anchor>>> =
19268            HashMap::default();
19269        for query_range in ranges {
19270            let query_rows =
19271                MultiBufferRow(query_range.start.row)..MultiBufferRow(query_range.end.row + 1);
19272            for hunk in self.buffer_snapshot.diff_hunks_in_range(
19273                Point::new(query_rows.start.0, 0)..Point::new(query_rows.end.0, 0),
19274            ) {
19275                // Include deleted hunks that are adjacent to the query range, because
19276                // otherwise they would be missed.
19277                let mut intersects_range = hunk.row_range.overlaps(&query_rows);
19278                if hunk.status().is_deleted() {
19279                    intersects_range |= hunk.row_range.start == query_rows.end;
19280                    intersects_range |= hunk.row_range.end == query_rows.start;
19281                }
19282                if intersects_range {
19283                    if !processed_buffer_rows
19284                        .entry(hunk.buffer_id)
19285                        .or_default()
19286                        .insert(hunk.buffer_range.start..hunk.buffer_range.end)
19287                    {
19288                        continue;
19289                    }
19290                    hunks.push(hunk);
19291                }
19292            }
19293        }
19294
19295        hunks
19296    }
19297
19298    fn display_diff_hunks_for_rows<'a>(
19299        &'a self,
19300        display_rows: Range<DisplayRow>,
19301        folded_buffers: &'a HashSet<BufferId>,
19302    ) -> impl 'a + Iterator<Item = DisplayDiffHunk> {
19303        let buffer_start = DisplayPoint::new(display_rows.start, 0).to_point(self);
19304        let buffer_end = DisplayPoint::new(display_rows.end, 0).to_point(self);
19305
19306        self.buffer_snapshot
19307            .diff_hunks_in_range(buffer_start..buffer_end)
19308            .filter_map(|hunk| {
19309                if folded_buffers.contains(&hunk.buffer_id) {
19310                    return None;
19311                }
19312
19313                let hunk_start_point = Point::new(hunk.row_range.start.0, 0);
19314                let hunk_end_point = Point::new(hunk.row_range.end.0, 0);
19315
19316                let hunk_display_start = self.point_to_display_point(hunk_start_point, Bias::Left);
19317                let hunk_display_end = self.point_to_display_point(hunk_end_point, Bias::Right);
19318
19319                let display_hunk = if hunk_display_start.column() != 0 {
19320                    DisplayDiffHunk::Folded {
19321                        display_row: hunk_display_start.row(),
19322                    }
19323                } else {
19324                    let mut end_row = hunk_display_end.row();
19325                    if hunk_display_end.column() > 0 {
19326                        end_row.0 += 1;
19327                    }
19328                    let is_created_file = hunk.is_created_file();
19329                    DisplayDiffHunk::Unfolded {
19330                        status: hunk.status(),
19331                        diff_base_byte_range: hunk.diff_base_byte_range,
19332                        display_row_range: hunk_display_start.row()..end_row,
19333                        multi_buffer_range: Anchor::range_in_buffer(
19334                            hunk.excerpt_id,
19335                            hunk.buffer_id,
19336                            hunk.buffer_range,
19337                        ),
19338                        is_created_file,
19339                    }
19340                };
19341
19342                Some(display_hunk)
19343            })
19344    }
19345
19346    pub fn language_at<T: ToOffset>(&self, position: T) -> Option<&Arc<Language>> {
19347        self.display_snapshot.buffer_snapshot.language_at(position)
19348    }
19349
19350    pub fn is_focused(&self) -> bool {
19351        self.is_focused
19352    }
19353
19354    pub fn placeholder_text(&self) -> Option<&Arc<str>> {
19355        self.placeholder_text.as_ref()
19356    }
19357
19358    pub fn scroll_position(&self) -> gpui::Point<f32> {
19359        self.scroll_anchor.scroll_position(&self.display_snapshot)
19360    }
19361
19362    fn gutter_dimensions(
19363        &self,
19364        font_id: FontId,
19365        font_size: Pixels,
19366        max_line_number_width: Pixels,
19367        cx: &App,
19368    ) -> Option<GutterDimensions> {
19369        if !self.show_gutter {
19370            return None;
19371        }
19372
19373        let descent = cx.text_system().descent(font_id, font_size);
19374        let em_width = cx.text_system().em_width(font_id, font_size).log_err()?;
19375        let em_advance = cx.text_system().em_advance(font_id, font_size).log_err()?;
19376
19377        let show_git_gutter = self.show_git_diff_gutter.unwrap_or_else(|| {
19378            matches!(
19379                ProjectSettings::get_global(cx).git.git_gutter,
19380                Some(GitGutterSetting::TrackedFiles)
19381            )
19382        });
19383        let gutter_settings = EditorSettings::get_global(cx).gutter;
19384        let show_line_numbers = self
19385            .show_line_numbers
19386            .unwrap_or(gutter_settings.line_numbers);
19387        let line_gutter_width = if show_line_numbers {
19388            // Avoid flicker-like gutter resizes when the line number gains another digit and only resize the gutter on files with N*10^5 lines.
19389            let min_width_for_number_on_gutter = em_advance * MIN_LINE_NUMBER_DIGITS as f32;
19390            max_line_number_width.max(min_width_for_number_on_gutter)
19391        } else {
19392            0.0.into()
19393        };
19394
19395        let show_code_actions = self
19396            .show_code_actions
19397            .unwrap_or(gutter_settings.code_actions);
19398
19399        let show_runnables = self.show_runnables.unwrap_or(gutter_settings.runnables);
19400        let show_breakpoints = self.show_breakpoints.unwrap_or(gutter_settings.breakpoints);
19401
19402        let git_blame_entries_width =
19403            self.git_blame_gutter_max_author_length
19404                .map(|max_author_length| {
19405                    let renderer = cx.global::<GlobalBlameRenderer>().0.clone();
19406                    const MAX_RELATIVE_TIMESTAMP: &str = "60 minutes ago";
19407
19408                    /// The number of characters to dedicate to gaps and margins.
19409                    const SPACING_WIDTH: usize = 4;
19410
19411                    let max_char_count = max_author_length.min(renderer.max_author_length())
19412                        + ::git::SHORT_SHA_LENGTH
19413                        + MAX_RELATIVE_TIMESTAMP.len()
19414                        + SPACING_WIDTH;
19415
19416                    em_advance * max_char_count
19417                });
19418
19419        let is_singleton = self.buffer_snapshot.is_singleton();
19420
19421        let mut left_padding = git_blame_entries_width.unwrap_or(Pixels::ZERO);
19422        left_padding += if !is_singleton {
19423            em_width * 4.0
19424        } else if show_code_actions || show_runnables || show_breakpoints {
19425            em_width * 3.0
19426        } else if show_git_gutter && show_line_numbers {
19427            em_width * 2.0
19428        } else if show_git_gutter || show_line_numbers {
19429            em_width
19430        } else {
19431            px(0.)
19432        };
19433
19434        let shows_folds = is_singleton && gutter_settings.folds;
19435
19436        let right_padding = if shows_folds && show_line_numbers {
19437            em_width * 4.0
19438        } else if shows_folds || (!is_singleton && show_line_numbers) {
19439            em_width * 3.0
19440        } else if show_line_numbers {
19441            em_width
19442        } else {
19443            px(0.)
19444        };
19445
19446        Some(GutterDimensions {
19447            left_padding,
19448            right_padding,
19449            width: line_gutter_width + left_padding + right_padding,
19450            margin: -descent,
19451            git_blame_entries_width,
19452        })
19453    }
19454
19455    pub fn render_crease_toggle(
19456        &self,
19457        buffer_row: MultiBufferRow,
19458        row_contains_cursor: bool,
19459        editor: Entity<Editor>,
19460        window: &mut Window,
19461        cx: &mut App,
19462    ) -> Option<AnyElement> {
19463        let folded = self.is_line_folded(buffer_row);
19464        let mut is_foldable = false;
19465
19466        if let Some(crease) = self
19467            .crease_snapshot
19468            .query_row(buffer_row, &self.buffer_snapshot)
19469        {
19470            is_foldable = true;
19471            match crease {
19472                Crease::Inline { render_toggle, .. } | Crease::Block { render_toggle, .. } => {
19473                    if let Some(render_toggle) = render_toggle {
19474                        let toggle_callback =
19475                            Arc::new(move |folded, window: &mut Window, cx: &mut App| {
19476                                if folded {
19477                                    editor.update(cx, |editor, cx| {
19478                                        editor.fold_at(buffer_row, window, cx)
19479                                    });
19480                                } else {
19481                                    editor.update(cx, |editor, cx| {
19482                                        editor.unfold_at(buffer_row, window, cx)
19483                                    });
19484                                }
19485                            });
19486                        return Some((render_toggle)(
19487                            buffer_row,
19488                            folded,
19489                            toggle_callback,
19490                            window,
19491                            cx,
19492                        ));
19493                    }
19494                }
19495            }
19496        }
19497
19498        is_foldable |= self.starts_indent(buffer_row);
19499
19500        if folded || (is_foldable && (row_contains_cursor || self.gutter_hovered)) {
19501            Some(
19502                Disclosure::new(("gutter_crease", buffer_row.0), !folded)
19503                    .toggle_state(folded)
19504                    .on_click(window.listener_for(&editor, move |this, _e, window, cx| {
19505                        if folded {
19506                            this.unfold_at(buffer_row, window, cx);
19507                        } else {
19508                            this.fold_at(buffer_row, window, cx);
19509                        }
19510                    }))
19511                    .into_any_element(),
19512            )
19513        } else {
19514            None
19515        }
19516    }
19517
19518    pub fn render_crease_trailer(
19519        &self,
19520        buffer_row: MultiBufferRow,
19521        window: &mut Window,
19522        cx: &mut App,
19523    ) -> Option<AnyElement> {
19524        let folded = self.is_line_folded(buffer_row);
19525        if let Crease::Inline { render_trailer, .. } = self
19526            .crease_snapshot
19527            .query_row(buffer_row, &self.buffer_snapshot)?
19528        {
19529            let render_trailer = render_trailer.as_ref()?;
19530            Some(render_trailer(buffer_row, folded, window, cx))
19531        } else {
19532            None
19533        }
19534    }
19535}
19536
19537impl Deref for EditorSnapshot {
19538    type Target = DisplaySnapshot;
19539
19540    fn deref(&self) -> &Self::Target {
19541        &self.display_snapshot
19542    }
19543}
19544
19545#[derive(Clone, Debug, PartialEq, Eq)]
19546pub enum EditorEvent {
19547    InputIgnored {
19548        text: Arc<str>,
19549    },
19550    InputHandled {
19551        utf16_range_to_replace: Option<Range<isize>>,
19552        text: Arc<str>,
19553    },
19554    ExcerptsAdded {
19555        buffer: Entity<Buffer>,
19556        predecessor: ExcerptId,
19557        excerpts: Vec<(ExcerptId, ExcerptRange<language::Anchor>)>,
19558    },
19559    ExcerptsRemoved {
19560        ids: Vec<ExcerptId>,
19561    },
19562    BufferFoldToggled {
19563        ids: Vec<ExcerptId>,
19564        folded: bool,
19565    },
19566    ExcerptsEdited {
19567        ids: Vec<ExcerptId>,
19568    },
19569    ExcerptsExpanded {
19570        ids: Vec<ExcerptId>,
19571    },
19572    BufferEdited,
19573    Edited {
19574        transaction_id: clock::Lamport,
19575    },
19576    Reparsed(BufferId),
19577    Focused,
19578    FocusedIn,
19579    Blurred,
19580    DirtyChanged,
19581    Saved,
19582    TitleChanged,
19583    DiffBaseChanged,
19584    SelectionsChanged {
19585        local: bool,
19586    },
19587    ScrollPositionChanged {
19588        local: bool,
19589        autoscroll: bool,
19590    },
19591    Closed,
19592    TransactionUndone {
19593        transaction_id: clock::Lamport,
19594    },
19595    TransactionBegun {
19596        transaction_id: clock::Lamport,
19597    },
19598    Reloaded,
19599    CursorShapeChanged,
19600    PushedToNavHistory {
19601        anchor: Anchor,
19602        is_deactivate: bool,
19603    },
19604}
19605
19606impl EventEmitter<EditorEvent> for Editor {}
19607
19608impl Focusable for Editor {
19609    fn focus_handle(&self, _cx: &App) -> FocusHandle {
19610        self.focus_handle.clone()
19611    }
19612}
19613
19614impl Render for Editor {
19615    fn render(&mut self, _: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
19616        let settings = ThemeSettings::get_global(cx);
19617
19618        let mut text_style = match self.mode {
19619            EditorMode::SingleLine { .. } | EditorMode::AutoHeight { .. } => TextStyle {
19620                color: cx.theme().colors().editor_foreground,
19621                font_family: settings.ui_font.family.clone(),
19622                font_features: settings.ui_font.features.clone(),
19623                font_fallbacks: settings.ui_font.fallbacks.clone(),
19624                font_size: rems(0.875).into(),
19625                font_weight: settings.ui_font.weight,
19626                line_height: relative(settings.buffer_line_height.value()),
19627                ..Default::default()
19628            },
19629            EditorMode::Full { .. } => TextStyle {
19630                color: cx.theme().colors().editor_foreground,
19631                font_family: settings.buffer_font.family.clone(),
19632                font_features: settings.buffer_font.features.clone(),
19633                font_fallbacks: settings.buffer_font.fallbacks.clone(),
19634                font_size: settings.buffer_font_size(cx).into(),
19635                font_weight: settings.buffer_font.weight,
19636                line_height: relative(settings.buffer_line_height.value()),
19637                ..Default::default()
19638            },
19639        };
19640        if let Some(text_style_refinement) = &self.text_style_refinement {
19641            text_style.refine(text_style_refinement)
19642        }
19643
19644        let background = match self.mode {
19645            EditorMode::SingleLine { .. } => cx.theme().system().transparent,
19646            EditorMode::AutoHeight { max_lines: _ } => cx.theme().system().transparent,
19647            EditorMode::Full { .. } => cx.theme().colors().editor_background,
19648        };
19649
19650        EditorElement::new(
19651            &cx.entity(),
19652            EditorStyle {
19653                background,
19654                local_player: cx.theme().players().local(),
19655                text: text_style,
19656                scrollbar_width: EditorElement::SCROLLBAR_WIDTH,
19657                syntax: cx.theme().syntax().clone(),
19658                status: cx.theme().status().clone(),
19659                inlay_hints_style: make_inlay_hints_style(cx),
19660                inline_completion_styles: make_suggestion_styles(cx),
19661                unnecessary_code_fade: ThemeSettings::get_global(cx).unnecessary_code_fade,
19662            },
19663        )
19664    }
19665}
19666
19667impl EntityInputHandler for Editor {
19668    fn text_for_range(
19669        &mut self,
19670        range_utf16: Range<usize>,
19671        adjusted_range: &mut Option<Range<usize>>,
19672        _: &mut Window,
19673        cx: &mut Context<Self>,
19674    ) -> Option<String> {
19675        let snapshot = self.buffer.read(cx).read(cx);
19676        let start = snapshot.clip_offset_utf16(OffsetUtf16(range_utf16.start), Bias::Left);
19677        let end = snapshot.clip_offset_utf16(OffsetUtf16(range_utf16.end), Bias::Right);
19678        if (start.0..end.0) != range_utf16 {
19679            adjusted_range.replace(start.0..end.0);
19680        }
19681        Some(snapshot.text_for_range(start..end).collect())
19682    }
19683
19684    fn selected_text_range(
19685        &mut self,
19686        ignore_disabled_input: bool,
19687        _: &mut Window,
19688        cx: &mut Context<Self>,
19689    ) -> Option<UTF16Selection> {
19690        // Prevent the IME menu from appearing when holding down an alphabetic key
19691        // while input is disabled.
19692        if !ignore_disabled_input && !self.input_enabled {
19693            return None;
19694        }
19695
19696        let selection = self.selections.newest::<OffsetUtf16>(cx);
19697        let range = selection.range();
19698
19699        Some(UTF16Selection {
19700            range: range.start.0..range.end.0,
19701            reversed: selection.reversed,
19702        })
19703    }
19704
19705    fn marked_text_range(&self, _: &mut Window, cx: &mut Context<Self>) -> Option<Range<usize>> {
19706        let snapshot = self.buffer.read(cx).read(cx);
19707        let range = self.text_highlights::<InputComposition>(cx)?.1.first()?;
19708        Some(range.start.to_offset_utf16(&snapshot).0..range.end.to_offset_utf16(&snapshot).0)
19709    }
19710
19711    fn unmark_text(&mut self, _: &mut Window, cx: &mut Context<Self>) {
19712        self.clear_highlights::<InputComposition>(cx);
19713        self.ime_transaction.take();
19714    }
19715
19716    fn replace_text_in_range(
19717        &mut self,
19718        range_utf16: Option<Range<usize>>,
19719        text: &str,
19720        window: &mut Window,
19721        cx: &mut Context<Self>,
19722    ) {
19723        if !self.input_enabled {
19724            cx.emit(EditorEvent::InputIgnored { text: text.into() });
19725            return;
19726        }
19727
19728        self.transact(window, cx, |this, window, cx| {
19729            let new_selected_ranges = if let Some(range_utf16) = range_utf16 {
19730                let range_utf16 = OffsetUtf16(range_utf16.start)..OffsetUtf16(range_utf16.end);
19731                Some(this.selection_replacement_ranges(range_utf16, cx))
19732            } else {
19733                this.marked_text_ranges(cx)
19734            };
19735
19736            let range_to_replace = new_selected_ranges.as_ref().and_then(|ranges_to_replace| {
19737                let newest_selection_id = this.selections.newest_anchor().id;
19738                this.selections
19739                    .all::<OffsetUtf16>(cx)
19740                    .iter()
19741                    .zip(ranges_to_replace.iter())
19742                    .find_map(|(selection, range)| {
19743                        if selection.id == newest_selection_id {
19744                            Some(
19745                                (range.start.0 as isize - selection.head().0 as isize)
19746                                    ..(range.end.0 as isize - selection.head().0 as isize),
19747                            )
19748                        } else {
19749                            None
19750                        }
19751                    })
19752            });
19753
19754            cx.emit(EditorEvent::InputHandled {
19755                utf16_range_to_replace: range_to_replace,
19756                text: text.into(),
19757            });
19758
19759            if let Some(new_selected_ranges) = new_selected_ranges {
19760                this.change_selections(None, window, cx, |selections| {
19761                    selections.select_ranges(new_selected_ranges)
19762                });
19763                this.backspace(&Default::default(), window, cx);
19764            }
19765
19766            this.handle_input(text, window, cx);
19767        });
19768
19769        if let Some(transaction) = self.ime_transaction {
19770            self.buffer.update(cx, |buffer, cx| {
19771                buffer.group_until_transaction(transaction, cx);
19772            });
19773        }
19774
19775        self.unmark_text(window, cx);
19776    }
19777
19778    fn replace_and_mark_text_in_range(
19779        &mut self,
19780        range_utf16: Option<Range<usize>>,
19781        text: &str,
19782        new_selected_range_utf16: Option<Range<usize>>,
19783        window: &mut Window,
19784        cx: &mut Context<Self>,
19785    ) {
19786        if !self.input_enabled {
19787            return;
19788        }
19789
19790        let transaction = self.transact(window, cx, |this, window, cx| {
19791            let ranges_to_replace = if let Some(mut marked_ranges) = this.marked_text_ranges(cx) {
19792                let snapshot = this.buffer.read(cx).read(cx);
19793                if let Some(relative_range_utf16) = range_utf16.as_ref() {
19794                    for marked_range in &mut marked_ranges {
19795                        marked_range.end.0 = marked_range.start.0 + relative_range_utf16.end;
19796                        marked_range.start.0 += relative_range_utf16.start;
19797                        marked_range.start =
19798                            snapshot.clip_offset_utf16(marked_range.start, Bias::Left);
19799                        marked_range.end =
19800                            snapshot.clip_offset_utf16(marked_range.end, Bias::Right);
19801                    }
19802                }
19803                Some(marked_ranges)
19804            } else if let Some(range_utf16) = range_utf16 {
19805                let range_utf16 = OffsetUtf16(range_utf16.start)..OffsetUtf16(range_utf16.end);
19806                Some(this.selection_replacement_ranges(range_utf16, cx))
19807            } else {
19808                None
19809            };
19810
19811            let range_to_replace = ranges_to_replace.as_ref().and_then(|ranges_to_replace| {
19812                let newest_selection_id = this.selections.newest_anchor().id;
19813                this.selections
19814                    .all::<OffsetUtf16>(cx)
19815                    .iter()
19816                    .zip(ranges_to_replace.iter())
19817                    .find_map(|(selection, range)| {
19818                        if selection.id == newest_selection_id {
19819                            Some(
19820                                (range.start.0 as isize - selection.head().0 as isize)
19821                                    ..(range.end.0 as isize - selection.head().0 as isize),
19822                            )
19823                        } else {
19824                            None
19825                        }
19826                    })
19827            });
19828
19829            cx.emit(EditorEvent::InputHandled {
19830                utf16_range_to_replace: range_to_replace,
19831                text: text.into(),
19832            });
19833
19834            if let Some(ranges) = ranges_to_replace {
19835                this.change_selections(None, window, cx, |s| s.select_ranges(ranges));
19836            }
19837
19838            let marked_ranges = {
19839                let snapshot = this.buffer.read(cx).read(cx);
19840                this.selections
19841                    .disjoint_anchors()
19842                    .iter()
19843                    .map(|selection| {
19844                        selection.start.bias_left(&snapshot)..selection.end.bias_right(&snapshot)
19845                    })
19846                    .collect::<Vec<_>>()
19847            };
19848
19849            if text.is_empty() {
19850                this.unmark_text(window, cx);
19851            } else {
19852                this.highlight_text::<InputComposition>(
19853                    marked_ranges.clone(),
19854                    HighlightStyle {
19855                        underline: Some(UnderlineStyle {
19856                            thickness: px(1.),
19857                            color: None,
19858                            wavy: false,
19859                        }),
19860                        ..Default::default()
19861                    },
19862                    cx,
19863                );
19864            }
19865
19866            // Disable auto-closing when composing text (i.e. typing a `"` on a Brazilian keyboard)
19867            let use_autoclose = this.use_autoclose;
19868            let use_auto_surround = this.use_auto_surround;
19869            this.set_use_autoclose(false);
19870            this.set_use_auto_surround(false);
19871            this.handle_input(text, window, cx);
19872            this.set_use_autoclose(use_autoclose);
19873            this.set_use_auto_surround(use_auto_surround);
19874
19875            if let Some(new_selected_range) = new_selected_range_utf16 {
19876                let snapshot = this.buffer.read(cx).read(cx);
19877                let new_selected_ranges = marked_ranges
19878                    .into_iter()
19879                    .map(|marked_range| {
19880                        let insertion_start = marked_range.start.to_offset_utf16(&snapshot).0;
19881                        let new_start = OffsetUtf16(new_selected_range.start + insertion_start);
19882                        let new_end = OffsetUtf16(new_selected_range.end + insertion_start);
19883                        snapshot.clip_offset_utf16(new_start, Bias::Left)
19884                            ..snapshot.clip_offset_utf16(new_end, Bias::Right)
19885                    })
19886                    .collect::<Vec<_>>();
19887
19888                drop(snapshot);
19889                this.change_selections(None, window, cx, |selections| {
19890                    selections.select_ranges(new_selected_ranges)
19891                });
19892            }
19893        });
19894
19895        self.ime_transaction = self.ime_transaction.or(transaction);
19896        if let Some(transaction) = self.ime_transaction {
19897            self.buffer.update(cx, |buffer, cx| {
19898                buffer.group_until_transaction(transaction, cx);
19899            });
19900        }
19901
19902        if self.text_highlights::<InputComposition>(cx).is_none() {
19903            self.ime_transaction.take();
19904        }
19905    }
19906
19907    fn bounds_for_range(
19908        &mut self,
19909        range_utf16: Range<usize>,
19910        element_bounds: gpui::Bounds<Pixels>,
19911        window: &mut Window,
19912        cx: &mut Context<Self>,
19913    ) -> Option<gpui::Bounds<Pixels>> {
19914        let text_layout_details = self.text_layout_details(window);
19915        let gpui::Size {
19916            width: em_width,
19917            height: line_height,
19918        } = self.character_size(window);
19919
19920        let snapshot = self.snapshot(window, cx);
19921        let scroll_position = snapshot.scroll_position();
19922        let scroll_left = scroll_position.x * em_width;
19923
19924        let start = OffsetUtf16(range_utf16.start).to_display_point(&snapshot);
19925        let x = snapshot.x_for_display_point(start, &text_layout_details) - scroll_left
19926            + self.gutter_dimensions.width
19927            + self.gutter_dimensions.margin;
19928        let y = line_height * (start.row().as_f32() - scroll_position.y);
19929
19930        Some(Bounds {
19931            origin: element_bounds.origin + point(x, y),
19932            size: size(em_width, line_height),
19933        })
19934    }
19935
19936    fn character_index_for_point(
19937        &mut self,
19938        point: gpui::Point<Pixels>,
19939        _window: &mut Window,
19940        _cx: &mut Context<Self>,
19941    ) -> Option<usize> {
19942        let position_map = self.last_position_map.as_ref()?;
19943        if !position_map.text_hitbox.contains(&point) {
19944            return None;
19945        }
19946        let display_point = position_map.point_for_position(point).previous_valid;
19947        let anchor = position_map
19948            .snapshot
19949            .display_point_to_anchor(display_point, Bias::Left);
19950        let utf16_offset = anchor.to_offset_utf16(&position_map.snapshot.buffer_snapshot);
19951        Some(utf16_offset.0)
19952    }
19953}
19954
19955trait SelectionExt {
19956    fn display_range(&self, map: &DisplaySnapshot) -> Range<DisplayPoint>;
19957    fn spanned_rows(
19958        &self,
19959        include_end_if_at_line_start: bool,
19960        map: &DisplaySnapshot,
19961    ) -> Range<MultiBufferRow>;
19962}
19963
19964impl<T: ToPoint + ToOffset> SelectionExt for Selection<T> {
19965    fn display_range(&self, map: &DisplaySnapshot) -> Range<DisplayPoint> {
19966        let start = self
19967            .start
19968            .to_point(&map.buffer_snapshot)
19969            .to_display_point(map);
19970        let end = self
19971            .end
19972            .to_point(&map.buffer_snapshot)
19973            .to_display_point(map);
19974        if self.reversed {
19975            end..start
19976        } else {
19977            start..end
19978        }
19979    }
19980
19981    fn spanned_rows(
19982        &self,
19983        include_end_if_at_line_start: bool,
19984        map: &DisplaySnapshot,
19985    ) -> Range<MultiBufferRow> {
19986        let start = self.start.to_point(&map.buffer_snapshot);
19987        let mut end = self.end.to_point(&map.buffer_snapshot);
19988        if !include_end_if_at_line_start && start.row != end.row && end.column == 0 {
19989            end.row -= 1;
19990        }
19991
19992        let buffer_start = map.prev_line_boundary(start).0;
19993        let buffer_end = map.next_line_boundary(end).0;
19994        MultiBufferRow(buffer_start.row)..MultiBufferRow(buffer_end.row + 1)
19995    }
19996}
19997
19998impl<T: InvalidationRegion> InvalidationStack<T> {
19999    fn invalidate<S>(&mut self, selections: &[Selection<S>], buffer: &MultiBufferSnapshot)
20000    where
20001        S: Clone + ToOffset,
20002    {
20003        while let Some(region) = self.last() {
20004            let all_selections_inside_invalidation_ranges =
20005                if selections.len() == region.ranges().len() {
20006                    selections
20007                        .iter()
20008                        .zip(region.ranges().iter().map(|r| r.to_offset(buffer)))
20009                        .all(|(selection, invalidation_range)| {
20010                            let head = selection.head().to_offset(buffer);
20011                            invalidation_range.start <= head && invalidation_range.end >= head
20012                        })
20013                } else {
20014                    false
20015                };
20016
20017            if all_selections_inside_invalidation_ranges {
20018                break;
20019            } else {
20020                self.pop();
20021            }
20022        }
20023    }
20024}
20025
20026impl<T> Default for InvalidationStack<T> {
20027    fn default() -> Self {
20028        Self(Default::default())
20029    }
20030}
20031
20032impl<T> Deref for InvalidationStack<T> {
20033    type Target = Vec<T>;
20034
20035    fn deref(&self) -> &Self::Target {
20036        &self.0
20037    }
20038}
20039
20040impl<T> DerefMut for InvalidationStack<T> {
20041    fn deref_mut(&mut self) -> &mut Self::Target {
20042        &mut self.0
20043    }
20044}
20045
20046impl InvalidationRegion for SnippetState {
20047    fn ranges(&self) -> &[Range<Anchor>] {
20048        &self.ranges[self.active_index]
20049    }
20050}
20051
20052fn inline_completion_edit_text(
20053    current_snapshot: &BufferSnapshot,
20054    edits: &[(Range<Anchor>, String)],
20055    edit_preview: &EditPreview,
20056    include_deletions: bool,
20057    cx: &App,
20058) -> HighlightedText {
20059    let edits = edits
20060        .iter()
20061        .map(|(anchor, text)| {
20062            (
20063                anchor.start.text_anchor..anchor.end.text_anchor,
20064                text.clone(),
20065            )
20066        })
20067        .collect::<Vec<_>>();
20068
20069    edit_preview.highlight_edits(current_snapshot, &edits, include_deletions, cx)
20070}
20071
20072pub fn diagnostic_style(severity: DiagnosticSeverity, colors: &StatusColors) -> Hsla {
20073    match severity {
20074        DiagnosticSeverity::ERROR => colors.error,
20075        DiagnosticSeverity::WARNING => colors.warning,
20076        DiagnosticSeverity::INFORMATION => colors.info,
20077        DiagnosticSeverity::HINT => colors.info,
20078        _ => colors.ignored,
20079    }
20080}
20081
20082pub fn styled_runs_for_code_label<'a>(
20083    label: &'a CodeLabel,
20084    syntax_theme: &'a theme::SyntaxTheme,
20085) -> impl 'a + Iterator<Item = (Range<usize>, HighlightStyle)> {
20086    let fade_out = HighlightStyle {
20087        fade_out: Some(0.35),
20088        ..Default::default()
20089    };
20090
20091    let mut prev_end = label.filter_range.end;
20092    label
20093        .runs
20094        .iter()
20095        .enumerate()
20096        .flat_map(move |(ix, (range, highlight_id))| {
20097            let style = if let Some(style) = highlight_id.style(syntax_theme) {
20098                style
20099            } else {
20100                return Default::default();
20101            };
20102            let mut muted_style = style;
20103            muted_style.highlight(fade_out);
20104
20105            let mut runs = SmallVec::<[(Range<usize>, HighlightStyle); 3]>::new();
20106            if range.start >= label.filter_range.end {
20107                if range.start > prev_end {
20108                    runs.push((prev_end..range.start, fade_out));
20109                }
20110                runs.push((range.clone(), muted_style));
20111            } else if range.end <= label.filter_range.end {
20112                runs.push((range.clone(), style));
20113            } else {
20114                runs.push((range.start..label.filter_range.end, style));
20115                runs.push((label.filter_range.end..range.end, muted_style));
20116            }
20117            prev_end = cmp::max(prev_end, range.end);
20118
20119            if ix + 1 == label.runs.len() && label.text.len() > prev_end {
20120                runs.push((prev_end..label.text.len(), fade_out));
20121            }
20122
20123            runs
20124        })
20125}
20126
20127pub(crate) fn split_words(text: &str) -> impl std::iter::Iterator<Item = &str> + '_ {
20128    let mut prev_index = 0;
20129    let mut prev_codepoint: Option<char> = None;
20130    text.char_indices()
20131        .chain([(text.len(), '\0')])
20132        .filter_map(move |(index, codepoint)| {
20133            let prev_codepoint = prev_codepoint.replace(codepoint)?;
20134            let is_boundary = index == text.len()
20135                || !prev_codepoint.is_uppercase() && codepoint.is_uppercase()
20136                || !prev_codepoint.is_alphanumeric() && codepoint.is_alphanumeric();
20137            if is_boundary {
20138                let chunk = &text[prev_index..index];
20139                prev_index = index;
20140                Some(chunk)
20141            } else {
20142                None
20143            }
20144        })
20145}
20146
20147pub trait RangeToAnchorExt: Sized {
20148    fn to_anchors(self, snapshot: &MultiBufferSnapshot) -> Range<Anchor>;
20149
20150    fn to_display_points(self, snapshot: &EditorSnapshot) -> Range<DisplayPoint> {
20151        let anchor_range = self.to_anchors(&snapshot.buffer_snapshot);
20152        anchor_range.start.to_display_point(snapshot)..anchor_range.end.to_display_point(snapshot)
20153    }
20154}
20155
20156impl<T: ToOffset> RangeToAnchorExt for Range<T> {
20157    fn to_anchors(self, snapshot: &MultiBufferSnapshot) -> Range<Anchor> {
20158        let start_offset = self.start.to_offset(snapshot);
20159        let end_offset = self.end.to_offset(snapshot);
20160        if start_offset == end_offset {
20161            snapshot.anchor_before(start_offset)..snapshot.anchor_before(end_offset)
20162        } else {
20163            snapshot.anchor_after(self.start)..snapshot.anchor_before(self.end)
20164        }
20165    }
20166}
20167
20168pub trait RowExt {
20169    fn as_f32(&self) -> f32;
20170
20171    fn next_row(&self) -> Self;
20172
20173    fn previous_row(&self) -> Self;
20174
20175    fn minus(&self, other: Self) -> u32;
20176}
20177
20178impl RowExt for DisplayRow {
20179    fn as_f32(&self) -> f32 {
20180        self.0 as f32
20181    }
20182
20183    fn next_row(&self) -> Self {
20184        Self(self.0 + 1)
20185    }
20186
20187    fn previous_row(&self) -> Self {
20188        Self(self.0.saturating_sub(1))
20189    }
20190
20191    fn minus(&self, other: Self) -> u32 {
20192        self.0 - other.0
20193    }
20194}
20195
20196impl RowExt for MultiBufferRow {
20197    fn as_f32(&self) -> f32 {
20198        self.0 as f32
20199    }
20200
20201    fn next_row(&self) -> Self {
20202        Self(self.0 + 1)
20203    }
20204
20205    fn previous_row(&self) -> Self {
20206        Self(self.0.saturating_sub(1))
20207    }
20208
20209    fn minus(&self, other: Self) -> u32 {
20210        self.0 - other.0
20211    }
20212}
20213
20214trait RowRangeExt {
20215    type Row;
20216
20217    fn len(&self) -> usize;
20218
20219    fn iter_rows(&self) -> impl DoubleEndedIterator<Item = Self::Row>;
20220}
20221
20222impl RowRangeExt for Range<MultiBufferRow> {
20223    type Row = MultiBufferRow;
20224
20225    fn len(&self) -> usize {
20226        (self.end.0 - self.start.0) as usize
20227    }
20228
20229    fn iter_rows(&self) -> impl DoubleEndedIterator<Item = MultiBufferRow> {
20230        (self.start.0..self.end.0).map(MultiBufferRow)
20231    }
20232}
20233
20234impl RowRangeExt for Range<DisplayRow> {
20235    type Row = DisplayRow;
20236
20237    fn len(&self) -> usize {
20238        (self.end.0 - self.start.0) as usize
20239    }
20240
20241    fn iter_rows(&self) -> impl DoubleEndedIterator<Item = DisplayRow> {
20242        (self.start.0..self.end.0).map(DisplayRow)
20243    }
20244}
20245
20246/// If select range has more than one line, we
20247/// just point the cursor to range.start.
20248fn collapse_multiline_range(range: Range<Point>) -> Range<Point> {
20249    if range.start.row == range.end.row {
20250        range
20251    } else {
20252        range.start..range.start
20253    }
20254}
20255pub struct KillRing(ClipboardItem);
20256impl Global for KillRing {}
20257
20258const UPDATE_DEBOUNCE: Duration = Duration::from_millis(50);
20259
20260enum BreakpointPromptEditAction {
20261    Log,
20262    Condition,
20263    HitCondition,
20264}
20265
20266struct BreakpointPromptEditor {
20267    pub(crate) prompt: Entity<Editor>,
20268    editor: WeakEntity<Editor>,
20269    breakpoint_anchor: Anchor,
20270    breakpoint: Breakpoint,
20271    edit_action: BreakpointPromptEditAction,
20272    block_ids: HashSet<CustomBlockId>,
20273    gutter_dimensions: Arc<Mutex<GutterDimensions>>,
20274    _subscriptions: Vec<Subscription>,
20275}
20276
20277impl BreakpointPromptEditor {
20278    const MAX_LINES: u8 = 4;
20279
20280    fn new(
20281        editor: WeakEntity<Editor>,
20282        breakpoint_anchor: Anchor,
20283        breakpoint: Breakpoint,
20284        edit_action: BreakpointPromptEditAction,
20285        window: &mut Window,
20286        cx: &mut Context<Self>,
20287    ) -> Self {
20288        let base_text = match edit_action {
20289            BreakpointPromptEditAction::Log => breakpoint.message.as_ref(),
20290            BreakpointPromptEditAction::Condition => breakpoint.condition.as_ref(),
20291            BreakpointPromptEditAction::HitCondition => breakpoint.hit_condition.as_ref(),
20292        }
20293        .map(|msg| msg.to_string())
20294        .unwrap_or_default();
20295
20296        let buffer = cx.new(|cx| Buffer::local(base_text, cx));
20297        let buffer = cx.new(|cx| MultiBuffer::singleton(buffer, cx));
20298
20299        let prompt = cx.new(|cx| {
20300            let mut prompt = Editor::new(
20301                EditorMode::AutoHeight {
20302                    max_lines: Self::MAX_LINES as usize,
20303                },
20304                buffer,
20305                None,
20306                window,
20307                cx,
20308            );
20309            prompt.set_soft_wrap_mode(language::language_settings::SoftWrap::EditorWidth, cx);
20310            prompt.set_show_cursor_when_unfocused(false, cx);
20311            prompt.set_placeholder_text(
20312                match edit_action {
20313                    BreakpointPromptEditAction::Log => "Message to log when a breakpoint is hit. Expressions within {} are interpolated.",
20314                    BreakpointPromptEditAction::Condition => "Condition when a breakpoint is hit. Expressions within {} are interpolated.",
20315                    BreakpointPromptEditAction::HitCondition => "How many breakpoint hits to ignore",
20316                },
20317                cx,
20318            );
20319
20320            prompt
20321        });
20322
20323        Self {
20324            prompt,
20325            editor,
20326            breakpoint_anchor,
20327            breakpoint,
20328            edit_action,
20329            gutter_dimensions: Arc::new(Mutex::new(GutterDimensions::default())),
20330            block_ids: Default::default(),
20331            _subscriptions: vec![],
20332        }
20333    }
20334
20335    pub(crate) fn add_block_ids(&mut self, block_ids: Vec<CustomBlockId>) {
20336        self.block_ids.extend(block_ids)
20337    }
20338
20339    fn confirm(&mut self, _: &menu::Confirm, window: &mut Window, cx: &mut Context<Self>) {
20340        if let Some(editor) = self.editor.upgrade() {
20341            let message = self
20342                .prompt
20343                .read(cx)
20344                .buffer
20345                .read(cx)
20346                .as_singleton()
20347                .expect("A multi buffer in breakpoint prompt isn't possible")
20348                .read(cx)
20349                .as_rope()
20350                .to_string();
20351
20352            editor.update(cx, |editor, cx| {
20353                editor.edit_breakpoint_at_anchor(
20354                    self.breakpoint_anchor,
20355                    self.breakpoint.clone(),
20356                    match self.edit_action {
20357                        BreakpointPromptEditAction::Log => {
20358                            BreakpointEditAction::EditLogMessage(message.into())
20359                        }
20360                        BreakpointPromptEditAction::Condition => {
20361                            BreakpointEditAction::EditCondition(message.into())
20362                        }
20363                        BreakpointPromptEditAction::HitCondition => {
20364                            BreakpointEditAction::EditHitCondition(message.into())
20365                        }
20366                    },
20367                    cx,
20368                );
20369
20370                editor.remove_blocks(self.block_ids.clone(), None, cx);
20371                cx.focus_self(window);
20372            });
20373        }
20374    }
20375
20376    fn cancel(&mut self, _: &menu::Cancel, window: &mut Window, cx: &mut Context<Self>) {
20377        self.editor
20378            .update(cx, |editor, cx| {
20379                editor.remove_blocks(self.block_ids.clone(), None, cx);
20380                window.focus(&editor.focus_handle);
20381            })
20382            .log_err();
20383    }
20384
20385    fn render_prompt_editor(&self, cx: &mut Context<Self>) -> impl IntoElement {
20386        let settings = ThemeSettings::get_global(cx);
20387        let text_style = TextStyle {
20388            color: if self.prompt.read(cx).read_only(cx) {
20389                cx.theme().colors().text_disabled
20390            } else {
20391                cx.theme().colors().text
20392            },
20393            font_family: settings.buffer_font.family.clone(),
20394            font_fallbacks: settings.buffer_font.fallbacks.clone(),
20395            font_size: settings.buffer_font_size(cx).into(),
20396            font_weight: settings.buffer_font.weight,
20397            line_height: relative(settings.buffer_line_height.value()),
20398            ..Default::default()
20399        };
20400        EditorElement::new(
20401            &self.prompt,
20402            EditorStyle {
20403                background: cx.theme().colors().editor_background,
20404                local_player: cx.theme().players().local(),
20405                text: text_style,
20406                ..Default::default()
20407            },
20408        )
20409    }
20410}
20411
20412impl Render for BreakpointPromptEditor {
20413    fn render(&mut self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
20414        let gutter_dimensions = *self.gutter_dimensions.lock();
20415        h_flex()
20416            .key_context("Editor")
20417            .bg(cx.theme().colors().editor_background)
20418            .border_y_1()
20419            .border_color(cx.theme().status().info_border)
20420            .size_full()
20421            .py(window.line_height() / 2.5)
20422            .on_action(cx.listener(Self::confirm))
20423            .on_action(cx.listener(Self::cancel))
20424            .child(h_flex().w(gutter_dimensions.full_width() + (gutter_dimensions.margin / 2.0)))
20425            .child(div().flex_1().child(self.render_prompt_editor(cx)))
20426    }
20427}
20428
20429impl Focusable for BreakpointPromptEditor {
20430    fn focus_handle(&self, cx: &App) -> FocusHandle {
20431        self.prompt.focus_handle(cx)
20432    }
20433}
20434
20435fn all_edits_insertions_or_deletions(
20436    edits: &Vec<(Range<Anchor>, String)>,
20437    snapshot: &MultiBufferSnapshot,
20438) -> bool {
20439    let mut all_insertions = true;
20440    let mut all_deletions = true;
20441
20442    for (range, new_text) in edits.iter() {
20443        let range_is_empty = range.to_offset(&snapshot).is_empty();
20444        let text_is_empty = new_text.is_empty();
20445
20446        if range_is_empty != text_is_empty {
20447            if range_is_empty {
20448                all_deletions = false;
20449            } else {
20450                all_insertions = false;
20451            }
20452        } else {
20453            return false;
20454        }
20455
20456        if !all_insertions && !all_deletions {
20457            return false;
20458        }
20459    }
20460    all_insertions || all_deletions
20461}
20462
20463struct MissingEditPredictionKeybindingTooltip;
20464
20465impl Render for MissingEditPredictionKeybindingTooltip {
20466    fn render(&mut self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
20467        ui::tooltip_container(window, cx, |container, _, cx| {
20468            container
20469                .flex_shrink_0()
20470                .max_w_80()
20471                .min_h(rems_from_px(124.))
20472                .justify_between()
20473                .child(
20474                    v_flex()
20475                        .flex_1()
20476                        .text_ui_sm(cx)
20477                        .child(Label::new("Conflict with Accept Keybinding"))
20478                        .child("Your keymap currently overrides the default accept keybinding. To continue, assign one keybinding for the `editor::AcceptEditPrediction` action.")
20479                )
20480                .child(
20481                    h_flex()
20482                        .pb_1()
20483                        .gap_1()
20484                        .items_end()
20485                        .w_full()
20486                        .child(Button::new("open-keymap", "Assign Keybinding").size(ButtonSize::Compact).on_click(|_ev, window, cx| {
20487                            window.dispatch_action(zed_actions::OpenKeymap.boxed_clone(), cx)
20488                        }))
20489                        .child(Button::new("see-docs", "See Docs").size(ButtonSize::Compact).on_click(|_ev, _window, cx| {
20490                            cx.open_url("https://zed.dev/docs/completions#edit-predictions-missing-keybinding");
20491                        })),
20492                )
20493        })
20494    }
20495}
20496
20497#[derive(Debug, Clone, Copy, PartialEq)]
20498pub struct LineHighlight {
20499    pub background: Background,
20500    pub border: Option<gpui::Hsla>,
20501}
20502
20503impl From<Hsla> for LineHighlight {
20504    fn from(hsla: Hsla) -> Self {
20505        Self {
20506            background: hsla.into(),
20507            border: None,
20508        }
20509    }
20510}
20511
20512impl From<Background> for LineHighlight {
20513    fn from(background: Background) -> Self {
20514        Self {
20515            background,
20516            border: None,
20517        }
20518    }
20519}
20520
20521fn render_diff_hunk_controls(
20522    row: u32,
20523    status: &DiffHunkStatus,
20524    hunk_range: Range<Anchor>,
20525    is_created_file: bool,
20526    line_height: Pixels,
20527    editor: &Entity<Editor>,
20528    _window: &mut Window,
20529    cx: &mut App,
20530) -> AnyElement {
20531    h_flex()
20532        .h(line_height)
20533        .mr_1()
20534        .gap_1()
20535        .px_0p5()
20536        .pb_1()
20537        .border_x_1()
20538        .border_b_1()
20539        .border_color(cx.theme().colors().border_variant)
20540        .rounded_b_lg()
20541        .bg(cx.theme().colors().editor_background)
20542        .gap_1()
20543        .occlude()
20544        .shadow_md()
20545        .child(if status.has_secondary_hunk() {
20546            Button::new(("stage", row as u64), "Stage")
20547                .alpha(if status.is_pending() { 0.66 } else { 1.0 })
20548                .tooltip({
20549                    let focus_handle = editor.focus_handle(cx);
20550                    move |window, cx| {
20551                        Tooltip::for_action_in(
20552                            "Stage Hunk",
20553                            &::git::ToggleStaged,
20554                            &focus_handle,
20555                            window,
20556                            cx,
20557                        )
20558                    }
20559                })
20560                .on_click({
20561                    let editor = editor.clone();
20562                    move |_event, _window, cx| {
20563                        editor.update(cx, |editor, cx| {
20564                            editor.stage_or_unstage_diff_hunks(
20565                                true,
20566                                vec![hunk_range.start..hunk_range.start],
20567                                cx,
20568                            );
20569                        });
20570                    }
20571                })
20572        } else {
20573            Button::new(("unstage", row as u64), "Unstage")
20574                .alpha(if status.is_pending() { 0.66 } else { 1.0 })
20575                .tooltip({
20576                    let focus_handle = editor.focus_handle(cx);
20577                    move |window, cx| {
20578                        Tooltip::for_action_in(
20579                            "Unstage Hunk",
20580                            &::git::ToggleStaged,
20581                            &focus_handle,
20582                            window,
20583                            cx,
20584                        )
20585                    }
20586                })
20587                .on_click({
20588                    let editor = editor.clone();
20589                    move |_event, _window, cx| {
20590                        editor.update(cx, |editor, cx| {
20591                            editor.stage_or_unstage_diff_hunks(
20592                                false,
20593                                vec![hunk_range.start..hunk_range.start],
20594                                cx,
20595                            );
20596                        });
20597                    }
20598                })
20599        })
20600        .child(
20601            Button::new(("restore", row as u64), "Restore")
20602                .tooltip({
20603                    let focus_handle = editor.focus_handle(cx);
20604                    move |window, cx| {
20605                        Tooltip::for_action_in(
20606                            "Restore Hunk",
20607                            &::git::Restore,
20608                            &focus_handle,
20609                            window,
20610                            cx,
20611                        )
20612                    }
20613                })
20614                .on_click({
20615                    let editor = editor.clone();
20616                    move |_event, window, cx| {
20617                        editor.update(cx, |editor, cx| {
20618                            let snapshot = editor.snapshot(window, cx);
20619                            let point = hunk_range.start.to_point(&snapshot.buffer_snapshot);
20620                            editor.restore_hunks_in_ranges(vec![point..point], window, cx);
20621                        });
20622                    }
20623                })
20624                .disabled(is_created_file),
20625        )
20626        .when(
20627            !editor.read(cx).buffer().read(cx).all_diff_hunks_expanded(),
20628            |el| {
20629                el.child(
20630                    IconButton::new(("next-hunk", row as u64), IconName::ArrowDown)
20631                        .shape(IconButtonShape::Square)
20632                        .icon_size(IconSize::Small)
20633                        // .disabled(!has_multiple_hunks)
20634                        .tooltip({
20635                            let focus_handle = editor.focus_handle(cx);
20636                            move |window, cx| {
20637                                Tooltip::for_action_in(
20638                                    "Next Hunk",
20639                                    &GoToHunk,
20640                                    &focus_handle,
20641                                    window,
20642                                    cx,
20643                                )
20644                            }
20645                        })
20646                        .on_click({
20647                            let editor = editor.clone();
20648                            move |_event, window, cx| {
20649                                editor.update(cx, |editor, cx| {
20650                                    let snapshot = editor.snapshot(window, cx);
20651                                    let position =
20652                                        hunk_range.end.to_point(&snapshot.buffer_snapshot);
20653                                    editor.go_to_hunk_before_or_after_position(
20654                                        &snapshot,
20655                                        position,
20656                                        Direction::Next,
20657                                        window,
20658                                        cx,
20659                                    );
20660                                    editor.expand_selected_diff_hunks(cx);
20661                                });
20662                            }
20663                        }),
20664                )
20665                .child(
20666                    IconButton::new(("prev-hunk", row as u64), IconName::ArrowUp)
20667                        .shape(IconButtonShape::Square)
20668                        .icon_size(IconSize::Small)
20669                        // .disabled(!has_multiple_hunks)
20670                        .tooltip({
20671                            let focus_handle = editor.focus_handle(cx);
20672                            move |window, cx| {
20673                                Tooltip::for_action_in(
20674                                    "Previous Hunk",
20675                                    &GoToPreviousHunk,
20676                                    &focus_handle,
20677                                    window,
20678                                    cx,
20679                                )
20680                            }
20681                        })
20682                        .on_click({
20683                            let editor = editor.clone();
20684                            move |_event, window, cx| {
20685                                editor.update(cx, |editor, cx| {
20686                                    let snapshot = editor.snapshot(window, cx);
20687                                    let point =
20688                                        hunk_range.start.to_point(&snapshot.buffer_snapshot);
20689                                    editor.go_to_hunk_before_or_after_position(
20690                                        &snapshot,
20691                                        point,
20692                                        Direction::Prev,
20693                                        window,
20694                                        cx,
20695                                    );
20696                                    editor.expand_selected_diff_hunks(cx);
20697                                });
20698                            }
20699                        }),
20700                )
20701            },
20702        )
20703        .into_any_element()
20704}