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;
   26mod 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, StyledText, Subscription, Task, TextStyle,
   92    TextStyleRefinement, UTF16Selection, UnderlineStyle, UniformListScrollHandle, WeakEntity,
   93    WeakFocusHandle, Window, div, impl_actions, point, prelude::*, pulsating_between, px, relative,
   94    size,
   95};
   96use highlight_matching_bracket::refresh_matching_bracket_highlights;
   97use hover_links::{HoverLink, HoveredLinkState, InlayHighlight, find_file};
   98pub use hover_popover::hover_markdown_style;
   99use hover_popover::{HoverState, hide_hover};
  100use indent_guides::ActiveIndentGuidesState;
  101use inlay_hint_cache::{InlayHintCache, InlaySplice, InvalidationStrategy};
  102pub use inline_completion::Direction;
  103use inline_completion::{EditPredictionProvider, InlineCompletionProviderHandle};
  104pub use items::MAX_TAB_TITLE_LEN;
  105use itertools::Itertools;
  106use language::{
  107    AutoindentMode, BracketMatch, BracketPair, Buffer, Capability, CharKind, CodeLabel,
  108    CursorShape, Diagnostic, DiffOptions, EditPredictionsMode, EditPreview, HighlightedText,
  109    IndentKind, IndentSize, Language, OffsetRangeExt, Point, Selection, SelectionGoal, TextObject,
  110    TransactionId, TreeSitterOptions, WordsQuery,
  111    language_settings::{
  112        self, InlayHintSettings, LspInsertMode, RewrapBehavior, WordsCompletionMode,
  113        all_language_settings, language_settings,
  114    },
  115    point_from_lsp, text_diff_with_options,
  116};
  117use language::{BufferRow, CharClassifier, Runnable, RunnableRange, point_to_lsp};
  118use linked_editing_ranges::refresh_linked_ranges;
  119use mouse_context_menu::MouseContextMenu;
  120use persistence::DB;
  121use project::{
  122    ProjectPath,
  123    debugger::breakpoint_store::{
  124        BreakpointEditAction, BreakpointState, BreakpointStore, BreakpointStoreEvent,
  125    },
  126};
  127
  128pub use git::blame::BlameRenderer;
  129pub use proposed_changes_editor::{
  130    ProposedChangeLocation, ProposedChangesEditor, ProposedChangesEditorToolbar,
  131};
  132use smallvec::smallvec;
  133use std::{cell::OnceCell, iter::Peekable};
  134use task::{ResolvedTask, RunnableTag, TaskTemplate, TaskVariables};
  135
  136pub use lsp::CompletionContext;
  137use lsp::{
  138    CodeActionKind, CompletionItemKind, CompletionTriggerKind, DiagnosticSeverity,
  139    InsertTextFormat, InsertTextMode, LanguageServerId, LanguageServerName,
  140};
  141
  142use language::BufferSnapshot;
  143pub use lsp_ext::lsp_tasks;
  144use movement::TextLayoutDetails;
  145pub use multi_buffer::{
  146    Anchor, AnchorRangeExt, ExcerptId, ExcerptRange, MultiBuffer, MultiBufferSnapshot, RowInfo,
  147    ToOffset, ToPoint,
  148};
  149use multi_buffer::{
  150    ExcerptInfo, ExpandExcerptDirection, MultiBufferDiffHunk, MultiBufferPoint, MultiBufferRow,
  151    MultiOrSingleBufferOffsetRange, PathKey, ToOffsetUtf16,
  152};
  153use parking_lot::Mutex;
  154use project::{
  155    CodeAction, Completion, CompletionIntent, CompletionSource, DocumentHighlight, InlayHint,
  156    Location, LocationLink, PrepareRenameResponse, Project, ProjectItem, ProjectTransaction,
  157    TaskSourceKind,
  158    debugger::breakpoint_store::Breakpoint,
  159    lsp_store::{CompletionDocumentation, FormatTrigger, LspFormatTarget, OpenLspBufferHandle},
  160    project_settings::{GitGutterSetting, ProjectSettings},
  161};
  162use rand::prelude::*;
  163use rpc::{ErrorExt, proto::*};
  164use scroll::{Autoscroll, OngoingScroll, ScrollAnchor, ScrollManager, ScrollbarAutoHide};
  165use selections_collection::{
  166    MutableSelectionsCollection, SelectionsCollection, resolve_selections,
  167};
  168use serde::{Deserialize, Serialize};
  169use settings::{Settings, SettingsLocation, SettingsStore, update_settings_file};
  170use smallvec::SmallVec;
  171use snippet::Snippet;
  172use std::sync::Arc;
  173use std::{
  174    any::TypeId,
  175    borrow::Cow,
  176    cell::RefCell,
  177    cmp::{self, Ordering, Reverse},
  178    mem,
  179    num::NonZeroU32,
  180    ops::{ControlFlow, Deref, DerefMut, Not as _, Range, RangeInclusive},
  181    path::{Path, PathBuf},
  182    rc::Rc,
  183    time::{Duration, Instant},
  184};
  185pub use sum_tree::Bias;
  186use sum_tree::TreeMap;
  187use text::{BufferId, FromAnchor, OffsetUtf16, Rope};
  188use theme::{
  189    ActiveTheme, PlayerColor, StatusColors, SyntaxTheme, ThemeColors, ThemeSettings,
  190    observe_buffer_font_size_adjustment,
  191};
  192use ui::{
  193    ButtonSize, ButtonStyle, ContextMenu, Disclosure, IconButton, IconButtonShape, IconName,
  194    IconSize, Key, Tooltip, h_flex, prelude::*,
  195};
  196use util::{RangeExt, ResultExt, TryFutureExt, maybe, post_inc};
  197use workspace::{
  198    Item as WorkspaceItem, ItemId, ItemNavHistory, OpenInTerminal, OpenTerminal,
  199    RestoreOnStartupBehavior, SERIALIZATION_THROTTLE_TIME, SplitDirection, TabBarSettings, Toast,
  200    ViewId, Workspace, WorkspaceId, WorkspaceSettings,
  201    item::{ItemHandle, PreviewTabsSettings},
  202    notifications::{DetachAndPromptErr, NotificationId, NotifyTaskExt},
  203    searchable::SearchEvent,
  204};
  205
  206use crate::hover_links::{find_url, find_url_from_range};
  207use crate::signature_help::{SignatureHelpHiddenBy, SignatureHelpState};
  208
  209pub const FILE_HEADER_HEIGHT: u32 = 2;
  210pub const MULTI_BUFFER_EXCERPT_HEADER_HEIGHT: u32 = 1;
  211pub const DEFAULT_MULTIBUFFER_CONTEXT: u32 = 2;
  212const CURSOR_BLINK_INTERVAL: Duration = Duration::from_millis(500);
  213const MAX_LINE_LEN: usize = 1024;
  214const MIN_NAVIGATION_HISTORY_ROW_DELTA: i64 = 10;
  215const MAX_SELECTION_HISTORY_LEN: usize = 1024;
  216pub(crate) const CURSORS_VISIBLE_FOR: Duration = Duration::from_millis(2000);
  217#[doc(hidden)]
  218pub const CODE_ACTIONS_DEBOUNCE_TIMEOUT: Duration = Duration::from_millis(250);
  219
  220pub(crate) const CODE_ACTION_TIMEOUT: Duration = Duration::from_secs(5);
  221pub(crate) const FORMAT_TIMEOUT: Duration = Duration::from_secs(5);
  222pub(crate) const SCROLL_CENTER_TOP_BOTTOM_DEBOUNCE_TIMEOUT: Duration = Duration::from_secs(1);
  223
  224pub(crate) const EDIT_PREDICTION_KEY_CONTEXT: &str = "edit_prediction";
  225pub(crate) const EDIT_PREDICTION_CONFLICT_KEY_CONTEXT: &str = "edit_prediction_conflict";
  226pub(crate) const MIN_LINE_NUMBER_DIGITS: u32 = 4;
  227
  228pub type RenderDiffHunkControlsFn = Arc<
  229    dyn Fn(
  230        u32,
  231        &DiffHunkStatus,
  232        Range<Anchor>,
  233        bool,
  234        Pixels,
  235        &Entity<Editor>,
  236        &mut Window,
  237        &mut App,
  238    ) -> AnyElement,
  239>;
  240
  241const COLUMNAR_SELECTION_MODIFIERS: Modifiers = Modifiers {
  242    alt: true,
  243    shift: true,
  244    control: false,
  245    platform: false,
  246    function: false,
  247};
  248
  249#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
  250pub enum InlayId {
  251    InlineCompletion(usize),
  252    Hint(usize),
  253}
  254
  255impl InlayId {
  256    fn id(&self) -> usize {
  257        match self {
  258            Self::InlineCompletion(id) => *id,
  259            Self::Hint(id) => *id,
  260        }
  261    }
  262}
  263
  264pub enum DebugCurrentRowHighlight {}
  265enum DocumentHighlightRead {}
  266enum DocumentHighlightWrite {}
  267enum InputComposition {}
  268enum SelectedTextHighlight {}
  269
  270#[derive(Debug, Copy, Clone, PartialEq, Eq)]
  271pub enum Navigated {
  272    Yes,
  273    No,
  274}
  275
  276impl Navigated {
  277    pub fn from_bool(yes: bool) -> Navigated {
  278        if yes { Navigated::Yes } else { Navigated::No }
  279    }
  280}
  281
  282#[derive(Debug, Clone, PartialEq, Eq)]
  283enum DisplayDiffHunk {
  284    Folded {
  285        display_row: DisplayRow,
  286    },
  287    Unfolded {
  288        is_created_file: bool,
  289        diff_base_byte_range: Range<usize>,
  290        display_row_range: Range<DisplayRow>,
  291        multi_buffer_range: Range<Anchor>,
  292        status: DiffHunkStatus,
  293    },
  294}
  295
  296pub enum HideMouseCursorOrigin {
  297    TypingAction,
  298    MovementAction,
  299}
  300
  301pub fn init_settings(cx: &mut App) {
  302    EditorSettings::register(cx);
  303}
  304
  305pub fn init(cx: &mut App) {
  306    init_settings(cx);
  307
  308    cx.set_global(GlobalBlameRenderer(Arc::new(())));
  309
  310    workspace::register_project_item::<Editor>(cx);
  311    workspace::FollowableViewRegistry::register::<Editor>(cx);
  312    workspace::register_serializable_item::<Editor>(cx);
  313
  314    cx.observe_new(
  315        |workspace: &mut Workspace, _: Option<&mut Window>, _cx: &mut Context<Workspace>| {
  316            workspace.register_action(Editor::new_file);
  317            workspace.register_action(Editor::new_file_vertical);
  318            workspace.register_action(Editor::new_file_horizontal);
  319            workspace.register_action(Editor::cancel_language_server_work);
  320        },
  321    )
  322    .detach();
  323
  324    cx.on_action(move |_: &workspace::NewFile, cx| {
  325        let app_state = workspace::AppState::global(cx);
  326        if let Some(app_state) = app_state.upgrade() {
  327            workspace::open_new(
  328                Default::default(),
  329                app_state,
  330                cx,
  331                |workspace, window, cx| {
  332                    Editor::new_file(workspace, &Default::default(), window, cx)
  333                },
  334            )
  335            .detach();
  336        }
  337    });
  338    cx.on_action(move |_: &workspace::NewWindow, cx| {
  339        let app_state = workspace::AppState::global(cx);
  340        if let Some(app_state) = app_state.upgrade() {
  341            workspace::open_new(
  342                Default::default(),
  343                app_state,
  344                cx,
  345                |workspace, window, cx| {
  346                    cx.activate(true);
  347                    Editor::new_file(workspace, &Default::default(), window, cx)
  348                },
  349            )
  350            .detach();
  351        }
  352    });
  353}
  354
  355pub fn set_blame_renderer(renderer: impl BlameRenderer + 'static, cx: &mut App) {
  356    cx.set_global(GlobalBlameRenderer(Arc::new(renderer)));
  357}
  358
  359pub struct SearchWithinRange;
  360
  361trait InvalidationRegion {
  362    fn ranges(&self) -> &[Range<Anchor>];
  363}
  364
  365#[derive(Clone, Debug, PartialEq)]
  366pub enum SelectPhase {
  367    Begin {
  368        position: DisplayPoint,
  369        add: bool,
  370        click_count: usize,
  371    },
  372    BeginColumnar {
  373        position: DisplayPoint,
  374        reset: bool,
  375        goal_column: u32,
  376    },
  377    Extend {
  378        position: DisplayPoint,
  379        click_count: usize,
  380    },
  381    Update {
  382        position: DisplayPoint,
  383        goal_column: u32,
  384        scroll_delta: gpui::Point<f32>,
  385    },
  386    End,
  387}
  388
  389#[derive(Clone, Debug)]
  390pub enum SelectMode {
  391    Character,
  392    Word(Range<Anchor>),
  393    Line(Range<Anchor>),
  394    All,
  395}
  396
  397#[derive(Copy, Clone, PartialEq, Eq, Debug)]
  398pub enum EditorMode {
  399    SingleLine {
  400        auto_width: bool,
  401    },
  402    AutoHeight {
  403        max_lines: usize,
  404    },
  405    Full {
  406        /// When set to `true`, the editor will scale its UI elements with the buffer font size.
  407        scale_ui_elements_with_buffer_font_size: bool,
  408        /// When set to `true`, the editor will render a background for the active line.
  409        show_active_line_background: bool,
  410    },
  411}
  412
  413impl EditorMode {
  414    pub fn full() -> Self {
  415        Self::Full {
  416            scale_ui_elements_with_buffer_font_size: true,
  417            show_active_line_background: true,
  418        }
  419    }
  420
  421    pub fn is_full(&self) -> bool {
  422        matches!(self, Self::Full { .. })
  423    }
  424}
  425
  426#[derive(Copy, Clone, Debug)]
  427pub enum SoftWrap {
  428    /// Prefer not to wrap at all.
  429    ///
  430    /// Note: this is currently internal, as actually limited by [`crate::MAX_LINE_LEN`] until it wraps.
  431    /// The mode is used inside git diff hunks, where it's seems currently more useful to not wrap as much as possible.
  432    GitDiff,
  433    /// Prefer a single line generally, unless an overly long line is encountered.
  434    None,
  435    /// Soft wrap lines that exceed the editor width.
  436    EditorWidth,
  437    /// Soft wrap lines at the preferred line length.
  438    Column(u32),
  439    /// Soft wrap line at the preferred line length or the editor width (whichever is smaller).
  440    Bounded(u32),
  441}
  442
  443#[derive(Clone)]
  444pub struct EditorStyle {
  445    pub background: Hsla,
  446    pub local_player: PlayerColor,
  447    pub text: TextStyle,
  448    pub scrollbar_width: Pixels,
  449    pub syntax: Arc<SyntaxTheme>,
  450    pub status: StatusColors,
  451    pub inlay_hints_style: HighlightStyle,
  452    pub inline_completion_styles: InlineCompletionStyles,
  453    pub unnecessary_code_fade: f32,
  454}
  455
  456impl Default for EditorStyle {
  457    fn default() -> Self {
  458        Self {
  459            background: Hsla::default(),
  460            local_player: PlayerColor::default(),
  461            text: TextStyle::default(),
  462            scrollbar_width: Pixels::default(),
  463            syntax: Default::default(),
  464            // HACK: Status colors don't have a real default.
  465            // We should look into removing the status colors from the editor
  466            // style and retrieve them directly from the theme.
  467            status: StatusColors::dark(),
  468            inlay_hints_style: HighlightStyle::default(),
  469            inline_completion_styles: InlineCompletionStyles {
  470                insertion: HighlightStyle::default(),
  471                whitespace: HighlightStyle::default(),
  472            },
  473            unnecessary_code_fade: Default::default(),
  474        }
  475    }
  476}
  477
  478pub fn make_inlay_hints_style(cx: &mut App) -> HighlightStyle {
  479    let show_background = language_settings::language_settings(None, None, cx)
  480        .inlay_hints
  481        .show_background;
  482
  483    HighlightStyle {
  484        color: Some(cx.theme().status().hint),
  485        background_color: show_background.then(|| cx.theme().status().hint_background),
  486        ..HighlightStyle::default()
  487    }
  488}
  489
  490pub fn make_suggestion_styles(cx: &mut App) -> InlineCompletionStyles {
  491    InlineCompletionStyles {
  492        insertion: HighlightStyle {
  493            color: Some(cx.theme().status().predictive),
  494            ..HighlightStyle::default()
  495        },
  496        whitespace: HighlightStyle {
  497            background_color: Some(cx.theme().status().created_background),
  498            ..HighlightStyle::default()
  499        },
  500    }
  501}
  502
  503type CompletionId = usize;
  504
  505pub(crate) enum EditDisplayMode {
  506    TabAccept,
  507    DiffPopover,
  508    Inline,
  509}
  510
  511enum InlineCompletion {
  512    Edit {
  513        edits: Vec<(Range<Anchor>, String)>,
  514        edit_preview: Option<EditPreview>,
  515        display_mode: EditDisplayMode,
  516        snapshot: BufferSnapshot,
  517    },
  518    Move {
  519        target: Anchor,
  520        snapshot: BufferSnapshot,
  521    },
  522}
  523
  524struct InlineCompletionState {
  525    inlay_ids: Vec<InlayId>,
  526    completion: InlineCompletion,
  527    completion_id: Option<SharedString>,
  528    invalidation_range: Range<Anchor>,
  529}
  530
  531enum EditPredictionSettings {
  532    Disabled,
  533    Enabled {
  534        show_in_menu: bool,
  535        preview_requires_modifier: bool,
  536    },
  537}
  538
  539enum InlineCompletionHighlight {}
  540
  541#[derive(Debug, Clone)]
  542struct InlineDiagnostic {
  543    message: SharedString,
  544    group_id: usize,
  545    is_primary: bool,
  546    start: Point,
  547    severity: DiagnosticSeverity,
  548}
  549
  550pub enum MenuInlineCompletionsPolicy {
  551    Never,
  552    ByProvider,
  553}
  554
  555pub enum EditPredictionPreview {
  556    /// Modifier is not pressed
  557    Inactive { released_too_fast: bool },
  558    /// Modifier pressed
  559    Active {
  560        since: Instant,
  561        previous_scroll_position: Option<ScrollAnchor>,
  562    },
  563}
  564
  565impl EditPredictionPreview {
  566    pub fn released_too_fast(&self) -> bool {
  567        match self {
  568            EditPredictionPreview::Inactive { released_too_fast } => *released_too_fast,
  569            EditPredictionPreview::Active { .. } => false,
  570        }
  571    }
  572
  573    pub fn set_previous_scroll_position(&mut self, scroll_position: Option<ScrollAnchor>) {
  574        if let EditPredictionPreview::Active {
  575            previous_scroll_position,
  576            ..
  577        } = self
  578        {
  579            *previous_scroll_position = scroll_position;
  580        }
  581    }
  582}
  583
  584pub struct ContextMenuOptions {
  585    pub min_entries_visible: usize,
  586    pub max_entries_visible: usize,
  587    pub placement: Option<ContextMenuPlacement>,
  588}
  589
  590#[derive(Debug, Clone, PartialEq, Eq)]
  591pub enum ContextMenuPlacement {
  592    Above,
  593    Below,
  594}
  595
  596#[derive(Copy, Clone, Eq, PartialEq, PartialOrd, Ord, Debug, Default)]
  597struct EditorActionId(usize);
  598
  599impl EditorActionId {
  600    pub fn post_inc(&mut self) -> Self {
  601        let answer = self.0;
  602
  603        *self = Self(answer + 1);
  604
  605        Self(answer)
  606    }
  607}
  608
  609// type GetFieldEditorTheme = dyn Fn(&theme::Theme) -> theme::FieldEditor;
  610// type OverrideTextStyle = dyn Fn(&EditorStyle) -> Option<HighlightStyle>;
  611
  612type BackgroundHighlight = (fn(&ThemeColors) -> Hsla, Arc<[Range<Anchor>]>);
  613type GutterHighlight = (fn(&App) -> Hsla, Arc<[Range<Anchor>]>);
  614
  615#[derive(Default)]
  616struct ScrollbarMarkerState {
  617    scrollbar_size: Size<Pixels>,
  618    dirty: bool,
  619    markers: Arc<[PaintQuad]>,
  620    pending_refresh: Option<Task<Result<()>>>,
  621}
  622
  623impl ScrollbarMarkerState {
  624    fn should_refresh(&self, scrollbar_size: Size<Pixels>) -> bool {
  625        self.pending_refresh.is_none() && (self.scrollbar_size != scrollbar_size || self.dirty)
  626    }
  627}
  628
  629#[derive(Clone, Debug)]
  630struct RunnableTasks {
  631    templates: Vec<(TaskSourceKind, TaskTemplate)>,
  632    offset: multi_buffer::Anchor,
  633    // We need the column at which the task context evaluation should take place (when we're spawning it via gutter).
  634    column: u32,
  635    // Values of all named captures, including those starting with '_'
  636    extra_variables: HashMap<String, String>,
  637    // Full range of the tagged region. We use it to determine which `extra_variables` to grab for context resolution in e.g. a modal.
  638    context_range: Range<BufferOffset>,
  639}
  640
  641impl RunnableTasks {
  642    fn resolve<'a>(
  643        &'a self,
  644        cx: &'a task::TaskContext,
  645    ) -> impl Iterator<Item = (TaskSourceKind, ResolvedTask)> + 'a {
  646        self.templates.iter().filter_map(|(kind, template)| {
  647            template
  648                .resolve_task(&kind.to_id_base(), cx)
  649                .map(|task| (kind.clone(), task))
  650        })
  651    }
  652}
  653
  654#[derive(Clone)]
  655struct ResolvedTasks {
  656    templates: SmallVec<[(TaskSourceKind, ResolvedTask); 1]>,
  657    position: Anchor,
  658}
  659
  660#[derive(Copy, Clone, Debug, PartialEq, PartialOrd)]
  661struct BufferOffset(usize);
  662
  663// Addons allow storing per-editor state in other crates (e.g. Vim)
  664pub trait Addon: 'static {
  665    fn extend_key_context(&self, _: &mut KeyContext, _: &App) {}
  666
  667    fn render_buffer_header_controls(
  668        &self,
  669        _: &ExcerptInfo,
  670        _: &Window,
  671        _: &App,
  672    ) -> Option<AnyElement> {
  673        None
  674    }
  675
  676    fn to_any(&self) -> &dyn std::any::Any;
  677}
  678
  679/// Zed's primary implementation of text input, allowing users to edit a [`MultiBuffer`].
  680///
  681/// See the [module level documentation](self) for more information.
  682pub struct Editor {
  683    focus_handle: FocusHandle,
  684    last_focused_descendant: Option<WeakFocusHandle>,
  685    /// The text buffer being edited
  686    buffer: Entity<MultiBuffer>,
  687    /// Map of how text in the buffer should be displayed.
  688    /// Handles soft wraps, folds, fake inlay text insertions, etc.
  689    pub display_map: Entity<DisplayMap>,
  690    pub selections: SelectionsCollection,
  691    pub scroll_manager: ScrollManager,
  692    /// When inline assist editors are linked, they all render cursors because
  693    /// typing enters text into each of them, even the ones that aren't focused.
  694    pub(crate) show_cursor_when_unfocused: bool,
  695    columnar_selection_tail: Option<Anchor>,
  696    add_selections_state: Option<AddSelectionsState>,
  697    select_next_state: Option<SelectNextState>,
  698    select_prev_state: Option<SelectNextState>,
  699    selection_history: SelectionHistory,
  700    autoclose_regions: Vec<AutocloseRegion>,
  701    snippet_stack: InvalidationStack<SnippetState>,
  702    select_syntax_node_history: SelectSyntaxNodeHistory,
  703    ime_transaction: Option<TransactionId>,
  704    active_diagnostics: Option<ActiveDiagnosticGroup>,
  705    show_inline_diagnostics: bool,
  706    inline_diagnostics_update: Task<()>,
  707    inline_diagnostics_enabled: bool,
  708    inline_diagnostics: Vec<(Anchor, InlineDiagnostic)>,
  709    soft_wrap_mode_override: Option<language_settings::SoftWrap>,
  710    hard_wrap: Option<usize>,
  711
  712    // TODO: make this a access method
  713    pub project: Option<Entity<Project>>,
  714    semantics_provider: Option<Rc<dyn SemanticsProvider>>,
  715    completion_provider: Option<Box<dyn CompletionProvider>>,
  716    collaboration_hub: Option<Box<dyn CollaborationHub>>,
  717    blink_manager: Entity<BlinkManager>,
  718    show_cursor_names: bool,
  719    hovered_cursors: HashMap<HoveredCursor, Task<()>>,
  720    pub show_local_selections: bool,
  721    mode: EditorMode,
  722    show_breadcrumbs: bool,
  723    show_gutter: bool,
  724    show_scrollbars: bool,
  725    show_line_numbers: Option<bool>,
  726    use_relative_line_numbers: Option<bool>,
  727    show_git_diff_gutter: Option<bool>,
  728    show_code_actions: Option<bool>,
  729    show_runnables: Option<bool>,
  730    show_breakpoints: Option<bool>,
  731    show_wrap_guides: Option<bool>,
  732    show_indent_guides: Option<bool>,
  733    placeholder_text: Option<Arc<str>>,
  734    highlight_order: usize,
  735    highlighted_rows: HashMap<TypeId, Vec<RowHighlight>>,
  736    background_highlights: TreeMap<TypeId, BackgroundHighlight>,
  737    gutter_highlights: TreeMap<TypeId, GutterHighlight>,
  738    scrollbar_marker_state: ScrollbarMarkerState,
  739    active_indent_guides_state: ActiveIndentGuidesState,
  740    nav_history: Option<ItemNavHistory>,
  741    context_menu: RefCell<Option<CodeContextMenu>>,
  742    context_menu_options: Option<ContextMenuOptions>,
  743    mouse_context_menu: Option<MouseContextMenu>,
  744    completion_tasks: Vec<(CompletionId, Task<Option<()>>)>,
  745    signature_help_state: SignatureHelpState,
  746    auto_signature_help: Option<bool>,
  747    find_all_references_task_sources: Vec<Anchor>,
  748    next_completion_id: CompletionId,
  749    available_code_actions: Option<(Location, Rc<[AvailableCodeAction]>)>,
  750    code_actions_task: Option<Task<Result<()>>>,
  751    selection_highlight_task: Option<Task<()>>,
  752    document_highlights_task: Option<Task<()>>,
  753    linked_editing_range_task: Option<Task<Option<()>>>,
  754    linked_edit_ranges: linked_editing_ranges::LinkedEditingRanges,
  755    pending_rename: Option<RenameState>,
  756    searchable: bool,
  757    cursor_shape: CursorShape,
  758    current_line_highlight: Option<CurrentLineHighlight>,
  759    collapse_matches: bool,
  760    autoindent_mode: Option<AutoindentMode>,
  761    workspace: Option<(WeakEntity<Workspace>, Option<WorkspaceId>)>,
  762    input_enabled: bool,
  763    use_modal_editing: bool,
  764    read_only: bool,
  765    leader_peer_id: Option<PeerId>,
  766    remote_id: Option<ViewId>,
  767    hover_state: HoverState,
  768    pending_mouse_down: Option<Rc<RefCell<Option<MouseDownEvent>>>>,
  769    gutter_hovered: bool,
  770    hovered_link_state: Option<HoveredLinkState>,
  771    edit_prediction_provider: Option<RegisteredInlineCompletionProvider>,
  772    code_action_providers: Vec<Rc<dyn CodeActionProvider>>,
  773    active_inline_completion: Option<InlineCompletionState>,
  774    /// Used to prevent flickering as the user types while the menu is open
  775    stale_inline_completion_in_menu: Option<InlineCompletionState>,
  776    edit_prediction_settings: EditPredictionSettings,
  777    inline_completions_hidden_for_vim_mode: bool,
  778    show_inline_completions_override: Option<bool>,
  779    menu_inline_completions_policy: MenuInlineCompletionsPolicy,
  780    edit_prediction_preview: EditPredictionPreview,
  781    edit_prediction_indent_conflict: bool,
  782    edit_prediction_requires_modifier_in_indent_conflict: bool,
  783    inlay_hint_cache: InlayHintCache,
  784    next_inlay_id: usize,
  785    _subscriptions: Vec<Subscription>,
  786    pixel_position_of_newest_cursor: Option<gpui::Point<Pixels>>,
  787    gutter_dimensions: GutterDimensions,
  788    style: Option<EditorStyle>,
  789    text_style_refinement: Option<TextStyleRefinement>,
  790    next_editor_action_id: EditorActionId,
  791    editor_actions:
  792        Rc<RefCell<BTreeMap<EditorActionId, Box<dyn Fn(&mut Window, &mut Context<Self>)>>>>,
  793    use_autoclose: bool,
  794    use_auto_surround: bool,
  795    auto_replace_emoji_shortcode: bool,
  796    jsx_tag_auto_close_enabled_in_any_buffer: bool,
  797    show_git_blame_gutter: bool,
  798    show_git_blame_inline: bool,
  799    show_git_blame_inline_delay_task: Option<Task<()>>,
  800    pub git_blame_inline_tooltip: Option<AnyWeakEntity>,
  801    git_blame_inline_enabled: bool,
  802    render_diff_hunk_controls: RenderDiffHunkControlsFn,
  803    serialize_dirty_buffers: bool,
  804    show_selection_menu: Option<bool>,
  805    blame: Option<Entity<GitBlame>>,
  806    blame_subscription: Option<Subscription>,
  807    custom_context_menu: Option<
  808        Box<
  809            dyn 'static
  810                + Fn(
  811                    &mut Self,
  812                    DisplayPoint,
  813                    &mut Window,
  814                    &mut Context<Self>,
  815                ) -> Option<Entity<ui::ContextMenu>>,
  816        >,
  817    >,
  818    last_bounds: Option<Bounds<Pixels>>,
  819    last_position_map: Option<Rc<PositionMap>>,
  820    expect_bounds_change: Option<Bounds<Pixels>>,
  821    tasks: BTreeMap<(BufferId, BufferRow), RunnableTasks>,
  822    tasks_update_task: Option<Task<()>>,
  823    breakpoint_store: Option<Entity<BreakpointStore>>,
  824    /// Allow's a user to create a breakpoint by selecting this indicator
  825    /// It should be None while a user is not hovering over the gutter
  826    /// Otherwise it represents the point that the breakpoint will be shown
  827    gutter_breakpoint_indicator: (Option<(DisplayPoint, bool)>, Option<Task<()>>),
  828    in_project_search: bool,
  829    previous_search_ranges: Option<Arc<[Range<Anchor>]>>,
  830    breadcrumb_header: Option<String>,
  831    focused_block: Option<FocusedBlock>,
  832    next_scroll_position: NextScrollCursorCenterTopBottom,
  833    addons: HashMap<TypeId, Box<dyn Addon>>,
  834    registered_buffers: HashMap<BufferId, OpenLspBufferHandle>,
  835    load_diff_task: Option<Shared<Task<()>>>,
  836    selection_mark_mode: bool,
  837    toggle_fold_multiple_buffers: Task<()>,
  838    _scroll_cursor_center_top_bottom_task: Task<()>,
  839    serialize_selections: Task<()>,
  840    serialize_folds: Task<()>,
  841    mouse_cursor_hidden: bool,
  842    hide_mouse_mode: HideMouseMode,
  843}
  844
  845#[derive(Copy, Clone, Debug, PartialEq, Eq, Default)]
  846enum NextScrollCursorCenterTopBottom {
  847    #[default]
  848    Center,
  849    Top,
  850    Bottom,
  851}
  852
  853impl NextScrollCursorCenterTopBottom {
  854    fn next(&self) -> Self {
  855        match self {
  856            Self::Center => Self::Top,
  857            Self::Top => Self::Bottom,
  858            Self::Bottom => Self::Center,
  859        }
  860    }
  861}
  862
  863#[derive(Clone)]
  864pub struct EditorSnapshot {
  865    pub mode: EditorMode,
  866    show_gutter: bool,
  867    show_line_numbers: Option<bool>,
  868    show_git_diff_gutter: Option<bool>,
  869    show_code_actions: Option<bool>,
  870    show_runnables: Option<bool>,
  871    show_breakpoints: Option<bool>,
  872    git_blame_gutter_max_author_length: Option<usize>,
  873    pub display_snapshot: DisplaySnapshot,
  874    pub placeholder_text: Option<Arc<str>>,
  875    is_focused: bool,
  876    scroll_anchor: ScrollAnchor,
  877    ongoing_scroll: OngoingScroll,
  878    current_line_highlight: CurrentLineHighlight,
  879    gutter_hovered: bool,
  880}
  881
  882#[derive(Default, Debug, Clone, Copy)]
  883pub struct GutterDimensions {
  884    pub left_padding: Pixels,
  885    pub right_padding: Pixels,
  886    pub width: Pixels,
  887    pub margin: Pixels,
  888    pub git_blame_entries_width: Option<Pixels>,
  889}
  890
  891impl GutterDimensions {
  892    /// The full width of the space taken up by the gutter.
  893    pub fn full_width(&self) -> Pixels {
  894        self.margin + self.width
  895    }
  896
  897    /// The width of the space reserved for the fold indicators,
  898    /// use alongside 'justify_end' and `gutter_width` to
  899    /// right align content with the line numbers
  900    pub fn fold_area_width(&self) -> Pixels {
  901        self.margin + self.right_padding
  902    }
  903}
  904
  905#[derive(Debug)]
  906pub struct RemoteSelection {
  907    pub replica_id: ReplicaId,
  908    pub selection: Selection<Anchor>,
  909    pub cursor_shape: CursorShape,
  910    pub peer_id: PeerId,
  911    pub line_mode: bool,
  912    pub participant_index: Option<ParticipantIndex>,
  913    pub user_name: Option<SharedString>,
  914}
  915
  916#[derive(Clone, Debug)]
  917struct SelectionHistoryEntry {
  918    selections: Arc<[Selection<Anchor>]>,
  919    select_next_state: Option<SelectNextState>,
  920    select_prev_state: Option<SelectNextState>,
  921    add_selections_state: Option<AddSelectionsState>,
  922}
  923
  924enum SelectionHistoryMode {
  925    Normal,
  926    Undoing,
  927    Redoing,
  928}
  929
  930#[derive(Clone, PartialEq, Eq, Hash)]
  931struct HoveredCursor {
  932    replica_id: u16,
  933    selection_id: usize,
  934}
  935
  936impl Default for SelectionHistoryMode {
  937    fn default() -> Self {
  938        Self::Normal
  939    }
  940}
  941
  942#[derive(Default)]
  943struct SelectionHistory {
  944    #[allow(clippy::type_complexity)]
  945    selections_by_transaction:
  946        HashMap<TransactionId, (Arc<[Selection<Anchor>]>, Option<Arc<[Selection<Anchor>]>>)>,
  947    mode: SelectionHistoryMode,
  948    undo_stack: VecDeque<SelectionHistoryEntry>,
  949    redo_stack: VecDeque<SelectionHistoryEntry>,
  950}
  951
  952impl SelectionHistory {
  953    fn insert_transaction(
  954        &mut self,
  955        transaction_id: TransactionId,
  956        selections: Arc<[Selection<Anchor>]>,
  957    ) {
  958        self.selections_by_transaction
  959            .insert(transaction_id, (selections, None));
  960    }
  961
  962    #[allow(clippy::type_complexity)]
  963    fn transaction(
  964        &self,
  965        transaction_id: TransactionId,
  966    ) -> Option<&(Arc<[Selection<Anchor>]>, Option<Arc<[Selection<Anchor>]>>)> {
  967        self.selections_by_transaction.get(&transaction_id)
  968    }
  969
  970    #[allow(clippy::type_complexity)]
  971    fn transaction_mut(
  972        &mut self,
  973        transaction_id: TransactionId,
  974    ) -> Option<&mut (Arc<[Selection<Anchor>]>, Option<Arc<[Selection<Anchor>]>>)> {
  975        self.selections_by_transaction.get_mut(&transaction_id)
  976    }
  977
  978    fn push(&mut self, entry: SelectionHistoryEntry) {
  979        if !entry.selections.is_empty() {
  980            match self.mode {
  981                SelectionHistoryMode::Normal => {
  982                    self.push_undo(entry);
  983                    self.redo_stack.clear();
  984                }
  985                SelectionHistoryMode::Undoing => self.push_redo(entry),
  986                SelectionHistoryMode::Redoing => self.push_undo(entry),
  987            }
  988        }
  989    }
  990
  991    fn push_undo(&mut self, entry: SelectionHistoryEntry) {
  992        if self
  993            .undo_stack
  994            .back()
  995            .map_or(true, |e| e.selections != entry.selections)
  996        {
  997            self.undo_stack.push_back(entry);
  998            if self.undo_stack.len() > MAX_SELECTION_HISTORY_LEN {
  999                self.undo_stack.pop_front();
 1000            }
 1001        }
 1002    }
 1003
 1004    fn push_redo(&mut self, entry: SelectionHistoryEntry) {
 1005        if self
 1006            .redo_stack
 1007            .back()
 1008            .map_or(true, |e| e.selections != entry.selections)
 1009        {
 1010            self.redo_stack.push_back(entry);
 1011            if self.redo_stack.len() > MAX_SELECTION_HISTORY_LEN {
 1012                self.redo_stack.pop_front();
 1013            }
 1014        }
 1015    }
 1016}
 1017
 1018struct RowHighlight {
 1019    index: usize,
 1020    range: Range<Anchor>,
 1021    color: Hsla,
 1022    should_autoscroll: bool,
 1023}
 1024
 1025#[derive(Clone, Debug)]
 1026struct AddSelectionsState {
 1027    above: bool,
 1028    stack: Vec<usize>,
 1029}
 1030
 1031#[derive(Clone)]
 1032struct SelectNextState {
 1033    query: AhoCorasick,
 1034    wordwise: bool,
 1035    done: bool,
 1036}
 1037
 1038impl std::fmt::Debug for SelectNextState {
 1039    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
 1040        f.debug_struct(std::any::type_name::<Self>())
 1041            .field("wordwise", &self.wordwise)
 1042            .field("done", &self.done)
 1043            .finish()
 1044    }
 1045}
 1046
 1047#[derive(Debug)]
 1048struct AutocloseRegion {
 1049    selection_id: usize,
 1050    range: Range<Anchor>,
 1051    pair: BracketPair,
 1052}
 1053
 1054#[derive(Debug)]
 1055struct SnippetState {
 1056    ranges: Vec<Vec<Range<Anchor>>>,
 1057    active_index: usize,
 1058    choices: Vec<Option<Vec<String>>>,
 1059}
 1060
 1061#[doc(hidden)]
 1062pub struct RenameState {
 1063    pub range: Range<Anchor>,
 1064    pub old_name: Arc<str>,
 1065    pub editor: Entity<Editor>,
 1066    block_id: CustomBlockId,
 1067}
 1068
 1069struct InvalidationStack<T>(Vec<T>);
 1070
 1071struct RegisteredInlineCompletionProvider {
 1072    provider: Arc<dyn InlineCompletionProviderHandle>,
 1073    _subscription: Subscription,
 1074}
 1075
 1076#[derive(Debug, PartialEq, Eq)]
 1077struct ActiveDiagnosticGroup {
 1078    primary_range: Range<Anchor>,
 1079    primary_message: String,
 1080    group_id: usize,
 1081    blocks: HashMap<CustomBlockId, Diagnostic>,
 1082    is_valid: bool,
 1083}
 1084
 1085#[derive(Serialize, Deserialize, Clone, Debug)]
 1086pub struct ClipboardSelection {
 1087    /// The number of bytes in this selection.
 1088    pub len: usize,
 1089    /// Whether this was a full-line selection.
 1090    pub is_entire_line: bool,
 1091    /// The indentation of the first line when this content was originally copied.
 1092    pub first_line_indent: u32,
 1093}
 1094
 1095// selections, scroll behavior, was newest selection reversed
 1096type SelectSyntaxNodeHistoryState = (
 1097    Box<[Selection<usize>]>,
 1098    SelectSyntaxNodeScrollBehavior,
 1099    bool,
 1100);
 1101
 1102#[derive(Default)]
 1103struct SelectSyntaxNodeHistory {
 1104    stack: Vec<SelectSyntaxNodeHistoryState>,
 1105    // disable temporarily to allow changing selections without losing the stack
 1106    pub disable_clearing: bool,
 1107}
 1108
 1109impl SelectSyntaxNodeHistory {
 1110    pub fn try_clear(&mut self) {
 1111        if !self.disable_clearing {
 1112            self.stack.clear();
 1113        }
 1114    }
 1115
 1116    pub fn push(&mut self, selection: SelectSyntaxNodeHistoryState) {
 1117        self.stack.push(selection);
 1118    }
 1119
 1120    pub fn pop(&mut self) -> Option<SelectSyntaxNodeHistoryState> {
 1121        self.stack.pop()
 1122    }
 1123}
 1124
 1125enum SelectSyntaxNodeScrollBehavior {
 1126    CursorTop,
 1127    FitSelection,
 1128    CursorBottom,
 1129}
 1130
 1131#[derive(Debug)]
 1132pub(crate) struct NavigationData {
 1133    cursor_anchor: Anchor,
 1134    cursor_position: Point,
 1135    scroll_anchor: ScrollAnchor,
 1136    scroll_top_row: u32,
 1137}
 1138
 1139#[derive(Debug, Clone, Copy, PartialEq, Eq)]
 1140pub enum GotoDefinitionKind {
 1141    Symbol,
 1142    Declaration,
 1143    Type,
 1144    Implementation,
 1145}
 1146
 1147#[derive(Debug, Clone)]
 1148enum InlayHintRefreshReason {
 1149    ModifiersChanged(bool),
 1150    Toggle(bool),
 1151    SettingsChange(InlayHintSettings),
 1152    NewLinesShown,
 1153    BufferEdited(HashSet<Arc<Language>>),
 1154    RefreshRequested,
 1155    ExcerptsRemoved(Vec<ExcerptId>),
 1156}
 1157
 1158impl InlayHintRefreshReason {
 1159    fn description(&self) -> &'static str {
 1160        match self {
 1161            Self::ModifiersChanged(_) => "modifiers changed",
 1162            Self::Toggle(_) => "toggle",
 1163            Self::SettingsChange(_) => "settings change",
 1164            Self::NewLinesShown => "new lines shown",
 1165            Self::BufferEdited(_) => "buffer edited",
 1166            Self::RefreshRequested => "refresh requested",
 1167            Self::ExcerptsRemoved(_) => "excerpts removed",
 1168        }
 1169    }
 1170}
 1171
 1172pub enum FormatTarget {
 1173    Buffers,
 1174    Ranges(Vec<Range<MultiBufferPoint>>),
 1175}
 1176
 1177pub(crate) struct FocusedBlock {
 1178    id: BlockId,
 1179    focus_handle: WeakFocusHandle,
 1180}
 1181
 1182#[derive(Clone)]
 1183enum JumpData {
 1184    MultiBufferRow {
 1185        row: MultiBufferRow,
 1186        line_offset_from_top: u32,
 1187    },
 1188    MultiBufferPoint {
 1189        excerpt_id: ExcerptId,
 1190        position: Point,
 1191        anchor: text::Anchor,
 1192        line_offset_from_top: u32,
 1193    },
 1194}
 1195
 1196pub enum MultibufferSelectionMode {
 1197    First,
 1198    All,
 1199}
 1200
 1201#[derive(Clone, Copy, Debug, Default)]
 1202pub struct RewrapOptions {
 1203    pub override_language_settings: bool,
 1204    pub preserve_existing_whitespace: bool,
 1205}
 1206
 1207impl Editor {
 1208    pub fn single_line(window: &mut Window, cx: &mut Context<Self>) -> Self {
 1209        let buffer = cx.new(|cx| Buffer::local("", cx));
 1210        let buffer = cx.new(|cx| MultiBuffer::singleton(buffer, cx));
 1211        Self::new(
 1212            EditorMode::SingleLine { auto_width: false },
 1213            buffer,
 1214            None,
 1215            window,
 1216            cx,
 1217        )
 1218    }
 1219
 1220    pub fn multi_line(window: &mut Window, cx: &mut Context<Self>) -> Self {
 1221        let buffer = cx.new(|cx| Buffer::local("", cx));
 1222        let buffer = cx.new(|cx| MultiBuffer::singleton(buffer, cx));
 1223        Self::new(EditorMode::full(), buffer, None, window, cx)
 1224    }
 1225
 1226    pub fn auto_width(window: &mut Window, cx: &mut Context<Self>) -> Self {
 1227        let buffer = cx.new(|cx| Buffer::local("", cx));
 1228        let buffer = cx.new(|cx| MultiBuffer::singleton(buffer, cx));
 1229        Self::new(
 1230            EditorMode::SingleLine { auto_width: true },
 1231            buffer,
 1232            None,
 1233            window,
 1234            cx,
 1235        )
 1236    }
 1237
 1238    pub fn auto_height(max_lines: usize, window: &mut Window, cx: &mut Context<Self>) -> Self {
 1239        let buffer = cx.new(|cx| Buffer::local("", cx));
 1240        let buffer = cx.new(|cx| MultiBuffer::singleton(buffer, cx));
 1241        Self::new(
 1242            EditorMode::AutoHeight { max_lines },
 1243            buffer,
 1244            None,
 1245            window,
 1246            cx,
 1247        )
 1248    }
 1249
 1250    pub fn for_buffer(
 1251        buffer: Entity<Buffer>,
 1252        project: Option<Entity<Project>>,
 1253        window: &mut Window,
 1254        cx: &mut Context<Self>,
 1255    ) -> Self {
 1256        let buffer = cx.new(|cx| MultiBuffer::singleton(buffer, cx));
 1257        Self::new(EditorMode::full(), buffer, project, window, cx)
 1258    }
 1259
 1260    pub fn for_multibuffer(
 1261        buffer: Entity<MultiBuffer>,
 1262        project: Option<Entity<Project>>,
 1263        window: &mut Window,
 1264        cx: &mut Context<Self>,
 1265    ) -> Self {
 1266        Self::new(EditorMode::full(), buffer, project, window, cx)
 1267    }
 1268
 1269    pub fn clone(&self, window: &mut Window, cx: &mut Context<Self>) -> Self {
 1270        let mut clone = Self::new(
 1271            self.mode,
 1272            self.buffer.clone(),
 1273            self.project.clone(),
 1274            window,
 1275            cx,
 1276        );
 1277        self.display_map.update(cx, |display_map, cx| {
 1278            let snapshot = display_map.snapshot(cx);
 1279            clone.display_map.update(cx, |display_map, cx| {
 1280                display_map.set_state(&snapshot, cx);
 1281            });
 1282        });
 1283        clone.folds_did_change(cx);
 1284        clone.selections.clone_state(&self.selections);
 1285        clone.scroll_manager.clone_state(&self.scroll_manager);
 1286        clone.searchable = self.searchable;
 1287        clone.read_only = self.read_only;
 1288        clone
 1289    }
 1290
 1291    pub fn new(
 1292        mode: EditorMode,
 1293        buffer: Entity<MultiBuffer>,
 1294        project: Option<Entity<Project>>,
 1295        window: &mut Window,
 1296        cx: &mut Context<Self>,
 1297    ) -> Self {
 1298        let style = window.text_style();
 1299        let font_size = style.font_size.to_pixels(window.rem_size());
 1300        let editor = cx.entity().downgrade();
 1301        let fold_placeholder = FoldPlaceholder {
 1302            constrain_width: true,
 1303            render: Arc::new(move |fold_id, fold_range, cx| {
 1304                let editor = editor.clone();
 1305                div()
 1306                    .id(fold_id)
 1307                    .bg(cx.theme().colors().ghost_element_background)
 1308                    .hover(|style| style.bg(cx.theme().colors().ghost_element_hover))
 1309                    .active(|style| style.bg(cx.theme().colors().ghost_element_active))
 1310                    .rounded_xs()
 1311                    .size_full()
 1312                    .cursor_pointer()
 1313                    .child("")
 1314                    .on_mouse_down(MouseButton::Left, |_, _, cx| cx.stop_propagation())
 1315                    .on_click(move |_, _window, cx| {
 1316                        editor
 1317                            .update(cx, |editor, cx| {
 1318                                editor.unfold_ranges(
 1319                                    &[fold_range.start..fold_range.end],
 1320                                    true,
 1321                                    false,
 1322                                    cx,
 1323                                );
 1324                                cx.stop_propagation();
 1325                            })
 1326                            .ok();
 1327                    })
 1328                    .into_any()
 1329            }),
 1330            merge_adjacent: true,
 1331            ..Default::default()
 1332        };
 1333        let display_map = cx.new(|cx| {
 1334            DisplayMap::new(
 1335                buffer.clone(),
 1336                style.font(),
 1337                font_size,
 1338                None,
 1339                FILE_HEADER_HEIGHT,
 1340                MULTI_BUFFER_EXCERPT_HEADER_HEIGHT,
 1341                fold_placeholder,
 1342                cx,
 1343            )
 1344        });
 1345
 1346        let selections = SelectionsCollection::new(display_map.clone(), buffer.clone());
 1347
 1348        let blink_manager = cx.new(|cx| BlinkManager::new(CURSOR_BLINK_INTERVAL, cx));
 1349
 1350        let soft_wrap_mode_override = matches!(mode, EditorMode::SingleLine { .. })
 1351            .then(|| language_settings::SoftWrap::None);
 1352
 1353        let mut project_subscriptions = Vec::new();
 1354        if mode.is_full() {
 1355            if let Some(project) = project.as_ref() {
 1356                project_subscriptions.push(cx.subscribe_in(
 1357                    project,
 1358                    window,
 1359                    |editor, _, event, window, cx| match event {
 1360                        project::Event::RefreshCodeLens => {
 1361                            // we always query lens with actions, without storing them, always refreshing them
 1362                        }
 1363                        project::Event::RefreshInlayHints => {
 1364                            editor
 1365                                .refresh_inlay_hints(InlayHintRefreshReason::RefreshRequested, cx);
 1366                        }
 1367                        project::Event::SnippetEdit(id, snippet_edits) => {
 1368                            if let Some(buffer) = editor.buffer.read(cx).buffer(*id) {
 1369                                let focus_handle = editor.focus_handle(cx);
 1370                                if focus_handle.is_focused(window) {
 1371                                    let snapshot = buffer.read(cx).snapshot();
 1372                                    for (range, snippet) in snippet_edits {
 1373                                        let editor_range =
 1374                                            language::range_from_lsp(*range).to_offset(&snapshot);
 1375                                        editor
 1376                                            .insert_snippet(
 1377                                                &[editor_range],
 1378                                                snippet.clone(),
 1379                                                window,
 1380                                                cx,
 1381                                            )
 1382                                            .ok();
 1383                                    }
 1384                                }
 1385                            }
 1386                        }
 1387                        _ => {}
 1388                    },
 1389                ));
 1390                if let Some(task_inventory) = project
 1391                    .read(cx)
 1392                    .task_store()
 1393                    .read(cx)
 1394                    .task_inventory()
 1395                    .cloned()
 1396                {
 1397                    project_subscriptions.push(cx.observe_in(
 1398                        &task_inventory,
 1399                        window,
 1400                        |editor, _, window, cx| {
 1401                            editor.tasks_update_task = Some(editor.refresh_runnables(window, cx));
 1402                        },
 1403                    ));
 1404                };
 1405
 1406                project_subscriptions.push(cx.subscribe_in(
 1407                    &project.read(cx).breakpoint_store(),
 1408                    window,
 1409                    |editor, _, event, window, cx| match event {
 1410                        BreakpointStoreEvent::ActiveDebugLineChanged => {
 1411                            if editor.go_to_active_debug_line(window, cx) {
 1412                                cx.stop_propagation();
 1413                            }
 1414                        }
 1415                        _ => {}
 1416                    },
 1417                ));
 1418            }
 1419        }
 1420
 1421        let buffer_snapshot = buffer.read(cx).snapshot(cx);
 1422
 1423        let inlay_hint_settings =
 1424            inlay_hint_settings(selections.newest_anchor().head(), &buffer_snapshot, cx);
 1425        let focus_handle = cx.focus_handle();
 1426        cx.on_focus(&focus_handle, window, Self::handle_focus)
 1427            .detach();
 1428        cx.on_focus_in(&focus_handle, window, Self::handle_focus_in)
 1429            .detach();
 1430        cx.on_focus_out(&focus_handle, window, Self::handle_focus_out)
 1431            .detach();
 1432        cx.on_blur(&focus_handle, window, Self::handle_blur)
 1433            .detach();
 1434
 1435        let show_indent_guides = if matches!(mode, EditorMode::SingleLine { .. }) {
 1436            Some(false)
 1437        } else {
 1438            None
 1439        };
 1440
 1441        let breakpoint_store = match (mode, project.as_ref()) {
 1442            (EditorMode::Full { .. }, Some(project)) => Some(project.read(cx).breakpoint_store()),
 1443            _ => None,
 1444        };
 1445
 1446        let mut code_action_providers = Vec::new();
 1447        let mut load_uncommitted_diff = None;
 1448        if let Some(project) = project.clone() {
 1449            load_uncommitted_diff = Some(
 1450                get_uncommitted_diff_for_buffer(
 1451                    &project,
 1452                    buffer.read(cx).all_buffers(),
 1453                    buffer.clone(),
 1454                    cx,
 1455                )
 1456                .shared(),
 1457            );
 1458            code_action_providers.push(Rc::new(project) as Rc<_>);
 1459        }
 1460
 1461        let mut this = Self {
 1462            focus_handle,
 1463            show_cursor_when_unfocused: false,
 1464            last_focused_descendant: None,
 1465            buffer: buffer.clone(),
 1466            display_map: display_map.clone(),
 1467            selections,
 1468            scroll_manager: ScrollManager::new(cx),
 1469            columnar_selection_tail: None,
 1470            add_selections_state: None,
 1471            select_next_state: None,
 1472            select_prev_state: None,
 1473            selection_history: Default::default(),
 1474            autoclose_regions: Default::default(),
 1475            snippet_stack: Default::default(),
 1476            select_syntax_node_history: SelectSyntaxNodeHistory::default(),
 1477            ime_transaction: Default::default(),
 1478            active_diagnostics: None,
 1479            show_inline_diagnostics: ProjectSettings::get_global(cx).diagnostics.inline.enabled,
 1480            inline_diagnostics_update: Task::ready(()),
 1481            inline_diagnostics: Vec::new(),
 1482            soft_wrap_mode_override,
 1483            hard_wrap: None,
 1484            completion_provider: project.clone().map(|project| Box::new(project) as _),
 1485            semantics_provider: project.clone().map(|project| Rc::new(project) as _),
 1486            collaboration_hub: project.clone().map(|project| Box::new(project) as _),
 1487            project,
 1488            blink_manager: blink_manager.clone(),
 1489            show_local_selections: true,
 1490            show_scrollbars: true,
 1491            mode,
 1492            show_breadcrumbs: EditorSettings::get_global(cx).toolbar.breadcrumbs,
 1493            show_gutter: mode.is_full(),
 1494            show_line_numbers: None,
 1495            use_relative_line_numbers: None,
 1496            show_git_diff_gutter: None,
 1497            show_code_actions: None,
 1498            show_runnables: None,
 1499            show_breakpoints: None,
 1500            show_wrap_guides: None,
 1501            show_indent_guides,
 1502            placeholder_text: None,
 1503            highlight_order: 0,
 1504            highlighted_rows: HashMap::default(),
 1505            background_highlights: Default::default(),
 1506            gutter_highlights: TreeMap::default(),
 1507            scrollbar_marker_state: ScrollbarMarkerState::default(),
 1508            active_indent_guides_state: ActiveIndentGuidesState::default(),
 1509            nav_history: None,
 1510            context_menu: RefCell::new(None),
 1511            context_menu_options: None,
 1512            mouse_context_menu: None,
 1513            completion_tasks: Default::default(),
 1514            signature_help_state: SignatureHelpState::default(),
 1515            auto_signature_help: None,
 1516            find_all_references_task_sources: Vec::new(),
 1517            next_completion_id: 0,
 1518            next_inlay_id: 0,
 1519            code_action_providers,
 1520            available_code_actions: Default::default(),
 1521            code_actions_task: Default::default(),
 1522            selection_highlight_task: Default::default(),
 1523            document_highlights_task: Default::default(),
 1524            linked_editing_range_task: Default::default(),
 1525            pending_rename: Default::default(),
 1526            searchable: true,
 1527            cursor_shape: EditorSettings::get_global(cx)
 1528                .cursor_shape
 1529                .unwrap_or_default(),
 1530            current_line_highlight: None,
 1531            autoindent_mode: Some(AutoindentMode::EachLine),
 1532            collapse_matches: false,
 1533            workspace: None,
 1534            input_enabled: true,
 1535            use_modal_editing: mode.is_full(),
 1536            read_only: false,
 1537            use_autoclose: true,
 1538            use_auto_surround: true,
 1539            auto_replace_emoji_shortcode: false,
 1540            jsx_tag_auto_close_enabled_in_any_buffer: false,
 1541            leader_peer_id: None,
 1542            remote_id: None,
 1543            hover_state: Default::default(),
 1544            pending_mouse_down: None,
 1545            hovered_link_state: Default::default(),
 1546            edit_prediction_provider: None,
 1547            active_inline_completion: None,
 1548            stale_inline_completion_in_menu: None,
 1549            edit_prediction_preview: EditPredictionPreview::Inactive {
 1550                released_too_fast: false,
 1551            },
 1552            inline_diagnostics_enabled: mode.is_full(),
 1553            inlay_hint_cache: InlayHintCache::new(inlay_hint_settings),
 1554
 1555            gutter_hovered: false,
 1556            pixel_position_of_newest_cursor: None,
 1557            last_bounds: None,
 1558            last_position_map: None,
 1559            expect_bounds_change: None,
 1560            gutter_dimensions: GutterDimensions::default(),
 1561            style: None,
 1562            show_cursor_names: false,
 1563            hovered_cursors: Default::default(),
 1564            next_editor_action_id: EditorActionId::default(),
 1565            editor_actions: Rc::default(),
 1566            inline_completions_hidden_for_vim_mode: false,
 1567            show_inline_completions_override: None,
 1568            menu_inline_completions_policy: MenuInlineCompletionsPolicy::ByProvider,
 1569            edit_prediction_settings: EditPredictionSettings::Disabled,
 1570            edit_prediction_indent_conflict: false,
 1571            edit_prediction_requires_modifier_in_indent_conflict: true,
 1572            custom_context_menu: None,
 1573            show_git_blame_gutter: false,
 1574            show_git_blame_inline: false,
 1575            show_selection_menu: None,
 1576            show_git_blame_inline_delay_task: None,
 1577            git_blame_inline_tooltip: None,
 1578            git_blame_inline_enabled: ProjectSettings::get_global(cx).git.inline_blame_enabled(),
 1579            render_diff_hunk_controls: Arc::new(render_diff_hunk_controls),
 1580            serialize_dirty_buffers: ProjectSettings::get_global(cx)
 1581                .session
 1582                .restore_unsaved_buffers,
 1583            blame: None,
 1584            blame_subscription: None,
 1585            tasks: Default::default(),
 1586
 1587            breakpoint_store,
 1588            gutter_breakpoint_indicator: (None, None),
 1589            _subscriptions: vec![
 1590                cx.observe(&buffer, Self::on_buffer_changed),
 1591                cx.subscribe_in(&buffer, window, Self::on_buffer_event),
 1592                cx.observe_in(&display_map, window, Self::on_display_map_changed),
 1593                cx.observe(&blink_manager, |_, _, cx| cx.notify()),
 1594                cx.observe_global_in::<SettingsStore>(window, Self::settings_changed),
 1595                observe_buffer_font_size_adjustment(cx, |_, cx| cx.notify()),
 1596                cx.observe_window_activation(window, |editor, window, cx| {
 1597                    let active = window.is_window_active();
 1598                    editor.blink_manager.update(cx, |blink_manager, cx| {
 1599                        if active {
 1600                            blink_manager.enable(cx);
 1601                        } else {
 1602                            blink_manager.disable(cx);
 1603                        }
 1604                    });
 1605                }),
 1606            ],
 1607            tasks_update_task: None,
 1608            linked_edit_ranges: Default::default(),
 1609            in_project_search: false,
 1610            previous_search_ranges: None,
 1611            breadcrumb_header: None,
 1612            focused_block: None,
 1613            next_scroll_position: NextScrollCursorCenterTopBottom::default(),
 1614            addons: HashMap::default(),
 1615            registered_buffers: HashMap::default(),
 1616            _scroll_cursor_center_top_bottom_task: Task::ready(()),
 1617            selection_mark_mode: false,
 1618            toggle_fold_multiple_buffers: Task::ready(()),
 1619            serialize_selections: Task::ready(()),
 1620            serialize_folds: Task::ready(()),
 1621            text_style_refinement: None,
 1622            load_diff_task: load_uncommitted_diff,
 1623            mouse_cursor_hidden: false,
 1624            hide_mouse_mode: EditorSettings::get_global(cx)
 1625                .hide_mouse
 1626                .unwrap_or_default(),
 1627        };
 1628        if let Some(breakpoints) = this.breakpoint_store.as_ref() {
 1629            this._subscriptions
 1630                .push(cx.observe(breakpoints, |_, _, cx| {
 1631                    cx.notify();
 1632                }));
 1633        }
 1634        this.tasks_update_task = Some(this.refresh_runnables(window, cx));
 1635        this._subscriptions.extend(project_subscriptions);
 1636
 1637        this._subscriptions.push(cx.subscribe_in(
 1638            &cx.entity(),
 1639            window,
 1640            |editor, _, e: &EditorEvent, window, cx| {
 1641                if let EditorEvent::SelectionsChanged { local } = e {
 1642                    if *local {
 1643                        let new_anchor = editor.scroll_manager.anchor();
 1644                        let snapshot = editor.snapshot(window, cx);
 1645                        editor.update_restoration_data(cx, move |data| {
 1646                            data.scroll_position = (
 1647                                new_anchor.top_row(&snapshot.buffer_snapshot),
 1648                                new_anchor.offset,
 1649                            );
 1650                        });
 1651                    }
 1652                }
 1653            },
 1654        ));
 1655
 1656        this.end_selection(window, cx);
 1657        this.scroll_manager.show_scrollbars(window, cx);
 1658        jsx_tag_auto_close::refresh_enabled_in_any_buffer(&mut this, &buffer, cx);
 1659
 1660        if mode.is_full() {
 1661            let should_auto_hide_scrollbars = cx.should_auto_hide_scrollbars();
 1662            cx.set_global(ScrollbarAutoHide(should_auto_hide_scrollbars));
 1663
 1664            if this.git_blame_inline_enabled {
 1665                this.git_blame_inline_enabled = true;
 1666                this.start_git_blame_inline(false, window, cx);
 1667            }
 1668
 1669            this.go_to_active_debug_line(window, cx);
 1670
 1671            if let Some(buffer) = buffer.read(cx).as_singleton() {
 1672                if let Some(project) = this.project.as_ref() {
 1673                    let handle = project.update(cx, |project, cx| {
 1674                        project.register_buffer_with_language_servers(&buffer, cx)
 1675                    });
 1676                    this.registered_buffers
 1677                        .insert(buffer.read(cx).remote_id(), handle);
 1678                }
 1679            }
 1680        }
 1681
 1682        this.report_editor_event("Editor Opened", None, cx);
 1683        this
 1684    }
 1685
 1686    pub fn deploy_mouse_context_menu(
 1687        &mut self,
 1688        position: gpui::Point<Pixels>,
 1689        context_menu: Entity<ContextMenu>,
 1690        window: &mut Window,
 1691        cx: &mut Context<Self>,
 1692    ) {
 1693        self.mouse_context_menu = Some(MouseContextMenu::new(
 1694            crate::mouse_context_menu::MenuPosition::PinnedToScreen(position),
 1695            context_menu,
 1696            window,
 1697            cx,
 1698        ));
 1699    }
 1700
 1701    pub fn mouse_menu_is_focused(&self, window: &Window, cx: &App) -> bool {
 1702        self.mouse_context_menu
 1703            .as_ref()
 1704            .is_some_and(|menu| menu.context_menu.focus_handle(cx).is_focused(window))
 1705    }
 1706
 1707    fn key_context(&self, window: &Window, cx: &App) -> KeyContext {
 1708        self.key_context_internal(self.has_active_inline_completion(), window, cx)
 1709    }
 1710
 1711    fn key_context_internal(
 1712        &self,
 1713        has_active_edit_prediction: bool,
 1714        window: &Window,
 1715        cx: &App,
 1716    ) -> KeyContext {
 1717        let mut key_context = KeyContext::new_with_defaults();
 1718        key_context.add("Editor");
 1719        let mode = match self.mode {
 1720            EditorMode::SingleLine { .. } => "single_line",
 1721            EditorMode::AutoHeight { .. } => "auto_height",
 1722            EditorMode::Full { .. } => "full",
 1723        };
 1724
 1725        if EditorSettings::jupyter_enabled(cx) {
 1726            key_context.add("jupyter");
 1727        }
 1728
 1729        key_context.set("mode", mode);
 1730        if self.pending_rename.is_some() {
 1731            key_context.add("renaming");
 1732        }
 1733
 1734        match self.context_menu.borrow().as_ref() {
 1735            Some(CodeContextMenu::Completions(_)) => {
 1736                key_context.add("menu");
 1737                key_context.add("showing_completions");
 1738            }
 1739            Some(CodeContextMenu::CodeActions(_)) => {
 1740                key_context.add("menu");
 1741                key_context.add("showing_code_actions")
 1742            }
 1743            None => {}
 1744        }
 1745
 1746        // Disable vim contexts when a sub-editor (e.g. rename/inline assistant) is focused.
 1747        if !self.focus_handle(cx).contains_focused(window, cx)
 1748            || (self.is_focused(window) || self.mouse_menu_is_focused(window, cx))
 1749        {
 1750            for addon in self.addons.values() {
 1751                addon.extend_key_context(&mut key_context, cx)
 1752            }
 1753        }
 1754
 1755        if let Some(singleton_buffer) = self.buffer.read(cx).as_singleton() {
 1756            if let Some(extension) = singleton_buffer
 1757                .read(cx)
 1758                .file()
 1759                .and_then(|file| file.path().extension()?.to_str())
 1760            {
 1761                key_context.set("extension", extension.to_string());
 1762            }
 1763        } else {
 1764            key_context.add("multibuffer");
 1765        }
 1766
 1767        if has_active_edit_prediction {
 1768            if self.edit_prediction_in_conflict() {
 1769                key_context.add(EDIT_PREDICTION_CONFLICT_KEY_CONTEXT);
 1770            } else {
 1771                key_context.add(EDIT_PREDICTION_KEY_CONTEXT);
 1772                key_context.add("copilot_suggestion");
 1773            }
 1774        }
 1775
 1776        if self.selection_mark_mode {
 1777            key_context.add("selection_mode");
 1778        }
 1779
 1780        key_context
 1781    }
 1782
 1783    pub fn hide_mouse_cursor(&mut self, origin: &HideMouseCursorOrigin) {
 1784        self.mouse_cursor_hidden = match origin {
 1785            HideMouseCursorOrigin::TypingAction => {
 1786                matches!(
 1787                    self.hide_mouse_mode,
 1788                    HideMouseMode::OnTyping | HideMouseMode::OnTypingAndMovement
 1789                )
 1790            }
 1791            HideMouseCursorOrigin::MovementAction => {
 1792                matches!(self.hide_mouse_mode, HideMouseMode::OnTypingAndMovement)
 1793            }
 1794        };
 1795    }
 1796
 1797    pub fn edit_prediction_in_conflict(&self) -> bool {
 1798        if !self.show_edit_predictions_in_menu() {
 1799            return false;
 1800        }
 1801
 1802        let showing_completions = self
 1803            .context_menu
 1804            .borrow()
 1805            .as_ref()
 1806            .map_or(false, |context| {
 1807                matches!(context, CodeContextMenu::Completions(_))
 1808            });
 1809
 1810        showing_completions
 1811            || self.edit_prediction_requires_modifier()
 1812            // Require modifier key when the cursor is on leading whitespace, to allow `tab`
 1813            // bindings to insert tab characters.
 1814            || (self.edit_prediction_requires_modifier_in_indent_conflict && self.edit_prediction_indent_conflict)
 1815    }
 1816
 1817    pub fn accept_edit_prediction_keybind(
 1818        &self,
 1819        window: &Window,
 1820        cx: &App,
 1821    ) -> AcceptEditPredictionBinding {
 1822        let key_context = self.key_context_internal(true, window, cx);
 1823        let in_conflict = self.edit_prediction_in_conflict();
 1824
 1825        AcceptEditPredictionBinding(
 1826            window
 1827                .bindings_for_action_in_context(&AcceptEditPrediction, key_context)
 1828                .into_iter()
 1829                .filter(|binding| {
 1830                    !in_conflict
 1831                        || binding
 1832                            .keystrokes()
 1833                            .first()
 1834                            .map_or(false, |keystroke| keystroke.modifiers.modified())
 1835                })
 1836                .rev()
 1837                .min_by_key(|binding| {
 1838                    binding
 1839                        .keystrokes()
 1840                        .first()
 1841                        .map_or(u8::MAX, |k| k.modifiers.number_of_modifiers())
 1842                }),
 1843        )
 1844    }
 1845
 1846    pub fn new_file(
 1847        workspace: &mut Workspace,
 1848        _: &workspace::NewFile,
 1849        window: &mut Window,
 1850        cx: &mut Context<Workspace>,
 1851    ) {
 1852        Self::new_in_workspace(workspace, window, cx).detach_and_prompt_err(
 1853            "Failed to create buffer",
 1854            window,
 1855            cx,
 1856            |e, _, _| match e.error_code() {
 1857                ErrorCode::RemoteUpgradeRequired => Some(format!(
 1858                "The remote instance of Zed does not support this yet. It must be upgraded to {}",
 1859                e.error_tag("required").unwrap_or("the latest version")
 1860            )),
 1861                _ => None,
 1862            },
 1863        );
 1864    }
 1865
 1866    pub fn new_in_workspace(
 1867        workspace: &mut Workspace,
 1868        window: &mut Window,
 1869        cx: &mut Context<Workspace>,
 1870    ) -> Task<Result<Entity<Editor>>> {
 1871        let project = workspace.project().clone();
 1872        let create = project.update(cx, |project, cx| project.create_buffer(cx));
 1873
 1874        cx.spawn_in(window, async move |workspace, cx| {
 1875            let buffer = create.await?;
 1876            workspace.update_in(cx, |workspace, window, cx| {
 1877                let editor =
 1878                    cx.new(|cx| Editor::for_buffer(buffer, Some(project.clone()), window, cx));
 1879                workspace.add_item_to_active_pane(Box::new(editor.clone()), None, true, window, cx);
 1880                editor
 1881            })
 1882        })
 1883    }
 1884
 1885    fn new_file_vertical(
 1886        workspace: &mut Workspace,
 1887        _: &workspace::NewFileSplitVertical,
 1888        window: &mut Window,
 1889        cx: &mut Context<Workspace>,
 1890    ) {
 1891        Self::new_file_in_direction(workspace, SplitDirection::vertical(cx), window, cx)
 1892    }
 1893
 1894    fn new_file_horizontal(
 1895        workspace: &mut Workspace,
 1896        _: &workspace::NewFileSplitHorizontal,
 1897        window: &mut Window,
 1898        cx: &mut Context<Workspace>,
 1899    ) {
 1900        Self::new_file_in_direction(workspace, SplitDirection::horizontal(cx), window, cx)
 1901    }
 1902
 1903    fn new_file_in_direction(
 1904        workspace: &mut Workspace,
 1905        direction: SplitDirection,
 1906        window: &mut Window,
 1907        cx: &mut Context<Workspace>,
 1908    ) {
 1909        let project = workspace.project().clone();
 1910        let create = project.update(cx, |project, cx| project.create_buffer(cx));
 1911
 1912        cx.spawn_in(window, async move |workspace, cx| {
 1913            let buffer = create.await?;
 1914            workspace.update_in(cx, move |workspace, window, cx| {
 1915                workspace.split_item(
 1916                    direction,
 1917                    Box::new(
 1918                        cx.new(|cx| Editor::for_buffer(buffer, Some(project.clone()), window, cx)),
 1919                    ),
 1920                    window,
 1921                    cx,
 1922                )
 1923            })?;
 1924            anyhow::Ok(())
 1925        })
 1926        .detach_and_prompt_err("Failed to create buffer", window, cx, |e, _, _| {
 1927            match e.error_code() {
 1928                ErrorCode::RemoteUpgradeRequired => Some(format!(
 1929                "The remote instance of Zed does not support this yet. It must be upgraded to {}",
 1930                e.error_tag("required").unwrap_or("the latest version")
 1931            )),
 1932                _ => None,
 1933            }
 1934        });
 1935    }
 1936
 1937    pub fn leader_peer_id(&self) -> Option<PeerId> {
 1938        self.leader_peer_id
 1939    }
 1940
 1941    pub fn buffer(&self) -> &Entity<MultiBuffer> {
 1942        &self.buffer
 1943    }
 1944
 1945    pub fn workspace(&self) -> Option<Entity<Workspace>> {
 1946        self.workspace.as_ref()?.0.upgrade()
 1947    }
 1948
 1949    pub fn title<'a>(&self, cx: &'a App) -> Cow<'a, str> {
 1950        self.buffer().read(cx).title(cx)
 1951    }
 1952
 1953    pub fn snapshot(&self, window: &mut Window, cx: &mut App) -> EditorSnapshot {
 1954        let git_blame_gutter_max_author_length = self
 1955            .render_git_blame_gutter(cx)
 1956            .then(|| {
 1957                if let Some(blame) = self.blame.as_ref() {
 1958                    let max_author_length =
 1959                        blame.update(cx, |blame, cx| blame.max_author_length(cx));
 1960                    Some(max_author_length)
 1961                } else {
 1962                    None
 1963                }
 1964            })
 1965            .flatten();
 1966
 1967        EditorSnapshot {
 1968            mode: self.mode,
 1969            show_gutter: self.show_gutter,
 1970            show_line_numbers: self.show_line_numbers,
 1971            show_git_diff_gutter: self.show_git_diff_gutter,
 1972            show_code_actions: self.show_code_actions,
 1973            show_runnables: self.show_runnables,
 1974            show_breakpoints: self.show_breakpoints,
 1975            git_blame_gutter_max_author_length,
 1976            display_snapshot: self.display_map.update(cx, |map, cx| map.snapshot(cx)),
 1977            scroll_anchor: self.scroll_manager.anchor(),
 1978            ongoing_scroll: self.scroll_manager.ongoing_scroll(),
 1979            placeholder_text: self.placeholder_text.clone(),
 1980            is_focused: self.focus_handle.is_focused(window),
 1981            current_line_highlight: self
 1982                .current_line_highlight
 1983                .unwrap_or_else(|| EditorSettings::get_global(cx).current_line_highlight),
 1984            gutter_hovered: self.gutter_hovered,
 1985        }
 1986    }
 1987
 1988    pub fn language_at<T: ToOffset>(&self, point: T, cx: &App) -> Option<Arc<Language>> {
 1989        self.buffer.read(cx).language_at(point, cx)
 1990    }
 1991
 1992    pub fn file_at<T: ToOffset>(&self, point: T, cx: &App) -> Option<Arc<dyn language::File>> {
 1993        self.buffer.read(cx).read(cx).file_at(point).cloned()
 1994    }
 1995
 1996    pub fn active_excerpt(
 1997        &self,
 1998        cx: &App,
 1999    ) -> Option<(ExcerptId, Entity<Buffer>, Range<text::Anchor>)> {
 2000        self.buffer
 2001            .read(cx)
 2002            .excerpt_containing(self.selections.newest_anchor().head(), cx)
 2003    }
 2004
 2005    pub fn mode(&self) -> EditorMode {
 2006        self.mode
 2007    }
 2008
 2009    pub fn set_mode(&mut self, mode: EditorMode) {
 2010        self.mode = mode;
 2011    }
 2012
 2013    pub fn collaboration_hub(&self) -> Option<&dyn CollaborationHub> {
 2014        self.collaboration_hub.as_deref()
 2015    }
 2016
 2017    pub fn set_collaboration_hub(&mut self, hub: Box<dyn CollaborationHub>) {
 2018        self.collaboration_hub = Some(hub);
 2019    }
 2020
 2021    pub fn set_in_project_search(&mut self, in_project_search: bool) {
 2022        self.in_project_search = in_project_search;
 2023    }
 2024
 2025    pub fn set_custom_context_menu(
 2026        &mut self,
 2027        f: impl 'static
 2028        + Fn(
 2029            &mut Self,
 2030            DisplayPoint,
 2031            &mut Window,
 2032            &mut Context<Self>,
 2033        ) -> Option<Entity<ui::ContextMenu>>,
 2034    ) {
 2035        self.custom_context_menu = Some(Box::new(f))
 2036    }
 2037
 2038    pub fn set_completion_provider(&mut self, provider: Option<Box<dyn CompletionProvider>>) {
 2039        self.completion_provider = provider;
 2040    }
 2041
 2042    pub fn semantics_provider(&self) -> Option<Rc<dyn SemanticsProvider>> {
 2043        self.semantics_provider.clone()
 2044    }
 2045
 2046    pub fn set_semantics_provider(&mut self, provider: Option<Rc<dyn SemanticsProvider>>) {
 2047        self.semantics_provider = provider;
 2048    }
 2049
 2050    pub fn set_edit_prediction_provider<T>(
 2051        &mut self,
 2052        provider: Option<Entity<T>>,
 2053        window: &mut Window,
 2054        cx: &mut Context<Self>,
 2055    ) where
 2056        T: EditPredictionProvider,
 2057    {
 2058        self.edit_prediction_provider =
 2059            provider.map(|provider| RegisteredInlineCompletionProvider {
 2060                _subscription: cx.observe_in(&provider, window, |this, _, window, cx| {
 2061                    if this.focus_handle.is_focused(window) {
 2062                        this.update_visible_inline_completion(window, cx);
 2063                    }
 2064                }),
 2065                provider: Arc::new(provider),
 2066            });
 2067        self.update_edit_prediction_settings(cx);
 2068        self.refresh_inline_completion(false, false, window, cx);
 2069    }
 2070
 2071    pub fn placeholder_text(&self) -> Option<&str> {
 2072        self.placeholder_text.as_deref()
 2073    }
 2074
 2075    pub fn set_placeholder_text(
 2076        &mut self,
 2077        placeholder_text: impl Into<Arc<str>>,
 2078        cx: &mut Context<Self>,
 2079    ) {
 2080        let placeholder_text = Some(placeholder_text.into());
 2081        if self.placeholder_text != placeholder_text {
 2082            self.placeholder_text = placeholder_text;
 2083            cx.notify();
 2084        }
 2085    }
 2086
 2087    pub fn set_cursor_shape(&mut self, cursor_shape: CursorShape, cx: &mut Context<Self>) {
 2088        self.cursor_shape = cursor_shape;
 2089
 2090        // Disrupt blink for immediate user feedback that the cursor shape has changed
 2091        self.blink_manager.update(cx, BlinkManager::show_cursor);
 2092
 2093        cx.notify();
 2094    }
 2095
 2096    pub fn set_current_line_highlight(
 2097        &mut self,
 2098        current_line_highlight: Option<CurrentLineHighlight>,
 2099    ) {
 2100        self.current_line_highlight = current_line_highlight;
 2101    }
 2102
 2103    pub fn set_collapse_matches(&mut self, collapse_matches: bool) {
 2104        self.collapse_matches = collapse_matches;
 2105    }
 2106
 2107    fn register_buffers_with_language_servers(&mut self, cx: &mut Context<Self>) {
 2108        let buffers = self.buffer.read(cx).all_buffers();
 2109        let Some(project) = self.project.as_ref() else {
 2110            return;
 2111        };
 2112        project.update(cx, |project, cx| {
 2113            for buffer in buffers {
 2114                self.registered_buffers
 2115                    .entry(buffer.read(cx).remote_id())
 2116                    .or_insert_with(|| project.register_buffer_with_language_servers(&buffer, cx));
 2117            }
 2118        })
 2119    }
 2120
 2121    pub fn range_for_match<T: std::marker::Copy>(&self, range: &Range<T>) -> Range<T> {
 2122        if self.collapse_matches {
 2123            return range.start..range.start;
 2124        }
 2125        range.clone()
 2126    }
 2127
 2128    pub fn set_clip_at_line_ends(&mut self, clip: bool, cx: &mut Context<Self>) {
 2129        if self.display_map.read(cx).clip_at_line_ends != clip {
 2130            self.display_map
 2131                .update(cx, |map, _| map.clip_at_line_ends = clip);
 2132        }
 2133    }
 2134
 2135    pub fn set_input_enabled(&mut self, input_enabled: bool) {
 2136        self.input_enabled = input_enabled;
 2137    }
 2138
 2139    pub fn set_inline_completions_hidden_for_vim_mode(
 2140        &mut self,
 2141        hidden: bool,
 2142        window: &mut Window,
 2143        cx: &mut Context<Self>,
 2144    ) {
 2145        if hidden != self.inline_completions_hidden_for_vim_mode {
 2146            self.inline_completions_hidden_for_vim_mode = hidden;
 2147            if hidden {
 2148                self.update_visible_inline_completion(window, cx);
 2149            } else {
 2150                self.refresh_inline_completion(true, false, window, cx);
 2151            }
 2152        }
 2153    }
 2154
 2155    pub fn set_menu_inline_completions_policy(&mut self, value: MenuInlineCompletionsPolicy) {
 2156        self.menu_inline_completions_policy = value;
 2157    }
 2158
 2159    pub fn set_autoindent(&mut self, autoindent: bool) {
 2160        if autoindent {
 2161            self.autoindent_mode = Some(AutoindentMode::EachLine);
 2162        } else {
 2163            self.autoindent_mode = None;
 2164        }
 2165    }
 2166
 2167    pub fn read_only(&self, cx: &App) -> bool {
 2168        self.read_only || self.buffer.read(cx).read_only()
 2169    }
 2170
 2171    pub fn set_read_only(&mut self, read_only: bool) {
 2172        self.read_only = read_only;
 2173    }
 2174
 2175    pub fn set_use_autoclose(&mut self, autoclose: bool) {
 2176        self.use_autoclose = autoclose;
 2177    }
 2178
 2179    pub fn set_use_auto_surround(&mut self, auto_surround: bool) {
 2180        self.use_auto_surround = auto_surround;
 2181    }
 2182
 2183    pub fn set_auto_replace_emoji_shortcode(&mut self, auto_replace: bool) {
 2184        self.auto_replace_emoji_shortcode = auto_replace;
 2185    }
 2186
 2187    pub fn toggle_edit_predictions(
 2188        &mut self,
 2189        _: &ToggleEditPrediction,
 2190        window: &mut Window,
 2191        cx: &mut Context<Self>,
 2192    ) {
 2193        if self.show_inline_completions_override.is_some() {
 2194            self.set_show_edit_predictions(None, window, cx);
 2195        } else {
 2196            let show_edit_predictions = !self.edit_predictions_enabled();
 2197            self.set_show_edit_predictions(Some(show_edit_predictions), window, cx);
 2198        }
 2199    }
 2200
 2201    pub fn set_show_edit_predictions(
 2202        &mut self,
 2203        show_edit_predictions: Option<bool>,
 2204        window: &mut Window,
 2205        cx: &mut Context<Self>,
 2206    ) {
 2207        self.show_inline_completions_override = show_edit_predictions;
 2208        self.update_edit_prediction_settings(cx);
 2209
 2210        if let Some(false) = show_edit_predictions {
 2211            self.discard_inline_completion(false, cx);
 2212        } else {
 2213            self.refresh_inline_completion(false, true, window, cx);
 2214        }
 2215    }
 2216
 2217    fn inline_completions_disabled_in_scope(
 2218        &self,
 2219        buffer: &Entity<Buffer>,
 2220        buffer_position: language::Anchor,
 2221        cx: &App,
 2222    ) -> bool {
 2223        let snapshot = buffer.read(cx).snapshot();
 2224        let settings = snapshot.settings_at(buffer_position, cx);
 2225
 2226        let Some(scope) = snapshot.language_scope_at(buffer_position) else {
 2227            return false;
 2228        };
 2229
 2230        scope.override_name().map_or(false, |scope_name| {
 2231            settings
 2232                .edit_predictions_disabled_in
 2233                .iter()
 2234                .any(|s| s == scope_name)
 2235        })
 2236    }
 2237
 2238    pub fn set_use_modal_editing(&mut self, to: bool) {
 2239        self.use_modal_editing = to;
 2240    }
 2241
 2242    pub fn use_modal_editing(&self) -> bool {
 2243        self.use_modal_editing
 2244    }
 2245
 2246    fn selections_did_change(
 2247        &mut self,
 2248        local: bool,
 2249        old_cursor_position: &Anchor,
 2250        show_completions: bool,
 2251        window: &mut Window,
 2252        cx: &mut Context<Self>,
 2253    ) {
 2254        window.invalidate_character_coordinates();
 2255
 2256        // Copy selections to primary selection buffer
 2257        #[cfg(any(target_os = "linux", target_os = "freebsd"))]
 2258        if local {
 2259            let selections = self.selections.all::<usize>(cx);
 2260            let buffer_handle = self.buffer.read(cx).read(cx);
 2261
 2262            let mut text = String::new();
 2263            for (index, selection) in selections.iter().enumerate() {
 2264                let text_for_selection = buffer_handle
 2265                    .text_for_range(selection.start..selection.end)
 2266                    .collect::<String>();
 2267
 2268                text.push_str(&text_for_selection);
 2269                if index != selections.len() - 1 {
 2270                    text.push('\n');
 2271                }
 2272            }
 2273
 2274            if !text.is_empty() {
 2275                cx.write_to_primary(ClipboardItem::new_string(text));
 2276            }
 2277        }
 2278
 2279        if self.focus_handle.is_focused(window) && self.leader_peer_id.is_none() {
 2280            self.buffer.update(cx, |buffer, cx| {
 2281                buffer.set_active_selections(
 2282                    &self.selections.disjoint_anchors(),
 2283                    self.selections.line_mode,
 2284                    self.cursor_shape,
 2285                    cx,
 2286                )
 2287            });
 2288        }
 2289        let display_map = self
 2290            .display_map
 2291            .update(cx, |display_map, cx| display_map.snapshot(cx));
 2292        let buffer = &display_map.buffer_snapshot;
 2293        self.add_selections_state = None;
 2294        self.select_next_state = None;
 2295        self.select_prev_state = None;
 2296        self.select_syntax_node_history.try_clear();
 2297        self.invalidate_autoclose_regions(&self.selections.disjoint_anchors(), buffer);
 2298        self.snippet_stack
 2299            .invalidate(&self.selections.disjoint_anchors(), buffer);
 2300        self.take_rename(false, window, cx);
 2301
 2302        let new_cursor_position = self.selections.newest_anchor().head();
 2303
 2304        self.push_to_nav_history(
 2305            *old_cursor_position,
 2306            Some(new_cursor_position.to_point(buffer)),
 2307            false,
 2308            cx,
 2309        );
 2310
 2311        if local {
 2312            let new_cursor_position = self.selections.newest_anchor().head();
 2313            let mut context_menu = self.context_menu.borrow_mut();
 2314            let completion_menu = match context_menu.as_ref() {
 2315                Some(CodeContextMenu::Completions(menu)) => Some(menu),
 2316                _ => {
 2317                    *context_menu = None;
 2318                    None
 2319                }
 2320            };
 2321            if let Some(buffer_id) = new_cursor_position.buffer_id {
 2322                if !self.registered_buffers.contains_key(&buffer_id) {
 2323                    if let Some(project) = self.project.as_ref() {
 2324                        project.update(cx, |project, cx| {
 2325                            let Some(buffer) = self.buffer.read(cx).buffer(buffer_id) else {
 2326                                return;
 2327                            };
 2328                            self.registered_buffers.insert(
 2329                                buffer_id,
 2330                                project.register_buffer_with_language_servers(&buffer, cx),
 2331                            );
 2332                        })
 2333                    }
 2334                }
 2335            }
 2336
 2337            if let Some(completion_menu) = completion_menu {
 2338                let cursor_position = new_cursor_position.to_offset(buffer);
 2339                let (word_range, kind) =
 2340                    buffer.surrounding_word(completion_menu.initial_position, true);
 2341                if kind == Some(CharKind::Word)
 2342                    && word_range.to_inclusive().contains(&cursor_position)
 2343                {
 2344                    let mut completion_menu = completion_menu.clone();
 2345                    drop(context_menu);
 2346
 2347                    let query = Self::completion_query(buffer, cursor_position);
 2348                    cx.spawn(async move |this, cx| {
 2349                        completion_menu
 2350                            .filter(query.as_deref(), cx.background_executor().clone())
 2351                            .await;
 2352
 2353                        this.update(cx, |this, cx| {
 2354                            let mut context_menu = this.context_menu.borrow_mut();
 2355                            let Some(CodeContextMenu::Completions(menu)) = context_menu.as_ref()
 2356                            else {
 2357                                return;
 2358                            };
 2359
 2360                            if menu.id > completion_menu.id {
 2361                                return;
 2362                            }
 2363
 2364                            *context_menu = Some(CodeContextMenu::Completions(completion_menu));
 2365                            drop(context_menu);
 2366                            cx.notify();
 2367                        })
 2368                    })
 2369                    .detach();
 2370
 2371                    if show_completions {
 2372                        self.show_completions(&ShowCompletions { trigger: None }, window, cx);
 2373                    }
 2374                } else {
 2375                    drop(context_menu);
 2376                    self.hide_context_menu(window, cx);
 2377                }
 2378            } else {
 2379                drop(context_menu);
 2380            }
 2381
 2382            hide_hover(self, cx);
 2383
 2384            if old_cursor_position.to_display_point(&display_map).row()
 2385                != new_cursor_position.to_display_point(&display_map).row()
 2386            {
 2387                self.available_code_actions.take();
 2388            }
 2389            self.refresh_code_actions(window, cx);
 2390            self.refresh_document_highlights(cx);
 2391            self.refresh_selected_text_highlights(window, cx);
 2392            refresh_matching_bracket_highlights(self, window, cx);
 2393            self.update_visible_inline_completion(window, cx);
 2394            self.edit_prediction_requires_modifier_in_indent_conflict = true;
 2395            linked_editing_ranges::refresh_linked_ranges(self, window, cx);
 2396            if self.git_blame_inline_enabled {
 2397                self.start_inline_blame_timer(window, cx);
 2398            }
 2399        }
 2400
 2401        self.blink_manager.update(cx, BlinkManager::pause_blinking);
 2402        cx.emit(EditorEvent::SelectionsChanged { local });
 2403
 2404        let selections = &self.selections.disjoint;
 2405        if selections.len() == 1 {
 2406            cx.emit(SearchEvent::ActiveMatchChanged)
 2407        }
 2408        if local {
 2409            if let Some((_, _, buffer_snapshot)) = buffer.as_singleton() {
 2410                let inmemory_selections = selections
 2411                    .iter()
 2412                    .map(|s| {
 2413                        text::ToPoint::to_point(&s.range().start.text_anchor, buffer_snapshot)
 2414                            ..text::ToPoint::to_point(&s.range().end.text_anchor, buffer_snapshot)
 2415                    })
 2416                    .collect();
 2417                self.update_restoration_data(cx, |data| {
 2418                    data.selections = inmemory_selections;
 2419                });
 2420
 2421                if WorkspaceSettings::get(None, cx).restore_on_startup
 2422                    != RestoreOnStartupBehavior::None
 2423                {
 2424                    if let Some(workspace_id) =
 2425                        self.workspace.as_ref().and_then(|workspace| workspace.1)
 2426                    {
 2427                        let snapshot = self.buffer().read(cx).snapshot(cx);
 2428                        let selections = selections.clone();
 2429                        let background_executor = cx.background_executor().clone();
 2430                        let editor_id = cx.entity().entity_id().as_u64() as ItemId;
 2431                        self.serialize_selections = cx.background_spawn(async move {
 2432                    background_executor.timer(SERIALIZATION_THROTTLE_TIME).await;
 2433                    let db_selections = selections
 2434                        .iter()
 2435                        .map(|selection| {
 2436                            (
 2437                                selection.start.to_offset(&snapshot),
 2438                                selection.end.to_offset(&snapshot),
 2439                            )
 2440                        })
 2441                        .collect();
 2442
 2443                    DB.save_editor_selections(editor_id, workspace_id, db_selections)
 2444                        .await
 2445                        .with_context(|| format!("persisting editor selections for editor {editor_id}, workspace {workspace_id:?}"))
 2446                        .log_err();
 2447                });
 2448                    }
 2449                }
 2450            }
 2451        }
 2452
 2453        cx.notify();
 2454    }
 2455
 2456    fn folds_did_change(&mut self, cx: &mut Context<Self>) {
 2457        use text::ToOffset as _;
 2458        use text::ToPoint as _;
 2459
 2460        if WorkspaceSettings::get(None, cx).restore_on_startup == RestoreOnStartupBehavior::None {
 2461            return;
 2462        }
 2463
 2464        let Some(singleton) = self.buffer().read(cx).as_singleton() else {
 2465            return;
 2466        };
 2467
 2468        let snapshot = singleton.read(cx).snapshot();
 2469        let inmemory_folds = self.display_map.update(cx, |display_map, cx| {
 2470            let display_snapshot = display_map.snapshot(cx);
 2471
 2472            display_snapshot
 2473                .folds_in_range(0..display_snapshot.buffer_snapshot.len())
 2474                .map(|fold| {
 2475                    fold.range.start.text_anchor.to_point(&snapshot)
 2476                        ..fold.range.end.text_anchor.to_point(&snapshot)
 2477                })
 2478                .collect()
 2479        });
 2480        self.update_restoration_data(cx, |data| {
 2481            data.folds = inmemory_folds;
 2482        });
 2483
 2484        let Some(workspace_id) = self.workspace.as_ref().and_then(|workspace| workspace.1) else {
 2485            return;
 2486        };
 2487        let background_executor = cx.background_executor().clone();
 2488        let editor_id = cx.entity().entity_id().as_u64() as ItemId;
 2489        let db_folds = self.display_map.update(cx, |display_map, cx| {
 2490            display_map
 2491                .snapshot(cx)
 2492                .folds_in_range(0..snapshot.len())
 2493                .map(|fold| {
 2494                    (
 2495                        fold.range.start.text_anchor.to_offset(&snapshot),
 2496                        fold.range.end.text_anchor.to_offset(&snapshot),
 2497                    )
 2498                })
 2499                .collect()
 2500        });
 2501        self.serialize_folds = cx.background_spawn(async move {
 2502            background_executor.timer(SERIALIZATION_THROTTLE_TIME).await;
 2503            DB.save_editor_folds(editor_id, workspace_id, db_folds)
 2504                .await
 2505                .with_context(|| {
 2506                    format!(
 2507                        "persisting editor folds for editor {editor_id}, workspace {workspace_id:?}"
 2508                    )
 2509                })
 2510                .log_err();
 2511        });
 2512    }
 2513
 2514    pub fn sync_selections(
 2515        &mut self,
 2516        other: Entity<Editor>,
 2517        cx: &mut Context<Self>,
 2518    ) -> gpui::Subscription {
 2519        let other_selections = other.read(cx).selections.disjoint.to_vec();
 2520        self.selections.change_with(cx, |selections| {
 2521            selections.select_anchors(other_selections);
 2522        });
 2523
 2524        let other_subscription =
 2525            cx.subscribe(&other, |this, other, other_evt, cx| match other_evt {
 2526                EditorEvent::SelectionsChanged { local: true } => {
 2527                    let other_selections = other.read(cx).selections.disjoint.to_vec();
 2528                    if other_selections.is_empty() {
 2529                        return;
 2530                    }
 2531                    this.selections.change_with(cx, |selections| {
 2532                        selections.select_anchors(other_selections);
 2533                    });
 2534                }
 2535                _ => {}
 2536            });
 2537
 2538        let this_subscription =
 2539            cx.subscribe_self::<EditorEvent>(move |this, this_evt, cx| match this_evt {
 2540                EditorEvent::SelectionsChanged { local: true } => {
 2541                    let these_selections = this.selections.disjoint.to_vec();
 2542                    if these_selections.is_empty() {
 2543                        return;
 2544                    }
 2545                    other.update(cx, |other_editor, cx| {
 2546                        other_editor.selections.change_with(cx, |selections| {
 2547                            selections.select_anchors(these_selections);
 2548                        })
 2549                    });
 2550                }
 2551                _ => {}
 2552            });
 2553
 2554        Subscription::join(other_subscription, this_subscription)
 2555    }
 2556
 2557    pub fn change_selections<R>(
 2558        &mut self,
 2559        autoscroll: Option<Autoscroll>,
 2560        window: &mut Window,
 2561        cx: &mut Context<Self>,
 2562        change: impl FnOnce(&mut MutableSelectionsCollection<'_>) -> R,
 2563    ) -> R {
 2564        self.change_selections_inner(autoscroll, true, window, cx, change)
 2565    }
 2566
 2567    fn change_selections_inner<R>(
 2568        &mut self,
 2569        autoscroll: Option<Autoscroll>,
 2570        request_completions: bool,
 2571        window: &mut Window,
 2572        cx: &mut Context<Self>,
 2573        change: impl FnOnce(&mut MutableSelectionsCollection<'_>) -> R,
 2574    ) -> R {
 2575        let old_cursor_position = self.selections.newest_anchor().head();
 2576        self.push_to_selection_history();
 2577
 2578        let (changed, result) = self.selections.change_with(cx, change);
 2579
 2580        if changed {
 2581            if let Some(autoscroll) = autoscroll {
 2582                self.request_autoscroll(autoscroll, cx);
 2583            }
 2584            self.selections_did_change(true, &old_cursor_position, request_completions, window, cx);
 2585
 2586            if self.should_open_signature_help_automatically(
 2587                &old_cursor_position,
 2588                self.signature_help_state.backspace_pressed(),
 2589                cx,
 2590            ) {
 2591                self.show_signature_help(&ShowSignatureHelp, window, cx);
 2592            }
 2593            self.signature_help_state.set_backspace_pressed(false);
 2594        }
 2595
 2596        result
 2597    }
 2598
 2599    pub fn edit<I, S, T>(&mut self, edits: I, cx: &mut Context<Self>)
 2600    where
 2601        I: IntoIterator<Item = (Range<S>, T)>,
 2602        S: ToOffset,
 2603        T: Into<Arc<str>>,
 2604    {
 2605        if self.read_only(cx) {
 2606            return;
 2607        }
 2608
 2609        self.buffer
 2610            .update(cx, |buffer, cx| buffer.edit(edits, None, cx));
 2611    }
 2612
 2613    pub fn edit_with_autoindent<I, S, T>(&mut self, edits: I, cx: &mut Context<Self>)
 2614    where
 2615        I: IntoIterator<Item = (Range<S>, T)>,
 2616        S: ToOffset,
 2617        T: Into<Arc<str>>,
 2618    {
 2619        if self.read_only(cx) {
 2620            return;
 2621        }
 2622
 2623        self.buffer.update(cx, |buffer, cx| {
 2624            buffer.edit(edits, self.autoindent_mode.clone(), cx)
 2625        });
 2626    }
 2627
 2628    pub fn edit_with_block_indent<I, S, T>(
 2629        &mut self,
 2630        edits: I,
 2631        original_indent_columns: Vec<Option<u32>>,
 2632        cx: &mut Context<Self>,
 2633    ) where
 2634        I: IntoIterator<Item = (Range<S>, T)>,
 2635        S: ToOffset,
 2636        T: Into<Arc<str>>,
 2637    {
 2638        if self.read_only(cx) {
 2639            return;
 2640        }
 2641
 2642        self.buffer.update(cx, |buffer, cx| {
 2643            buffer.edit(
 2644                edits,
 2645                Some(AutoindentMode::Block {
 2646                    original_indent_columns,
 2647                }),
 2648                cx,
 2649            )
 2650        });
 2651    }
 2652
 2653    fn select(&mut self, phase: SelectPhase, window: &mut Window, cx: &mut Context<Self>) {
 2654        self.hide_context_menu(window, cx);
 2655
 2656        match phase {
 2657            SelectPhase::Begin {
 2658                position,
 2659                add,
 2660                click_count,
 2661            } => self.begin_selection(position, add, click_count, window, cx),
 2662            SelectPhase::BeginColumnar {
 2663                position,
 2664                goal_column,
 2665                reset,
 2666            } => self.begin_columnar_selection(position, goal_column, reset, window, cx),
 2667            SelectPhase::Extend {
 2668                position,
 2669                click_count,
 2670            } => self.extend_selection(position, click_count, window, cx),
 2671            SelectPhase::Update {
 2672                position,
 2673                goal_column,
 2674                scroll_delta,
 2675            } => self.update_selection(position, goal_column, scroll_delta, window, cx),
 2676            SelectPhase::End => self.end_selection(window, cx),
 2677        }
 2678    }
 2679
 2680    fn extend_selection(
 2681        &mut self,
 2682        position: DisplayPoint,
 2683        click_count: usize,
 2684        window: &mut Window,
 2685        cx: &mut Context<Self>,
 2686    ) {
 2687        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 2688        let tail = self.selections.newest::<usize>(cx).tail();
 2689        self.begin_selection(position, false, click_count, window, cx);
 2690
 2691        let position = position.to_offset(&display_map, Bias::Left);
 2692        let tail_anchor = display_map.buffer_snapshot.anchor_before(tail);
 2693
 2694        let mut pending_selection = self
 2695            .selections
 2696            .pending_anchor()
 2697            .expect("extend_selection not called with pending selection");
 2698        if position >= tail {
 2699            pending_selection.start = tail_anchor;
 2700        } else {
 2701            pending_selection.end = tail_anchor;
 2702            pending_selection.reversed = true;
 2703        }
 2704
 2705        let mut pending_mode = self.selections.pending_mode().unwrap();
 2706        match &mut pending_mode {
 2707            SelectMode::Word(range) | SelectMode::Line(range) => *range = tail_anchor..tail_anchor,
 2708            _ => {}
 2709        }
 2710
 2711        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 2712            s.set_pending(pending_selection, pending_mode)
 2713        });
 2714    }
 2715
 2716    fn begin_selection(
 2717        &mut self,
 2718        position: DisplayPoint,
 2719        add: bool,
 2720        click_count: usize,
 2721        window: &mut Window,
 2722        cx: &mut Context<Self>,
 2723    ) {
 2724        if !self.focus_handle.is_focused(window) {
 2725            self.last_focused_descendant = None;
 2726            window.focus(&self.focus_handle);
 2727        }
 2728
 2729        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 2730        let buffer = &display_map.buffer_snapshot;
 2731        let newest_selection = self.selections.newest_anchor().clone();
 2732        let position = display_map.clip_point(position, Bias::Left);
 2733
 2734        let start;
 2735        let end;
 2736        let mode;
 2737        let mut auto_scroll;
 2738        match click_count {
 2739            1 => {
 2740                start = buffer.anchor_before(position.to_point(&display_map));
 2741                end = start;
 2742                mode = SelectMode::Character;
 2743                auto_scroll = true;
 2744            }
 2745            2 => {
 2746                let range = movement::surrounding_word(&display_map, position);
 2747                start = buffer.anchor_before(range.start.to_point(&display_map));
 2748                end = buffer.anchor_before(range.end.to_point(&display_map));
 2749                mode = SelectMode::Word(start..end);
 2750                auto_scroll = true;
 2751            }
 2752            3 => {
 2753                let position = display_map
 2754                    .clip_point(position, Bias::Left)
 2755                    .to_point(&display_map);
 2756                let line_start = display_map.prev_line_boundary(position).0;
 2757                let next_line_start = buffer.clip_point(
 2758                    display_map.next_line_boundary(position).0 + Point::new(1, 0),
 2759                    Bias::Left,
 2760                );
 2761                start = buffer.anchor_before(line_start);
 2762                end = buffer.anchor_before(next_line_start);
 2763                mode = SelectMode::Line(start..end);
 2764                auto_scroll = true;
 2765            }
 2766            _ => {
 2767                start = buffer.anchor_before(0);
 2768                end = buffer.anchor_before(buffer.len());
 2769                mode = SelectMode::All;
 2770                auto_scroll = false;
 2771            }
 2772        }
 2773        auto_scroll &= EditorSettings::get_global(cx).autoscroll_on_clicks;
 2774
 2775        let point_to_delete: Option<usize> = {
 2776            let selected_points: Vec<Selection<Point>> =
 2777                self.selections.disjoint_in_range(start..end, cx);
 2778
 2779            if !add || click_count > 1 {
 2780                None
 2781            } else if !selected_points.is_empty() {
 2782                Some(selected_points[0].id)
 2783            } else {
 2784                let clicked_point_already_selected =
 2785                    self.selections.disjoint.iter().find(|selection| {
 2786                        selection.start.to_point(buffer) == start.to_point(buffer)
 2787                            || selection.end.to_point(buffer) == end.to_point(buffer)
 2788                    });
 2789
 2790                clicked_point_already_selected.map(|selection| selection.id)
 2791            }
 2792        };
 2793
 2794        let selections_count = self.selections.count();
 2795
 2796        self.change_selections(auto_scroll.then(Autoscroll::newest), window, cx, |s| {
 2797            if let Some(point_to_delete) = point_to_delete {
 2798                s.delete(point_to_delete);
 2799
 2800                if selections_count == 1 {
 2801                    s.set_pending_anchor_range(start..end, mode);
 2802                }
 2803            } else {
 2804                if !add {
 2805                    s.clear_disjoint();
 2806                } else if click_count > 1 {
 2807                    s.delete(newest_selection.id)
 2808                }
 2809
 2810                s.set_pending_anchor_range(start..end, mode);
 2811            }
 2812        });
 2813    }
 2814
 2815    fn begin_columnar_selection(
 2816        &mut self,
 2817        position: DisplayPoint,
 2818        goal_column: u32,
 2819        reset: bool,
 2820        window: &mut Window,
 2821        cx: &mut Context<Self>,
 2822    ) {
 2823        if !self.focus_handle.is_focused(window) {
 2824            self.last_focused_descendant = None;
 2825            window.focus(&self.focus_handle);
 2826        }
 2827
 2828        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 2829
 2830        if reset {
 2831            let pointer_position = display_map
 2832                .buffer_snapshot
 2833                .anchor_before(position.to_point(&display_map));
 2834
 2835            self.change_selections(Some(Autoscroll::newest()), window, cx, |s| {
 2836                s.clear_disjoint();
 2837                s.set_pending_anchor_range(
 2838                    pointer_position..pointer_position,
 2839                    SelectMode::Character,
 2840                );
 2841            });
 2842        }
 2843
 2844        let tail = self.selections.newest::<Point>(cx).tail();
 2845        self.columnar_selection_tail = Some(display_map.buffer_snapshot.anchor_before(tail));
 2846
 2847        if !reset {
 2848            self.select_columns(
 2849                tail.to_display_point(&display_map),
 2850                position,
 2851                goal_column,
 2852                &display_map,
 2853                window,
 2854                cx,
 2855            );
 2856        }
 2857    }
 2858
 2859    fn update_selection(
 2860        &mut self,
 2861        position: DisplayPoint,
 2862        goal_column: u32,
 2863        scroll_delta: gpui::Point<f32>,
 2864        window: &mut Window,
 2865        cx: &mut Context<Self>,
 2866    ) {
 2867        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 2868
 2869        if let Some(tail) = self.columnar_selection_tail.as_ref() {
 2870            let tail = tail.to_display_point(&display_map);
 2871            self.select_columns(tail, position, goal_column, &display_map, window, cx);
 2872        } else if let Some(mut pending) = self.selections.pending_anchor() {
 2873            let buffer = self.buffer.read(cx).snapshot(cx);
 2874            let head;
 2875            let tail;
 2876            let mode = self.selections.pending_mode().unwrap();
 2877            match &mode {
 2878                SelectMode::Character => {
 2879                    head = position.to_point(&display_map);
 2880                    tail = pending.tail().to_point(&buffer);
 2881                }
 2882                SelectMode::Word(original_range) => {
 2883                    let original_display_range = original_range.start.to_display_point(&display_map)
 2884                        ..original_range.end.to_display_point(&display_map);
 2885                    let original_buffer_range = original_display_range.start.to_point(&display_map)
 2886                        ..original_display_range.end.to_point(&display_map);
 2887                    if movement::is_inside_word(&display_map, position)
 2888                        || original_display_range.contains(&position)
 2889                    {
 2890                        let word_range = movement::surrounding_word(&display_map, position);
 2891                        if word_range.start < original_display_range.start {
 2892                            head = word_range.start.to_point(&display_map);
 2893                        } else {
 2894                            head = word_range.end.to_point(&display_map);
 2895                        }
 2896                    } else {
 2897                        head = position.to_point(&display_map);
 2898                    }
 2899
 2900                    if head <= original_buffer_range.start {
 2901                        tail = original_buffer_range.end;
 2902                    } else {
 2903                        tail = original_buffer_range.start;
 2904                    }
 2905                }
 2906                SelectMode::Line(original_range) => {
 2907                    let original_range = original_range.to_point(&display_map.buffer_snapshot);
 2908
 2909                    let position = display_map
 2910                        .clip_point(position, Bias::Left)
 2911                        .to_point(&display_map);
 2912                    let line_start = display_map.prev_line_boundary(position).0;
 2913                    let next_line_start = buffer.clip_point(
 2914                        display_map.next_line_boundary(position).0 + Point::new(1, 0),
 2915                        Bias::Left,
 2916                    );
 2917
 2918                    if line_start < original_range.start {
 2919                        head = line_start
 2920                    } else {
 2921                        head = next_line_start
 2922                    }
 2923
 2924                    if head <= original_range.start {
 2925                        tail = original_range.end;
 2926                    } else {
 2927                        tail = original_range.start;
 2928                    }
 2929                }
 2930                SelectMode::All => {
 2931                    return;
 2932                }
 2933            };
 2934
 2935            if head < tail {
 2936                pending.start = buffer.anchor_before(head);
 2937                pending.end = buffer.anchor_before(tail);
 2938                pending.reversed = true;
 2939            } else {
 2940                pending.start = buffer.anchor_before(tail);
 2941                pending.end = buffer.anchor_before(head);
 2942                pending.reversed = false;
 2943            }
 2944
 2945            self.change_selections(None, window, cx, |s| {
 2946                s.set_pending(pending, mode);
 2947            });
 2948        } else {
 2949            log::error!("update_selection dispatched with no pending selection");
 2950            return;
 2951        }
 2952
 2953        self.apply_scroll_delta(scroll_delta, window, cx);
 2954        cx.notify();
 2955    }
 2956
 2957    fn end_selection(&mut self, window: &mut Window, cx: &mut Context<Self>) {
 2958        self.columnar_selection_tail.take();
 2959        if self.selections.pending_anchor().is_some() {
 2960            let selections = self.selections.all::<usize>(cx);
 2961            self.change_selections(None, window, cx, |s| {
 2962                s.select(selections);
 2963                s.clear_pending();
 2964            });
 2965        }
 2966    }
 2967
 2968    fn select_columns(
 2969        &mut self,
 2970        tail: DisplayPoint,
 2971        head: DisplayPoint,
 2972        goal_column: u32,
 2973        display_map: &DisplaySnapshot,
 2974        window: &mut Window,
 2975        cx: &mut Context<Self>,
 2976    ) {
 2977        let start_row = cmp::min(tail.row(), head.row());
 2978        let end_row = cmp::max(tail.row(), head.row());
 2979        let start_column = cmp::min(tail.column(), goal_column);
 2980        let end_column = cmp::max(tail.column(), goal_column);
 2981        let reversed = start_column < tail.column();
 2982
 2983        let selection_ranges = (start_row.0..=end_row.0)
 2984            .map(DisplayRow)
 2985            .filter_map(|row| {
 2986                if start_column <= display_map.line_len(row) && !display_map.is_block_line(row) {
 2987                    let start = display_map
 2988                        .clip_point(DisplayPoint::new(row, start_column), Bias::Left)
 2989                        .to_point(display_map);
 2990                    let end = display_map
 2991                        .clip_point(DisplayPoint::new(row, end_column), Bias::Right)
 2992                        .to_point(display_map);
 2993                    if reversed {
 2994                        Some(end..start)
 2995                    } else {
 2996                        Some(start..end)
 2997                    }
 2998                } else {
 2999                    None
 3000                }
 3001            })
 3002            .collect::<Vec<_>>();
 3003
 3004        self.change_selections(None, window, cx, |s| {
 3005            s.select_ranges(selection_ranges);
 3006        });
 3007        cx.notify();
 3008    }
 3009
 3010    pub fn has_pending_nonempty_selection(&self) -> bool {
 3011        let pending_nonempty_selection = match self.selections.pending_anchor() {
 3012            Some(Selection { start, end, .. }) => start != end,
 3013            None => false,
 3014        };
 3015
 3016        pending_nonempty_selection
 3017            || (self.columnar_selection_tail.is_some() && self.selections.disjoint.len() > 1)
 3018    }
 3019
 3020    pub fn has_pending_selection(&self) -> bool {
 3021        self.selections.pending_anchor().is_some() || self.columnar_selection_tail.is_some()
 3022    }
 3023
 3024    pub fn cancel(&mut self, _: &Cancel, window: &mut Window, cx: &mut Context<Self>) {
 3025        self.selection_mark_mode = false;
 3026
 3027        if self.clear_expanded_diff_hunks(cx) {
 3028            cx.notify();
 3029            return;
 3030        }
 3031        if self.dismiss_menus_and_popups(true, window, cx) {
 3032            return;
 3033        }
 3034
 3035        if self.mode.is_full()
 3036            && self.change_selections(Some(Autoscroll::fit()), window, cx, |s| s.try_cancel())
 3037        {
 3038            return;
 3039        }
 3040
 3041        cx.propagate();
 3042    }
 3043
 3044    pub fn dismiss_menus_and_popups(
 3045        &mut self,
 3046        is_user_requested: bool,
 3047        window: &mut Window,
 3048        cx: &mut Context<Self>,
 3049    ) -> bool {
 3050        if self.take_rename(false, window, cx).is_some() {
 3051            return true;
 3052        }
 3053
 3054        if hide_hover(self, cx) {
 3055            return true;
 3056        }
 3057
 3058        if self.hide_signature_help(cx, SignatureHelpHiddenBy::Escape) {
 3059            return true;
 3060        }
 3061
 3062        if self.hide_context_menu(window, cx).is_some() {
 3063            return true;
 3064        }
 3065
 3066        if self.mouse_context_menu.take().is_some() {
 3067            return true;
 3068        }
 3069
 3070        if is_user_requested && self.discard_inline_completion(true, cx) {
 3071            return true;
 3072        }
 3073
 3074        if self.snippet_stack.pop().is_some() {
 3075            return true;
 3076        }
 3077
 3078        if self.mode.is_full() && self.active_diagnostics.is_some() {
 3079            self.dismiss_diagnostics(cx);
 3080            return true;
 3081        }
 3082
 3083        false
 3084    }
 3085
 3086    fn linked_editing_ranges_for(
 3087        &self,
 3088        selection: Range<text::Anchor>,
 3089        cx: &App,
 3090    ) -> Option<HashMap<Entity<Buffer>, Vec<Range<text::Anchor>>>> {
 3091        if self.linked_edit_ranges.is_empty() {
 3092            return None;
 3093        }
 3094        let ((base_range, linked_ranges), buffer_snapshot, buffer) =
 3095            selection.end.buffer_id.and_then(|end_buffer_id| {
 3096                if selection.start.buffer_id != Some(end_buffer_id) {
 3097                    return None;
 3098                }
 3099                let buffer = self.buffer.read(cx).buffer(end_buffer_id)?;
 3100                let snapshot = buffer.read(cx).snapshot();
 3101                self.linked_edit_ranges
 3102                    .get(end_buffer_id, selection.start..selection.end, &snapshot)
 3103                    .map(|ranges| (ranges, snapshot, buffer))
 3104            })?;
 3105        use text::ToOffset as TO;
 3106        // find offset from the start of current range to current cursor position
 3107        let start_byte_offset = TO::to_offset(&base_range.start, &buffer_snapshot);
 3108
 3109        let start_offset = TO::to_offset(&selection.start, &buffer_snapshot);
 3110        let start_difference = start_offset - start_byte_offset;
 3111        let end_offset = TO::to_offset(&selection.end, &buffer_snapshot);
 3112        let end_difference = end_offset - start_byte_offset;
 3113        // Current range has associated linked ranges.
 3114        let mut linked_edits = HashMap::<_, Vec<_>>::default();
 3115        for range in linked_ranges.iter() {
 3116            let start_offset = TO::to_offset(&range.start, &buffer_snapshot);
 3117            let end_offset = start_offset + end_difference;
 3118            let start_offset = start_offset + start_difference;
 3119            if start_offset > buffer_snapshot.len() || end_offset > buffer_snapshot.len() {
 3120                continue;
 3121            }
 3122            if self.selections.disjoint_anchor_ranges().any(|s| {
 3123                if s.start.buffer_id != selection.start.buffer_id
 3124                    || s.end.buffer_id != selection.end.buffer_id
 3125                {
 3126                    return false;
 3127                }
 3128                TO::to_offset(&s.start.text_anchor, &buffer_snapshot) <= end_offset
 3129                    && TO::to_offset(&s.end.text_anchor, &buffer_snapshot) >= start_offset
 3130            }) {
 3131                continue;
 3132            }
 3133            let start = buffer_snapshot.anchor_after(start_offset);
 3134            let end = buffer_snapshot.anchor_after(end_offset);
 3135            linked_edits
 3136                .entry(buffer.clone())
 3137                .or_default()
 3138                .push(start..end);
 3139        }
 3140        Some(linked_edits)
 3141    }
 3142
 3143    pub fn handle_input(&mut self, text: &str, window: &mut Window, cx: &mut Context<Self>) {
 3144        let text: Arc<str> = text.into();
 3145
 3146        if self.read_only(cx) {
 3147            return;
 3148        }
 3149
 3150        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
 3151
 3152        let selections = self.selections.all_adjusted(cx);
 3153        let mut bracket_inserted = false;
 3154        let mut edits = Vec::new();
 3155        let mut linked_edits = HashMap::<_, Vec<_>>::default();
 3156        let mut new_selections = Vec::with_capacity(selections.len());
 3157        let mut new_autoclose_regions = Vec::new();
 3158        let snapshot = self.buffer.read(cx).read(cx);
 3159        let mut clear_linked_edit_ranges = false;
 3160
 3161        for (selection, autoclose_region) in
 3162            self.selections_with_autoclose_regions(selections, &snapshot)
 3163        {
 3164            if let Some(scope) = snapshot.language_scope_at(selection.head()) {
 3165                // Determine if the inserted text matches the opening or closing
 3166                // bracket of any of this language's bracket pairs.
 3167                let mut bracket_pair = None;
 3168                let mut is_bracket_pair_start = false;
 3169                let mut is_bracket_pair_end = false;
 3170                if !text.is_empty() {
 3171                    // `text` can be empty when a user is using IME (e.g. Chinese Wubi Simplified)
 3172                    //  and they are removing the character that triggered IME popup.
 3173                    for (pair, enabled) in scope.brackets() {
 3174                        if !pair.close && !pair.surround {
 3175                            continue;
 3176                        }
 3177
 3178                        if enabled && pair.start.ends_with(text.as_ref()) {
 3179                            let prefix_len = pair.start.len() - text.len();
 3180                            let preceding_text_matches_prefix = prefix_len == 0
 3181                                || (selection.start.column >= (prefix_len as u32)
 3182                                    && snapshot.contains_str_at(
 3183                                        Point::new(
 3184                                            selection.start.row,
 3185                                            selection.start.column - (prefix_len as u32),
 3186                                        ),
 3187                                        &pair.start[..prefix_len],
 3188                                    ));
 3189                            if preceding_text_matches_prefix {
 3190                                bracket_pair = Some(pair.clone());
 3191                                is_bracket_pair_start = true;
 3192                                break;
 3193                            }
 3194                        }
 3195                        if pair.end.as_str() == text.as_ref() {
 3196                            bracket_pair = Some(pair.clone());
 3197                            is_bracket_pair_end = true;
 3198                            break;
 3199                        }
 3200                    }
 3201                }
 3202
 3203                if let Some(bracket_pair) = bracket_pair {
 3204                    let snapshot_settings = snapshot.language_settings_at(selection.start, cx);
 3205                    let autoclose = self.use_autoclose && snapshot_settings.use_autoclose;
 3206                    let auto_surround =
 3207                        self.use_auto_surround && snapshot_settings.use_auto_surround;
 3208                    if selection.is_empty() {
 3209                        if is_bracket_pair_start {
 3210                            // If the inserted text is a suffix of an opening bracket and the
 3211                            // selection is preceded by the rest of the opening bracket, then
 3212                            // insert the closing bracket.
 3213                            let following_text_allows_autoclose = snapshot
 3214                                .chars_at(selection.start)
 3215                                .next()
 3216                                .map_or(true, |c| scope.should_autoclose_before(c));
 3217
 3218                            let preceding_text_allows_autoclose = selection.start.column == 0
 3219                                || snapshot.reversed_chars_at(selection.start).next().map_or(
 3220                                    true,
 3221                                    |c| {
 3222                                        bracket_pair.start != bracket_pair.end
 3223                                            || !snapshot
 3224                                                .char_classifier_at(selection.start)
 3225                                                .is_word(c)
 3226                                    },
 3227                                );
 3228
 3229                            let is_closing_quote = if bracket_pair.end == bracket_pair.start
 3230                                && bracket_pair.start.len() == 1
 3231                            {
 3232                                let target = bracket_pair.start.chars().next().unwrap();
 3233                                let current_line_count = snapshot
 3234                                    .reversed_chars_at(selection.start)
 3235                                    .take_while(|&c| c != '\n')
 3236                                    .filter(|&c| c == target)
 3237                                    .count();
 3238                                current_line_count % 2 == 1
 3239                            } else {
 3240                                false
 3241                            };
 3242
 3243                            if autoclose
 3244                                && bracket_pair.close
 3245                                && following_text_allows_autoclose
 3246                                && preceding_text_allows_autoclose
 3247                                && !is_closing_quote
 3248                            {
 3249                                let anchor = snapshot.anchor_before(selection.end);
 3250                                new_selections.push((selection.map(|_| anchor), text.len()));
 3251                                new_autoclose_regions.push((
 3252                                    anchor,
 3253                                    text.len(),
 3254                                    selection.id,
 3255                                    bracket_pair.clone(),
 3256                                ));
 3257                                edits.push((
 3258                                    selection.range(),
 3259                                    format!("{}{}", text, bracket_pair.end).into(),
 3260                                ));
 3261                                bracket_inserted = true;
 3262                                continue;
 3263                            }
 3264                        }
 3265
 3266                        if let Some(region) = autoclose_region {
 3267                            // If the selection is followed by an auto-inserted closing bracket,
 3268                            // then don't insert that closing bracket again; just move the selection
 3269                            // past the closing bracket.
 3270                            let should_skip = selection.end == region.range.end.to_point(&snapshot)
 3271                                && text.as_ref() == region.pair.end.as_str();
 3272                            if should_skip {
 3273                                let anchor = snapshot.anchor_after(selection.end);
 3274                                new_selections
 3275                                    .push((selection.map(|_| anchor), region.pair.end.len()));
 3276                                continue;
 3277                            }
 3278                        }
 3279
 3280                        let always_treat_brackets_as_autoclosed = snapshot
 3281                            .language_settings_at(selection.start, cx)
 3282                            .always_treat_brackets_as_autoclosed;
 3283                        if always_treat_brackets_as_autoclosed
 3284                            && is_bracket_pair_end
 3285                            && snapshot.contains_str_at(selection.end, text.as_ref())
 3286                        {
 3287                            // Otherwise, when `always_treat_brackets_as_autoclosed` is set to `true
 3288                            // and the inserted text is a closing bracket and the selection is followed
 3289                            // by the closing bracket then move the selection past the closing bracket.
 3290                            let anchor = snapshot.anchor_after(selection.end);
 3291                            new_selections.push((selection.map(|_| anchor), text.len()));
 3292                            continue;
 3293                        }
 3294                    }
 3295                    // If an opening bracket is 1 character long and is typed while
 3296                    // text is selected, then surround that text with the bracket pair.
 3297                    else if auto_surround
 3298                        && bracket_pair.surround
 3299                        && is_bracket_pair_start
 3300                        && bracket_pair.start.chars().count() == 1
 3301                    {
 3302                        edits.push((selection.start..selection.start, text.clone()));
 3303                        edits.push((
 3304                            selection.end..selection.end,
 3305                            bracket_pair.end.as_str().into(),
 3306                        ));
 3307                        bracket_inserted = true;
 3308                        new_selections.push((
 3309                            Selection {
 3310                                id: selection.id,
 3311                                start: snapshot.anchor_after(selection.start),
 3312                                end: snapshot.anchor_before(selection.end),
 3313                                reversed: selection.reversed,
 3314                                goal: selection.goal,
 3315                            },
 3316                            0,
 3317                        ));
 3318                        continue;
 3319                    }
 3320                }
 3321            }
 3322
 3323            if self.auto_replace_emoji_shortcode
 3324                && selection.is_empty()
 3325                && text.as_ref().ends_with(':')
 3326            {
 3327                if let Some(possible_emoji_short_code) =
 3328                    Self::find_possible_emoji_shortcode_at_position(&snapshot, selection.start)
 3329                {
 3330                    if !possible_emoji_short_code.is_empty() {
 3331                        if let Some(emoji) = emojis::get_by_shortcode(&possible_emoji_short_code) {
 3332                            let emoji_shortcode_start = Point::new(
 3333                                selection.start.row,
 3334                                selection.start.column - possible_emoji_short_code.len() as u32 - 1,
 3335                            );
 3336
 3337                            // Remove shortcode from buffer
 3338                            edits.push((
 3339                                emoji_shortcode_start..selection.start,
 3340                                "".to_string().into(),
 3341                            ));
 3342                            new_selections.push((
 3343                                Selection {
 3344                                    id: selection.id,
 3345                                    start: snapshot.anchor_after(emoji_shortcode_start),
 3346                                    end: snapshot.anchor_before(selection.start),
 3347                                    reversed: selection.reversed,
 3348                                    goal: selection.goal,
 3349                                },
 3350                                0,
 3351                            ));
 3352
 3353                            // Insert emoji
 3354                            let selection_start_anchor = snapshot.anchor_after(selection.start);
 3355                            new_selections.push((selection.map(|_| selection_start_anchor), 0));
 3356                            edits.push((selection.start..selection.end, emoji.to_string().into()));
 3357
 3358                            continue;
 3359                        }
 3360                    }
 3361                }
 3362            }
 3363
 3364            // If not handling any auto-close operation, then just replace the selected
 3365            // text with the given input and move the selection to the end of the
 3366            // newly inserted text.
 3367            let anchor = snapshot.anchor_after(selection.end);
 3368            if !self.linked_edit_ranges.is_empty() {
 3369                let start_anchor = snapshot.anchor_before(selection.start);
 3370
 3371                let is_word_char = text.chars().next().map_or(true, |char| {
 3372                    let classifier = snapshot.char_classifier_at(start_anchor.to_offset(&snapshot));
 3373                    classifier.is_word(char)
 3374                });
 3375
 3376                if is_word_char {
 3377                    if let Some(ranges) = self
 3378                        .linked_editing_ranges_for(start_anchor.text_anchor..anchor.text_anchor, cx)
 3379                    {
 3380                        for (buffer, edits) in ranges {
 3381                            linked_edits
 3382                                .entry(buffer.clone())
 3383                                .or_default()
 3384                                .extend(edits.into_iter().map(|range| (range, text.clone())));
 3385                        }
 3386                    }
 3387                } else {
 3388                    clear_linked_edit_ranges = true;
 3389                }
 3390            }
 3391
 3392            new_selections.push((selection.map(|_| anchor), 0));
 3393            edits.push((selection.start..selection.end, text.clone()));
 3394        }
 3395
 3396        drop(snapshot);
 3397
 3398        self.transact(window, cx, |this, window, cx| {
 3399            if clear_linked_edit_ranges {
 3400                this.linked_edit_ranges.clear();
 3401            }
 3402            let initial_buffer_versions =
 3403                jsx_tag_auto_close::construct_initial_buffer_versions_map(this, &edits, cx);
 3404
 3405            this.buffer.update(cx, |buffer, cx| {
 3406                buffer.edit(edits, this.autoindent_mode.clone(), cx);
 3407            });
 3408            for (buffer, edits) in linked_edits {
 3409                buffer.update(cx, |buffer, cx| {
 3410                    let snapshot = buffer.snapshot();
 3411                    let edits = edits
 3412                        .into_iter()
 3413                        .map(|(range, text)| {
 3414                            use text::ToPoint as TP;
 3415                            let end_point = TP::to_point(&range.end, &snapshot);
 3416                            let start_point = TP::to_point(&range.start, &snapshot);
 3417                            (start_point..end_point, text)
 3418                        })
 3419                        .sorted_by_key(|(range, _)| range.start);
 3420                    buffer.edit(edits, None, cx);
 3421                })
 3422            }
 3423            let new_anchor_selections = new_selections.iter().map(|e| &e.0);
 3424            let new_selection_deltas = new_selections.iter().map(|e| e.1);
 3425            let map = this.display_map.update(cx, |map, cx| map.snapshot(cx));
 3426            let new_selections = resolve_selections::<usize, _>(new_anchor_selections, &map)
 3427                .zip(new_selection_deltas)
 3428                .map(|(selection, delta)| Selection {
 3429                    id: selection.id,
 3430                    start: selection.start + delta,
 3431                    end: selection.end + delta,
 3432                    reversed: selection.reversed,
 3433                    goal: SelectionGoal::None,
 3434                })
 3435                .collect::<Vec<_>>();
 3436
 3437            let mut i = 0;
 3438            for (position, delta, selection_id, pair) in new_autoclose_regions {
 3439                let position = position.to_offset(&map.buffer_snapshot) + delta;
 3440                let start = map.buffer_snapshot.anchor_before(position);
 3441                let end = map.buffer_snapshot.anchor_after(position);
 3442                while let Some(existing_state) = this.autoclose_regions.get(i) {
 3443                    match existing_state.range.start.cmp(&start, &map.buffer_snapshot) {
 3444                        Ordering::Less => i += 1,
 3445                        Ordering::Greater => break,
 3446                        Ordering::Equal => {
 3447                            match end.cmp(&existing_state.range.end, &map.buffer_snapshot) {
 3448                                Ordering::Less => i += 1,
 3449                                Ordering::Equal => break,
 3450                                Ordering::Greater => break,
 3451                            }
 3452                        }
 3453                    }
 3454                }
 3455                this.autoclose_regions.insert(
 3456                    i,
 3457                    AutocloseRegion {
 3458                        selection_id,
 3459                        range: start..end,
 3460                        pair,
 3461                    },
 3462                );
 3463            }
 3464
 3465            let had_active_inline_completion = this.has_active_inline_completion();
 3466            this.change_selections_inner(Some(Autoscroll::fit()), false, window, cx, |s| {
 3467                s.select(new_selections)
 3468            });
 3469
 3470            if !bracket_inserted {
 3471                if let Some(on_type_format_task) =
 3472                    this.trigger_on_type_formatting(text.to_string(), window, cx)
 3473                {
 3474                    on_type_format_task.detach_and_log_err(cx);
 3475                }
 3476            }
 3477
 3478            let editor_settings = EditorSettings::get_global(cx);
 3479            if bracket_inserted
 3480                && (editor_settings.auto_signature_help
 3481                    || editor_settings.show_signature_help_after_edits)
 3482            {
 3483                this.show_signature_help(&ShowSignatureHelp, window, cx);
 3484            }
 3485
 3486            let trigger_in_words =
 3487                this.show_edit_predictions_in_menu() || !had_active_inline_completion;
 3488            if this.hard_wrap.is_some() {
 3489                let latest: Range<Point> = this.selections.newest(cx).range();
 3490                if latest.is_empty()
 3491                    && this
 3492                        .buffer()
 3493                        .read(cx)
 3494                        .snapshot(cx)
 3495                        .line_len(MultiBufferRow(latest.start.row))
 3496                        == latest.start.column
 3497                {
 3498                    this.rewrap_impl(
 3499                        RewrapOptions {
 3500                            override_language_settings: true,
 3501                            preserve_existing_whitespace: true,
 3502                        },
 3503                        cx,
 3504                    )
 3505                }
 3506            }
 3507            this.trigger_completion_on_input(&text, trigger_in_words, window, cx);
 3508            linked_editing_ranges::refresh_linked_ranges(this, window, cx);
 3509            this.refresh_inline_completion(true, false, window, cx);
 3510            jsx_tag_auto_close::handle_from(this, initial_buffer_versions, window, cx);
 3511        });
 3512    }
 3513
 3514    fn find_possible_emoji_shortcode_at_position(
 3515        snapshot: &MultiBufferSnapshot,
 3516        position: Point,
 3517    ) -> Option<String> {
 3518        let mut chars = Vec::new();
 3519        let mut found_colon = false;
 3520        for char in snapshot.reversed_chars_at(position).take(100) {
 3521            // Found a possible emoji shortcode in the middle of the buffer
 3522            if found_colon {
 3523                if char.is_whitespace() {
 3524                    chars.reverse();
 3525                    return Some(chars.iter().collect());
 3526                }
 3527                // If the previous character is not a whitespace, we are in the middle of a word
 3528                // and we only want to complete the shortcode if the word is made up of other emojis
 3529                let mut containing_word = String::new();
 3530                for ch in snapshot
 3531                    .reversed_chars_at(position)
 3532                    .skip(chars.len() + 1)
 3533                    .take(100)
 3534                {
 3535                    if ch.is_whitespace() {
 3536                        break;
 3537                    }
 3538                    containing_word.push(ch);
 3539                }
 3540                let containing_word = containing_word.chars().rev().collect::<String>();
 3541                if util::word_consists_of_emojis(containing_word.as_str()) {
 3542                    chars.reverse();
 3543                    return Some(chars.iter().collect());
 3544                }
 3545            }
 3546
 3547            if char.is_whitespace() || !char.is_ascii() {
 3548                return None;
 3549            }
 3550            if char == ':' {
 3551                found_colon = true;
 3552            } else {
 3553                chars.push(char);
 3554            }
 3555        }
 3556        // Found a possible emoji shortcode at the beginning of the buffer
 3557        chars.reverse();
 3558        Some(chars.iter().collect())
 3559    }
 3560
 3561    pub fn newline(&mut self, _: &Newline, window: &mut Window, cx: &mut Context<Self>) {
 3562        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
 3563        self.transact(window, cx, |this, window, cx| {
 3564            let (edits, selection_fixup_info): (Vec<_>, Vec<_>) = {
 3565                let selections = this.selections.all::<usize>(cx);
 3566                let multi_buffer = this.buffer.read(cx);
 3567                let buffer = multi_buffer.snapshot(cx);
 3568                selections
 3569                    .iter()
 3570                    .map(|selection| {
 3571                        let start_point = selection.start.to_point(&buffer);
 3572                        let mut indent =
 3573                            buffer.indent_size_for_line(MultiBufferRow(start_point.row));
 3574                        indent.len = cmp::min(indent.len, start_point.column);
 3575                        let start = selection.start;
 3576                        let end = selection.end;
 3577                        let selection_is_empty = start == end;
 3578                        let language_scope = buffer.language_scope_at(start);
 3579                        let (comment_delimiter, insert_extra_newline) = if let Some(language) =
 3580                            &language_scope
 3581                        {
 3582                            let insert_extra_newline =
 3583                                insert_extra_newline_brackets(&buffer, start..end, language)
 3584                                    || insert_extra_newline_tree_sitter(&buffer, start..end);
 3585
 3586                            // Comment extension on newline is allowed only for cursor selections
 3587                            let comment_delimiter = maybe!({
 3588                                if !selection_is_empty {
 3589                                    return None;
 3590                                }
 3591
 3592                                if !multi_buffer.language_settings(cx).extend_comment_on_newline {
 3593                                    return None;
 3594                                }
 3595
 3596                                let delimiters = language.line_comment_prefixes();
 3597                                let max_len_of_delimiter =
 3598                                    delimiters.iter().map(|delimiter| delimiter.len()).max()?;
 3599                                let (snapshot, range) =
 3600                                    buffer.buffer_line_for_row(MultiBufferRow(start_point.row))?;
 3601
 3602                                let mut index_of_first_non_whitespace = 0;
 3603                                let comment_candidate = snapshot
 3604                                    .chars_for_range(range)
 3605                                    .skip_while(|c| {
 3606                                        let should_skip = c.is_whitespace();
 3607                                        if should_skip {
 3608                                            index_of_first_non_whitespace += 1;
 3609                                        }
 3610                                        should_skip
 3611                                    })
 3612                                    .take(max_len_of_delimiter)
 3613                                    .collect::<String>();
 3614                                let comment_prefix = delimiters.iter().find(|comment_prefix| {
 3615                                    comment_candidate.starts_with(comment_prefix.as_ref())
 3616                                })?;
 3617                                let cursor_is_placed_after_comment_marker =
 3618                                    index_of_first_non_whitespace + comment_prefix.len()
 3619                                        <= start_point.column as usize;
 3620                                if cursor_is_placed_after_comment_marker {
 3621                                    Some(comment_prefix.clone())
 3622                                } else {
 3623                                    None
 3624                                }
 3625                            });
 3626                            (comment_delimiter, insert_extra_newline)
 3627                        } else {
 3628                            (None, false)
 3629                        };
 3630
 3631                        let capacity_for_delimiter = comment_delimiter
 3632                            .as_deref()
 3633                            .map(str::len)
 3634                            .unwrap_or_default();
 3635                        let mut new_text =
 3636                            String::with_capacity(1 + capacity_for_delimiter + indent.len as usize);
 3637                        new_text.push('\n');
 3638                        new_text.extend(indent.chars());
 3639                        if let Some(delimiter) = &comment_delimiter {
 3640                            new_text.push_str(delimiter);
 3641                        }
 3642                        if insert_extra_newline {
 3643                            new_text = new_text.repeat(2);
 3644                        }
 3645
 3646                        let anchor = buffer.anchor_after(end);
 3647                        let new_selection = selection.map(|_| anchor);
 3648                        (
 3649                            (start..end, new_text),
 3650                            (insert_extra_newline, new_selection),
 3651                        )
 3652                    })
 3653                    .unzip()
 3654            };
 3655
 3656            this.edit_with_autoindent(edits, cx);
 3657            let buffer = this.buffer.read(cx).snapshot(cx);
 3658            let new_selections = selection_fixup_info
 3659                .into_iter()
 3660                .map(|(extra_newline_inserted, new_selection)| {
 3661                    let mut cursor = new_selection.end.to_point(&buffer);
 3662                    if extra_newline_inserted {
 3663                        cursor.row -= 1;
 3664                        cursor.column = buffer.line_len(MultiBufferRow(cursor.row));
 3665                    }
 3666                    new_selection.map(|_| cursor)
 3667                })
 3668                .collect();
 3669
 3670            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 3671                s.select(new_selections)
 3672            });
 3673            this.refresh_inline_completion(true, false, window, cx);
 3674        });
 3675    }
 3676
 3677    pub fn newline_above(&mut self, _: &NewlineAbove, window: &mut Window, cx: &mut Context<Self>) {
 3678        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
 3679
 3680        let buffer = self.buffer.read(cx);
 3681        let snapshot = buffer.snapshot(cx);
 3682
 3683        let mut edits = Vec::new();
 3684        let mut rows = Vec::new();
 3685
 3686        for (rows_inserted, selection) in self.selections.all_adjusted(cx).into_iter().enumerate() {
 3687            let cursor = selection.head();
 3688            let row = cursor.row;
 3689
 3690            let start_of_line = snapshot.clip_point(Point::new(row, 0), Bias::Left);
 3691
 3692            let newline = "\n".to_string();
 3693            edits.push((start_of_line..start_of_line, newline));
 3694
 3695            rows.push(row + rows_inserted as u32);
 3696        }
 3697
 3698        self.transact(window, cx, |editor, window, cx| {
 3699            editor.edit(edits, cx);
 3700
 3701            editor.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 3702                let mut index = 0;
 3703                s.move_cursors_with(|map, _, _| {
 3704                    let row = rows[index];
 3705                    index += 1;
 3706
 3707                    let point = Point::new(row, 0);
 3708                    let boundary = map.next_line_boundary(point).1;
 3709                    let clipped = map.clip_point(boundary, Bias::Left);
 3710
 3711                    (clipped, SelectionGoal::None)
 3712                });
 3713            });
 3714
 3715            let mut indent_edits = Vec::new();
 3716            let multibuffer_snapshot = editor.buffer.read(cx).snapshot(cx);
 3717            for row in rows {
 3718                let indents = multibuffer_snapshot.suggested_indents(row..row + 1, cx);
 3719                for (row, indent) in indents {
 3720                    if indent.len == 0 {
 3721                        continue;
 3722                    }
 3723
 3724                    let text = match indent.kind {
 3725                        IndentKind::Space => " ".repeat(indent.len as usize),
 3726                        IndentKind::Tab => "\t".repeat(indent.len as usize),
 3727                    };
 3728                    let point = Point::new(row.0, 0);
 3729                    indent_edits.push((point..point, text));
 3730                }
 3731            }
 3732            editor.edit(indent_edits, cx);
 3733        });
 3734    }
 3735
 3736    pub fn newline_below(&mut self, _: &NewlineBelow, window: &mut Window, cx: &mut Context<Self>) {
 3737        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
 3738
 3739        let buffer = self.buffer.read(cx);
 3740        let snapshot = buffer.snapshot(cx);
 3741
 3742        let mut edits = Vec::new();
 3743        let mut rows = Vec::new();
 3744        let mut rows_inserted = 0;
 3745
 3746        for selection in self.selections.all_adjusted(cx) {
 3747            let cursor = selection.head();
 3748            let row = cursor.row;
 3749
 3750            let point = Point::new(row + 1, 0);
 3751            let start_of_line = snapshot.clip_point(point, Bias::Left);
 3752
 3753            let newline = "\n".to_string();
 3754            edits.push((start_of_line..start_of_line, newline));
 3755
 3756            rows_inserted += 1;
 3757            rows.push(row + rows_inserted);
 3758        }
 3759
 3760        self.transact(window, cx, |editor, window, cx| {
 3761            editor.edit(edits, cx);
 3762
 3763            editor.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 3764                let mut index = 0;
 3765                s.move_cursors_with(|map, _, _| {
 3766                    let row = rows[index];
 3767                    index += 1;
 3768
 3769                    let point = Point::new(row, 0);
 3770                    let boundary = map.next_line_boundary(point).1;
 3771                    let clipped = map.clip_point(boundary, Bias::Left);
 3772
 3773                    (clipped, SelectionGoal::None)
 3774                });
 3775            });
 3776
 3777            let mut indent_edits = Vec::new();
 3778            let multibuffer_snapshot = editor.buffer.read(cx).snapshot(cx);
 3779            for row in rows {
 3780                let indents = multibuffer_snapshot.suggested_indents(row..row + 1, cx);
 3781                for (row, indent) in indents {
 3782                    if indent.len == 0 {
 3783                        continue;
 3784                    }
 3785
 3786                    let text = match indent.kind {
 3787                        IndentKind::Space => " ".repeat(indent.len as usize),
 3788                        IndentKind::Tab => "\t".repeat(indent.len as usize),
 3789                    };
 3790                    let point = Point::new(row.0, 0);
 3791                    indent_edits.push((point..point, text));
 3792                }
 3793            }
 3794            editor.edit(indent_edits, cx);
 3795        });
 3796    }
 3797
 3798    pub fn insert(&mut self, text: &str, window: &mut Window, cx: &mut Context<Self>) {
 3799        let autoindent = text.is_empty().not().then(|| AutoindentMode::Block {
 3800            original_indent_columns: Vec::new(),
 3801        });
 3802        self.insert_with_autoindent_mode(text, autoindent, window, cx);
 3803    }
 3804
 3805    fn insert_with_autoindent_mode(
 3806        &mut self,
 3807        text: &str,
 3808        autoindent_mode: Option<AutoindentMode>,
 3809        window: &mut Window,
 3810        cx: &mut Context<Self>,
 3811    ) {
 3812        if self.read_only(cx) {
 3813            return;
 3814        }
 3815
 3816        let text: Arc<str> = text.into();
 3817        self.transact(window, cx, |this, window, cx| {
 3818            let old_selections = this.selections.all_adjusted(cx);
 3819            let selection_anchors = this.buffer.update(cx, |buffer, cx| {
 3820                let anchors = {
 3821                    let snapshot = buffer.read(cx);
 3822                    old_selections
 3823                        .iter()
 3824                        .map(|s| {
 3825                            let anchor = snapshot.anchor_after(s.head());
 3826                            s.map(|_| anchor)
 3827                        })
 3828                        .collect::<Vec<_>>()
 3829                };
 3830                buffer.edit(
 3831                    old_selections
 3832                        .iter()
 3833                        .map(|s| (s.start..s.end, text.clone())),
 3834                    autoindent_mode,
 3835                    cx,
 3836                );
 3837                anchors
 3838            });
 3839
 3840            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 3841                s.select_anchors(selection_anchors);
 3842            });
 3843
 3844            cx.notify();
 3845        });
 3846    }
 3847
 3848    fn trigger_completion_on_input(
 3849        &mut self,
 3850        text: &str,
 3851        trigger_in_words: bool,
 3852        window: &mut Window,
 3853        cx: &mut Context<Self>,
 3854    ) {
 3855        let ignore_completion_provider = self
 3856            .context_menu
 3857            .borrow()
 3858            .as_ref()
 3859            .map(|menu| match menu {
 3860                CodeContextMenu::Completions(completions_menu) => {
 3861                    completions_menu.ignore_completion_provider
 3862                }
 3863                CodeContextMenu::CodeActions(_) => false,
 3864            })
 3865            .unwrap_or(false);
 3866
 3867        if ignore_completion_provider {
 3868            self.show_word_completions(&ShowWordCompletions, window, cx);
 3869        } else if self.is_completion_trigger(text, trigger_in_words, cx) {
 3870            self.show_completions(
 3871                &ShowCompletions {
 3872                    trigger: Some(text.to_owned()).filter(|x| !x.is_empty()),
 3873                },
 3874                window,
 3875                cx,
 3876            );
 3877        } else {
 3878            self.hide_context_menu(window, cx);
 3879        }
 3880    }
 3881
 3882    fn is_completion_trigger(
 3883        &self,
 3884        text: &str,
 3885        trigger_in_words: bool,
 3886        cx: &mut Context<Self>,
 3887    ) -> bool {
 3888        let position = self.selections.newest_anchor().head();
 3889        let multibuffer = self.buffer.read(cx);
 3890        let Some(buffer) = position
 3891            .buffer_id
 3892            .and_then(|buffer_id| multibuffer.buffer(buffer_id).clone())
 3893        else {
 3894            return false;
 3895        };
 3896
 3897        if let Some(completion_provider) = &self.completion_provider {
 3898            completion_provider.is_completion_trigger(
 3899                &buffer,
 3900                position.text_anchor,
 3901                text,
 3902                trigger_in_words,
 3903                cx,
 3904            )
 3905        } else {
 3906            false
 3907        }
 3908    }
 3909
 3910    /// If any empty selections is touching the start of its innermost containing autoclose
 3911    /// region, expand it to select the brackets.
 3912    fn select_autoclose_pair(&mut self, window: &mut Window, cx: &mut Context<Self>) {
 3913        let selections = self.selections.all::<usize>(cx);
 3914        let buffer = self.buffer.read(cx).read(cx);
 3915        let new_selections = self
 3916            .selections_with_autoclose_regions(selections, &buffer)
 3917            .map(|(mut selection, region)| {
 3918                if !selection.is_empty() {
 3919                    return selection;
 3920                }
 3921
 3922                if let Some(region) = region {
 3923                    let mut range = region.range.to_offset(&buffer);
 3924                    if selection.start == range.start && range.start >= region.pair.start.len() {
 3925                        range.start -= region.pair.start.len();
 3926                        if buffer.contains_str_at(range.start, &region.pair.start)
 3927                            && buffer.contains_str_at(range.end, &region.pair.end)
 3928                        {
 3929                            range.end += region.pair.end.len();
 3930                            selection.start = range.start;
 3931                            selection.end = range.end;
 3932
 3933                            return selection;
 3934                        }
 3935                    }
 3936                }
 3937
 3938                let always_treat_brackets_as_autoclosed = buffer
 3939                    .language_settings_at(selection.start, cx)
 3940                    .always_treat_brackets_as_autoclosed;
 3941
 3942                if !always_treat_brackets_as_autoclosed {
 3943                    return selection;
 3944                }
 3945
 3946                if let Some(scope) = buffer.language_scope_at(selection.start) {
 3947                    for (pair, enabled) in scope.brackets() {
 3948                        if !enabled || !pair.close {
 3949                            continue;
 3950                        }
 3951
 3952                        if buffer.contains_str_at(selection.start, &pair.end) {
 3953                            let pair_start_len = pair.start.len();
 3954                            if buffer.contains_str_at(
 3955                                selection.start.saturating_sub(pair_start_len),
 3956                                &pair.start,
 3957                            ) {
 3958                                selection.start -= pair_start_len;
 3959                                selection.end += pair.end.len();
 3960
 3961                                return selection;
 3962                            }
 3963                        }
 3964                    }
 3965                }
 3966
 3967                selection
 3968            })
 3969            .collect();
 3970
 3971        drop(buffer);
 3972        self.change_selections(None, window, cx, |selections| {
 3973            selections.select(new_selections)
 3974        });
 3975    }
 3976
 3977    /// Iterate the given selections, and for each one, find the smallest surrounding
 3978    /// autoclose region. This uses the ordering of the selections and the autoclose
 3979    /// regions to avoid repeated comparisons.
 3980    fn selections_with_autoclose_regions<'a, D: ToOffset + Clone>(
 3981        &'a self,
 3982        selections: impl IntoIterator<Item = Selection<D>>,
 3983        buffer: &'a MultiBufferSnapshot,
 3984    ) -> impl Iterator<Item = (Selection<D>, Option<&'a AutocloseRegion>)> {
 3985        let mut i = 0;
 3986        let mut regions = self.autoclose_regions.as_slice();
 3987        selections.into_iter().map(move |selection| {
 3988            let range = selection.start.to_offset(buffer)..selection.end.to_offset(buffer);
 3989
 3990            let mut enclosing = None;
 3991            while let Some(pair_state) = regions.get(i) {
 3992                if pair_state.range.end.to_offset(buffer) < range.start {
 3993                    regions = &regions[i + 1..];
 3994                    i = 0;
 3995                } else if pair_state.range.start.to_offset(buffer) > range.end {
 3996                    break;
 3997                } else {
 3998                    if pair_state.selection_id == selection.id {
 3999                        enclosing = Some(pair_state);
 4000                    }
 4001                    i += 1;
 4002                }
 4003            }
 4004
 4005            (selection, enclosing)
 4006        })
 4007    }
 4008
 4009    /// Remove any autoclose regions that no longer contain their selection.
 4010    fn invalidate_autoclose_regions(
 4011        &mut self,
 4012        mut selections: &[Selection<Anchor>],
 4013        buffer: &MultiBufferSnapshot,
 4014    ) {
 4015        self.autoclose_regions.retain(|state| {
 4016            let mut i = 0;
 4017            while let Some(selection) = selections.get(i) {
 4018                if selection.end.cmp(&state.range.start, buffer).is_lt() {
 4019                    selections = &selections[1..];
 4020                    continue;
 4021                }
 4022                if selection.start.cmp(&state.range.end, buffer).is_gt() {
 4023                    break;
 4024                }
 4025                if selection.id == state.selection_id {
 4026                    return true;
 4027                } else {
 4028                    i += 1;
 4029                }
 4030            }
 4031            false
 4032        });
 4033    }
 4034
 4035    fn completion_query(buffer: &MultiBufferSnapshot, position: impl ToOffset) -> Option<String> {
 4036        let offset = position.to_offset(buffer);
 4037        let (word_range, kind) = buffer.surrounding_word(offset, true);
 4038        if offset > word_range.start && kind == Some(CharKind::Word) {
 4039            Some(
 4040                buffer
 4041                    .text_for_range(word_range.start..offset)
 4042                    .collect::<String>(),
 4043            )
 4044        } else {
 4045            None
 4046        }
 4047    }
 4048
 4049    pub fn toggle_inlay_hints(
 4050        &mut self,
 4051        _: &ToggleInlayHints,
 4052        _: &mut Window,
 4053        cx: &mut Context<Self>,
 4054    ) {
 4055        self.refresh_inlay_hints(
 4056            InlayHintRefreshReason::Toggle(!self.inlay_hints_enabled()),
 4057            cx,
 4058        );
 4059    }
 4060
 4061    pub fn inlay_hints_enabled(&self) -> bool {
 4062        self.inlay_hint_cache.enabled
 4063    }
 4064
 4065    fn refresh_inlay_hints(&mut self, reason: InlayHintRefreshReason, cx: &mut Context<Self>) {
 4066        if self.semantics_provider.is_none() || !self.mode.is_full() {
 4067            return;
 4068        }
 4069
 4070        let reason_description = reason.description();
 4071        let ignore_debounce = matches!(
 4072            reason,
 4073            InlayHintRefreshReason::SettingsChange(_)
 4074                | InlayHintRefreshReason::Toggle(_)
 4075                | InlayHintRefreshReason::ExcerptsRemoved(_)
 4076                | InlayHintRefreshReason::ModifiersChanged(_)
 4077        );
 4078        let (invalidate_cache, required_languages) = match reason {
 4079            InlayHintRefreshReason::ModifiersChanged(enabled) => {
 4080                match self.inlay_hint_cache.modifiers_override(enabled) {
 4081                    Some(enabled) => {
 4082                        if enabled {
 4083                            (InvalidationStrategy::RefreshRequested, None)
 4084                        } else {
 4085                            self.splice_inlays(
 4086                                &self
 4087                                    .visible_inlay_hints(cx)
 4088                                    .iter()
 4089                                    .map(|inlay| inlay.id)
 4090                                    .collect::<Vec<InlayId>>(),
 4091                                Vec::new(),
 4092                                cx,
 4093                            );
 4094                            return;
 4095                        }
 4096                    }
 4097                    None => return,
 4098                }
 4099            }
 4100            InlayHintRefreshReason::Toggle(enabled) => {
 4101                if self.inlay_hint_cache.toggle(enabled) {
 4102                    if enabled {
 4103                        (InvalidationStrategy::RefreshRequested, None)
 4104                    } else {
 4105                        self.splice_inlays(
 4106                            &self
 4107                                .visible_inlay_hints(cx)
 4108                                .iter()
 4109                                .map(|inlay| inlay.id)
 4110                                .collect::<Vec<InlayId>>(),
 4111                            Vec::new(),
 4112                            cx,
 4113                        );
 4114                        return;
 4115                    }
 4116                } else {
 4117                    return;
 4118                }
 4119            }
 4120            InlayHintRefreshReason::SettingsChange(new_settings) => {
 4121                match self.inlay_hint_cache.update_settings(
 4122                    &self.buffer,
 4123                    new_settings,
 4124                    self.visible_inlay_hints(cx),
 4125                    cx,
 4126                ) {
 4127                    ControlFlow::Break(Some(InlaySplice {
 4128                        to_remove,
 4129                        to_insert,
 4130                    })) => {
 4131                        self.splice_inlays(&to_remove, to_insert, cx);
 4132                        return;
 4133                    }
 4134                    ControlFlow::Break(None) => return,
 4135                    ControlFlow::Continue(()) => (InvalidationStrategy::RefreshRequested, None),
 4136                }
 4137            }
 4138            InlayHintRefreshReason::ExcerptsRemoved(excerpts_removed) => {
 4139                if let Some(InlaySplice {
 4140                    to_remove,
 4141                    to_insert,
 4142                }) = self.inlay_hint_cache.remove_excerpts(excerpts_removed)
 4143                {
 4144                    self.splice_inlays(&to_remove, to_insert, cx);
 4145                }
 4146                return;
 4147            }
 4148            InlayHintRefreshReason::NewLinesShown => (InvalidationStrategy::None, None),
 4149            InlayHintRefreshReason::BufferEdited(buffer_languages) => {
 4150                (InvalidationStrategy::BufferEdited, Some(buffer_languages))
 4151            }
 4152            InlayHintRefreshReason::RefreshRequested => {
 4153                (InvalidationStrategy::RefreshRequested, None)
 4154            }
 4155        };
 4156
 4157        if let Some(InlaySplice {
 4158            to_remove,
 4159            to_insert,
 4160        }) = self.inlay_hint_cache.spawn_hint_refresh(
 4161            reason_description,
 4162            self.excerpts_for_inlay_hints_query(required_languages.as_ref(), cx),
 4163            invalidate_cache,
 4164            ignore_debounce,
 4165            cx,
 4166        ) {
 4167            self.splice_inlays(&to_remove, to_insert, cx);
 4168        }
 4169    }
 4170
 4171    fn visible_inlay_hints(&self, cx: &Context<Editor>) -> Vec<Inlay> {
 4172        self.display_map
 4173            .read(cx)
 4174            .current_inlays()
 4175            .filter(move |inlay| matches!(inlay.id, InlayId::Hint(_)))
 4176            .cloned()
 4177            .collect()
 4178    }
 4179
 4180    pub fn excerpts_for_inlay_hints_query(
 4181        &self,
 4182        restrict_to_languages: Option<&HashSet<Arc<Language>>>,
 4183        cx: &mut Context<Editor>,
 4184    ) -> HashMap<ExcerptId, (Entity<Buffer>, clock::Global, Range<usize>)> {
 4185        let Some(project) = self.project.as_ref() else {
 4186            return HashMap::default();
 4187        };
 4188        let project = project.read(cx);
 4189        let multi_buffer = self.buffer().read(cx);
 4190        let multi_buffer_snapshot = multi_buffer.snapshot(cx);
 4191        let multi_buffer_visible_start = self
 4192            .scroll_manager
 4193            .anchor()
 4194            .anchor
 4195            .to_point(&multi_buffer_snapshot);
 4196        let multi_buffer_visible_end = multi_buffer_snapshot.clip_point(
 4197            multi_buffer_visible_start
 4198                + Point::new(self.visible_line_count().unwrap_or(0.).ceil() as u32, 0),
 4199            Bias::Left,
 4200        );
 4201        let multi_buffer_visible_range = multi_buffer_visible_start..multi_buffer_visible_end;
 4202        multi_buffer_snapshot
 4203            .range_to_buffer_ranges(multi_buffer_visible_range)
 4204            .into_iter()
 4205            .filter(|(_, excerpt_visible_range, _)| !excerpt_visible_range.is_empty())
 4206            .filter_map(|(buffer, excerpt_visible_range, excerpt_id)| {
 4207                let buffer_file = project::File::from_dyn(buffer.file())?;
 4208                let buffer_worktree = project.worktree_for_id(buffer_file.worktree_id(cx), cx)?;
 4209                let worktree_entry = buffer_worktree
 4210                    .read(cx)
 4211                    .entry_for_id(buffer_file.project_entry_id(cx)?)?;
 4212                if worktree_entry.is_ignored {
 4213                    return None;
 4214                }
 4215
 4216                let language = buffer.language()?;
 4217                if let Some(restrict_to_languages) = restrict_to_languages {
 4218                    if !restrict_to_languages.contains(language) {
 4219                        return None;
 4220                    }
 4221                }
 4222                Some((
 4223                    excerpt_id,
 4224                    (
 4225                        multi_buffer.buffer(buffer.remote_id()).unwrap(),
 4226                        buffer.version().clone(),
 4227                        excerpt_visible_range,
 4228                    ),
 4229                ))
 4230            })
 4231            .collect()
 4232    }
 4233
 4234    pub fn text_layout_details(&self, window: &mut Window) -> TextLayoutDetails {
 4235        TextLayoutDetails {
 4236            text_system: window.text_system().clone(),
 4237            editor_style: self.style.clone().unwrap(),
 4238            rem_size: window.rem_size(),
 4239            scroll_anchor: self.scroll_manager.anchor(),
 4240            visible_rows: self.visible_line_count(),
 4241            vertical_scroll_margin: self.scroll_manager.vertical_scroll_margin,
 4242        }
 4243    }
 4244
 4245    pub fn splice_inlays(
 4246        &self,
 4247        to_remove: &[InlayId],
 4248        to_insert: Vec<Inlay>,
 4249        cx: &mut Context<Self>,
 4250    ) {
 4251        self.display_map.update(cx, |display_map, cx| {
 4252            display_map.splice_inlays(to_remove, to_insert, cx)
 4253        });
 4254        cx.notify();
 4255    }
 4256
 4257    fn trigger_on_type_formatting(
 4258        &self,
 4259        input: String,
 4260        window: &mut Window,
 4261        cx: &mut Context<Self>,
 4262    ) -> Option<Task<Result<()>>> {
 4263        if input.len() != 1 {
 4264            return None;
 4265        }
 4266
 4267        let project = self.project.as_ref()?;
 4268        let position = self.selections.newest_anchor().head();
 4269        let (buffer, buffer_position) = self
 4270            .buffer
 4271            .read(cx)
 4272            .text_anchor_for_position(position, cx)?;
 4273
 4274        let settings = language_settings::language_settings(
 4275            buffer
 4276                .read(cx)
 4277                .language_at(buffer_position)
 4278                .map(|l| l.name()),
 4279            buffer.read(cx).file(),
 4280            cx,
 4281        );
 4282        if !settings.use_on_type_format {
 4283            return None;
 4284        }
 4285
 4286        // OnTypeFormatting returns a list of edits, no need to pass them between Zed instances,
 4287        // hence we do LSP request & edit on host side only — add formats to host's history.
 4288        let push_to_lsp_host_history = true;
 4289        // If this is not the host, append its history with new edits.
 4290        let push_to_client_history = project.read(cx).is_via_collab();
 4291
 4292        let on_type_formatting = project.update(cx, |project, cx| {
 4293            project.on_type_format(
 4294                buffer.clone(),
 4295                buffer_position,
 4296                input,
 4297                push_to_lsp_host_history,
 4298                cx,
 4299            )
 4300        });
 4301        Some(cx.spawn_in(window, async move |editor, cx| {
 4302            if let Some(transaction) = on_type_formatting.await? {
 4303                if push_to_client_history {
 4304                    buffer
 4305                        .update(cx, |buffer, _| {
 4306                            buffer.push_transaction(transaction, Instant::now());
 4307                            buffer.finalize_last_transaction();
 4308                        })
 4309                        .ok();
 4310                }
 4311                editor.update(cx, |editor, cx| {
 4312                    editor.refresh_document_highlights(cx);
 4313                })?;
 4314            }
 4315            Ok(())
 4316        }))
 4317    }
 4318
 4319    pub fn show_word_completions(
 4320        &mut self,
 4321        _: &ShowWordCompletions,
 4322        window: &mut Window,
 4323        cx: &mut Context<Self>,
 4324    ) {
 4325        self.open_completions_menu(true, None, window, cx);
 4326    }
 4327
 4328    pub fn show_completions(
 4329        &mut self,
 4330        options: &ShowCompletions,
 4331        window: &mut Window,
 4332        cx: &mut Context<Self>,
 4333    ) {
 4334        self.open_completions_menu(false, options.trigger.as_deref(), window, cx);
 4335    }
 4336
 4337    fn open_completions_menu(
 4338        &mut self,
 4339        ignore_completion_provider: bool,
 4340        trigger: Option<&str>,
 4341        window: &mut Window,
 4342        cx: &mut Context<Self>,
 4343    ) {
 4344        if self.pending_rename.is_some() {
 4345            return;
 4346        }
 4347        if !self.snippet_stack.is_empty() && self.context_menu.borrow().as_ref().is_some() {
 4348            return;
 4349        }
 4350
 4351        let position = self.selections.newest_anchor().head();
 4352        if position.diff_base_anchor.is_some() {
 4353            return;
 4354        }
 4355        let (buffer, buffer_position) =
 4356            if let Some(output) = self.buffer.read(cx).text_anchor_for_position(position, cx) {
 4357                output
 4358            } else {
 4359                return;
 4360            };
 4361        let buffer_snapshot = buffer.read(cx).snapshot();
 4362        let show_completion_documentation = buffer_snapshot
 4363            .settings_at(buffer_position, cx)
 4364            .show_completion_documentation;
 4365
 4366        let query = Self::completion_query(&self.buffer.read(cx).read(cx), position);
 4367
 4368        let trigger_kind = match trigger {
 4369            Some(trigger) if buffer.read(cx).completion_triggers().contains(trigger) => {
 4370                CompletionTriggerKind::TRIGGER_CHARACTER
 4371            }
 4372            _ => CompletionTriggerKind::INVOKED,
 4373        };
 4374        let completion_context = CompletionContext {
 4375            trigger_character: trigger.and_then(|trigger| {
 4376                if trigger_kind == CompletionTriggerKind::TRIGGER_CHARACTER {
 4377                    Some(String::from(trigger))
 4378                } else {
 4379                    None
 4380                }
 4381            }),
 4382            trigger_kind,
 4383        };
 4384
 4385        let (old_range, word_kind) = buffer_snapshot.surrounding_word(buffer_position);
 4386        let (old_range, word_to_exclude) = if word_kind == Some(CharKind::Word) {
 4387            let word_to_exclude = buffer_snapshot
 4388                .text_for_range(old_range.clone())
 4389                .collect::<String>();
 4390            (
 4391                buffer_snapshot.anchor_before(old_range.start)
 4392                    ..buffer_snapshot.anchor_after(old_range.end),
 4393                Some(word_to_exclude),
 4394            )
 4395        } else {
 4396            (buffer_position..buffer_position, None)
 4397        };
 4398
 4399        let completion_settings = language_settings(
 4400            buffer_snapshot
 4401                .language_at(buffer_position)
 4402                .map(|language| language.name()),
 4403            buffer_snapshot.file(),
 4404            cx,
 4405        )
 4406        .completions;
 4407
 4408        // The document can be large, so stay in reasonable bounds when searching for words,
 4409        // otherwise completion pop-up might be slow to appear.
 4410        const WORD_LOOKUP_ROWS: u32 = 5_000;
 4411        let buffer_row = text::ToPoint::to_point(&buffer_position, &buffer_snapshot).row;
 4412        let min_word_search = buffer_snapshot.clip_point(
 4413            Point::new(buffer_row.saturating_sub(WORD_LOOKUP_ROWS), 0),
 4414            Bias::Left,
 4415        );
 4416        let max_word_search = buffer_snapshot.clip_point(
 4417            Point::new(buffer_row + WORD_LOOKUP_ROWS, 0).min(buffer_snapshot.max_point()),
 4418            Bias::Right,
 4419        );
 4420        let word_search_range = buffer_snapshot.point_to_offset(min_word_search)
 4421            ..buffer_snapshot.point_to_offset(max_word_search);
 4422
 4423        let provider = self
 4424            .completion_provider
 4425            .as_ref()
 4426            .filter(|_| !ignore_completion_provider);
 4427        let skip_digits = query
 4428            .as_ref()
 4429            .map_or(true, |query| !query.chars().any(|c| c.is_digit(10)));
 4430
 4431        let (mut words, provided_completions) = match provider {
 4432            Some(provider) => {
 4433                let completions = provider.completions(
 4434                    position.excerpt_id,
 4435                    &buffer,
 4436                    buffer_position,
 4437                    completion_context,
 4438                    window,
 4439                    cx,
 4440                );
 4441
 4442                let words = match completion_settings.words {
 4443                    WordsCompletionMode::Disabled => Task::ready(BTreeMap::default()),
 4444                    WordsCompletionMode::Enabled | WordsCompletionMode::Fallback => cx
 4445                        .background_spawn(async move {
 4446                            buffer_snapshot.words_in_range(WordsQuery {
 4447                                fuzzy_contents: None,
 4448                                range: word_search_range,
 4449                                skip_digits,
 4450                            })
 4451                        }),
 4452                };
 4453
 4454                (words, completions)
 4455            }
 4456            None => (
 4457                cx.background_spawn(async move {
 4458                    buffer_snapshot.words_in_range(WordsQuery {
 4459                        fuzzy_contents: None,
 4460                        range: word_search_range,
 4461                        skip_digits,
 4462                    })
 4463                }),
 4464                Task::ready(Ok(None)),
 4465            ),
 4466        };
 4467
 4468        let sort_completions = provider
 4469            .as_ref()
 4470            .map_or(false, |provider| provider.sort_completions());
 4471
 4472        let filter_completions = provider
 4473            .as_ref()
 4474            .map_or(true, |provider| provider.filter_completions());
 4475
 4476        let id = post_inc(&mut self.next_completion_id);
 4477        let task = cx.spawn_in(window, async move |editor, cx| {
 4478            async move {
 4479                editor.update(cx, |this, _| {
 4480                    this.completion_tasks.retain(|(task_id, _)| *task_id >= id);
 4481                })?;
 4482
 4483                let mut completions = Vec::new();
 4484                if let Some(provided_completions) = provided_completions.await.log_err().flatten() {
 4485                    completions.extend(provided_completions);
 4486                    if completion_settings.words == WordsCompletionMode::Fallback {
 4487                        words = Task::ready(BTreeMap::default());
 4488                    }
 4489                }
 4490
 4491                let mut words = words.await;
 4492                if let Some(word_to_exclude) = &word_to_exclude {
 4493                    words.remove(word_to_exclude);
 4494                }
 4495                for lsp_completion in &completions {
 4496                    words.remove(&lsp_completion.new_text);
 4497                }
 4498                completions.extend(words.into_iter().map(|(word, word_range)| Completion {
 4499                    replace_range: old_range.clone(),
 4500                    new_text: word.clone(),
 4501                    label: CodeLabel::plain(word, None),
 4502                    icon_path: None,
 4503                    documentation: None,
 4504                    source: CompletionSource::BufferWord {
 4505                        word_range,
 4506                        resolved: false,
 4507                    },
 4508                    insert_text_mode: Some(InsertTextMode::AS_IS),
 4509                    confirm: None,
 4510                }));
 4511
 4512                let menu = if completions.is_empty() {
 4513                    None
 4514                } else {
 4515                    let mut menu = CompletionsMenu::new(
 4516                        id,
 4517                        sort_completions,
 4518                        show_completion_documentation,
 4519                        ignore_completion_provider,
 4520                        position,
 4521                        buffer.clone(),
 4522                        completions.into(),
 4523                    );
 4524
 4525                    menu.filter(
 4526                        if filter_completions {
 4527                            query.as_deref()
 4528                        } else {
 4529                            None
 4530                        },
 4531                        cx.background_executor().clone(),
 4532                    )
 4533                    .await;
 4534
 4535                    menu.visible().then_some(menu)
 4536                };
 4537
 4538                editor.update_in(cx, |editor, window, cx| {
 4539                    match editor.context_menu.borrow().as_ref() {
 4540                        None => {}
 4541                        Some(CodeContextMenu::Completions(prev_menu)) => {
 4542                            if prev_menu.id > id {
 4543                                return;
 4544                            }
 4545                        }
 4546                        _ => return,
 4547                    }
 4548
 4549                    if editor.focus_handle.is_focused(window) && menu.is_some() {
 4550                        let mut menu = menu.unwrap();
 4551                        menu.resolve_visible_completions(editor.completion_provider.as_deref(), cx);
 4552
 4553                        *editor.context_menu.borrow_mut() =
 4554                            Some(CodeContextMenu::Completions(menu));
 4555
 4556                        if editor.show_edit_predictions_in_menu() {
 4557                            editor.update_visible_inline_completion(window, cx);
 4558                        } else {
 4559                            editor.discard_inline_completion(false, cx);
 4560                        }
 4561
 4562                        cx.notify();
 4563                    } else if editor.completion_tasks.len() <= 1 {
 4564                        // If there are no more completion tasks and the last menu was
 4565                        // empty, we should hide it.
 4566                        let was_hidden = editor.hide_context_menu(window, cx).is_none();
 4567                        // If it was already hidden and we don't show inline
 4568                        // completions in the menu, we should also show the
 4569                        // inline-completion when available.
 4570                        if was_hidden && editor.show_edit_predictions_in_menu() {
 4571                            editor.update_visible_inline_completion(window, cx);
 4572                        }
 4573                    }
 4574                })?;
 4575
 4576                anyhow::Ok(())
 4577            }
 4578            .log_err()
 4579            .await
 4580        });
 4581
 4582        self.completion_tasks.push((id, task));
 4583    }
 4584
 4585    #[cfg(feature = "test-support")]
 4586    pub fn current_completions(&self) -> Option<Vec<project::Completion>> {
 4587        let menu = self.context_menu.borrow();
 4588        if let CodeContextMenu::Completions(menu) = menu.as_ref()? {
 4589            let completions = menu.completions.borrow();
 4590            Some(completions.to_vec())
 4591        } else {
 4592            None
 4593        }
 4594    }
 4595
 4596    pub fn confirm_completion(
 4597        &mut self,
 4598        action: &ConfirmCompletion,
 4599        window: &mut Window,
 4600        cx: &mut Context<Self>,
 4601    ) -> Option<Task<Result<()>>> {
 4602        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
 4603        self.do_completion(action.item_ix, CompletionIntent::Complete, window, cx)
 4604    }
 4605
 4606    pub fn confirm_completion_insert(
 4607        &mut self,
 4608        _: &ConfirmCompletionInsert,
 4609        window: &mut Window,
 4610        cx: &mut Context<Self>,
 4611    ) -> Option<Task<Result<()>>> {
 4612        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
 4613        self.do_completion(None, CompletionIntent::CompleteWithInsert, window, cx)
 4614    }
 4615
 4616    pub fn confirm_completion_replace(
 4617        &mut self,
 4618        _: &ConfirmCompletionReplace,
 4619        window: &mut Window,
 4620        cx: &mut Context<Self>,
 4621    ) -> Option<Task<Result<()>>> {
 4622        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
 4623        self.do_completion(None, CompletionIntent::CompleteWithReplace, window, cx)
 4624    }
 4625
 4626    pub fn compose_completion(
 4627        &mut self,
 4628        action: &ComposeCompletion,
 4629        window: &mut Window,
 4630        cx: &mut Context<Self>,
 4631    ) -> Option<Task<Result<()>>> {
 4632        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
 4633        self.do_completion(action.item_ix, CompletionIntent::Compose, window, cx)
 4634    }
 4635
 4636    fn do_completion(
 4637        &mut self,
 4638        item_ix: Option<usize>,
 4639        intent: CompletionIntent,
 4640        window: &mut Window,
 4641        cx: &mut Context<Editor>,
 4642    ) -> Option<Task<Result<()>>> {
 4643        use language::ToOffset as _;
 4644
 4645        let CodeContextMenu::Completions(completions_menu) = self.hide_context_menu(window, cx)?
 4646        else {
 4647            return None;
 4648        };
 4649
 4650        let candidate_id = {
 4651            let entries = completions_menu.entries.borrow();
 4652            let mat = entries.get(item_ix.unwrap_or(completions_menu.selected_item))?;
 4653            if self.show_edit_predictions_in_menu() {
 4654                self.discard_inline_completion(true, cx);
 4655            }
 4656            mat.candidate_id
 4657        };
 4658
 4659        let buffer_handle = completions_menu.buffer;
 4660        let completion = completions_menu
 4661            .completions
 4662            .borrow()
 4663            .get(candidate_id)?
 4664            .clone();
 4665        cx.stop_propagation();
 4666
 4667        let snippet;
 4668        let new_text;
 4669        if completion.is_snippet() {
 4670            snippet = Some(Snippet::parse(&completion.new_text).log_err()?);
 4671            new_text = snippet.as_ref().unwrap().text.clone();
 4672        } else {
 4673            snippet = None;
 4674            new_text = completion.new_text.clone();
 4675        };
 4676        let selections = self.selections.all::<usize>(cx);
 4677
 4678        let replace_range = choose_completion_range(&completion, intent, &buffer_handle, cx);
 4679        let buffer = buffer_handle.read(cx);
 4680        let old_text = buffer
 4681            .text_for_range(replace_range.clone())
 4682            .collect::<String>();
 4683
 4684        let newest_selection = self.selections.newest_anchor();
 4685        if newest_selection.start.buffer_id != Some(buffer_handle.read(cx).remote_id()) {
 4686            return None;
 4687        }
 4688
 4689        let lookbehind = newest_selection
 4690            .start
 4691            .text_anchor
 4692            .to_offset(buffer)
 4693            .saturating_sub(replace_range.start);
 4694        let lookahead = replace_range
 4695            .end
 4696            .saturating_sub(newest_selection.end.text_anchor.to_offset(buffer));
 4697        let mut common_prefix_len = 0;
 4698        for (a, b) in old_text.chars().zip(new_text.chars()) {
 4699            if a == b {
 4700                common_prefix_len += a.len_utf8();
 4701            } else {
 4702                break;
 4703            }
 4704        }
 4705
 4706        let snapshot = self.buffer.read(cx).snapshot(cx);
 4707        let mut range_to_replace: Option<Range<usize>> = None;
 4708        let mut ranges = Vec::new();
 4709        let mut linked_edits = HashMap::<_, Vec<_>>::default();
 4710        for selection in &selections {
 4711            if snapshot.contains_str_at(selection.start.saturating_sub(lookbehind), &old_text) {
 4712                let start = selection.start.saturating_sub(lookbehind);
 4713                let end = selection.end + lookahead;
 4714                if selection.id == newest_selection.id {
 4715                    range_to_replace = Some(start + common_prefix_len..end);
 4716                }
 4717                ranges.push(start + common_prefix_len..end);
 4718            } else {
 4719                common_prefix_len = 0;
 4720                ranges.clear();
 4721                ranges.extend(selections.iter().map(|s| {
 4722                    if s.id == newest_selection.id {
 4723                        range_to_replace = Some(replace_range.clone());
 4724                        replace_range.clone()
 4725                    } else {
 4726                        s.start..s.end
 4727                    }
 4728                }));
 4729                break;
 4730            }
 4731            if !self.linked_edit_ranges.is_empty() {
 4732                let start_anchor = snapshot.anchor_before(selection.head());
 4733                let end_anchor = snapshot.anchor_after(selection.tail());
 4734                if let Some(ranges) = self
 4735                    .linked_editing_ranges_for(start_anchor.text_anchor..end_anchor.text_anchor, cx)
 4736                {
 4737                    for (buffer, edits) in ranges {
 4738                        linked_edits.entry(buffer.clone()).or_default().extend(
 4739                            edits
 4740                                .into_iter()
 4741                                .map(|range| (range, new_text[common_prefix_len..].to_owned())),
 4742                        );
 4743                    }
 4744                }
 4745            }
 4746        }
 4747        let text = &new_text[common_prefix_len..];
 4748
 4749        let utf16_range_to_replace = range_to_replace.map(|range| {
 4750            let newest_selection = self.selections.newest::<OffsetUtf16>(cx).range();
 4751            let selection_start_utf16 = newest_selection.start.0 as isize;
 4752
 4753            range.start.to_offset_utf16(&snapshot).0 as isize - selection_start_utf16
 4754                ..range.end.to_offset_utf16(&snapshot).0 as isize - selection_start_utf16
 4755        });
 4756        cx.emit(EditorEvent::InputHandled {
 4757            utf16_range_to_replace,
 4758            text: text.into(),
 4759        });
 4760
 4761        self.transact(window, cx, |this, window, cx| {
 4762            if let Some(mut snippet) = snippet {
 4763                snippet.text = text.to_string();
 4764                for tabstop in snippet
 4765                    .tabstops
 4766                    .iter_mut()
 4767                    .flat_map(|tabstop| tabstop.ranges.iter_mut())
 4768                {
 4769                    tabstop.start -= common_prefix_len as isize;
 4770                    tabstop.end -= common_prefix_len as isize;
 4771                }
 4772
 4773                this.insert_snippet(&ranges, snippet, window, cx).log_err();
 4774            } else {
 4775                this.buffer.update(cx, |buffer, cx| {
 4776                    let edits = ranges.iter().map(|range| (range.clone(), text));
 4777                    let auto_indent = if completion.insert_text_mode == Some(InsertTextMode::AS_IS)
 4778                    {
 4779                        None
 4780                    } else {
 4781                        this.autoindent_mode.clone()
 4782                    };
 4783                    buffer.edit(edits, auto_indent, cx);
 4784                });
 4785            }
 4786            for (buffer, edits) in linked_edits {
 4787                buffer.update(cx, |buffer, cx| {
 4788                    let snapshot = buffer.snapshot();
 4789                    let edits = edits
 4790                        .into_iter()
 4791                        .map(|(range, text)| {
 4792                            use text::ToPoint as TP;
 4793                            let end_point = TP::to_point(&range.end, &snapshot);
 4794                            let start_point = TP::to_point(&range.start, &snapshot);
 4795                            (start_point..end_point, text)
 4796                        })
 4797                        .sorted_by_key(|(range, _)| range.start);
 4798                    buffer.edit(edits, None, cx);
 4799                })
 4800            }
 4801
 4802            this.refresh_inline_completion(true, false, window, cx);
 4803        });
 4804
 4805        let show_new_completions_on_confirm = completion
 4806            .confirm
 4807            .as_ref()
 4808            .map_or(false, |confirm| confirm(intent, window, cx));
 4809        if show_new_completions_on_confirm {
 4810            self.show_completions(&ShowCompletions { trigger: None }, window, cx);
 4811        }
 4812
 4813        let provider = self.completion_provider.as_ref()?;
 4814        drop(completion);
 4815        let apply_edits = provider.apply_additional_edits_for_completion(
 4816            buffer_handle,
 4817            completions_menu.completions.clone(),
 4818            candidate_id,
 4819            true,
 4820            cx,
 4821        );
 4822
 4823        let editor_settings = EditorSettings::get_global(cx);
 4824        if editor_settings.show_signature_help_after_edits || editor_settings.auto_signature_help {
 4825            // After the code completion is finished, users often want to know what signatures are needed.
 4826            // so we should automatically call signature_help
 4827            self.show_signature_help(&ShowSignatureHelp, window, cx);
 4828        }
 4829
 4830        Some(cx.foreground_executor().spawn(async move {
 4831            apply_edits.await?;
 4832            Ok(())
 4833        }))
 4834    }
 4835
 4836    pub fn toggle_code_actions(
 4837        &mut self,
 4838        action: &ToggleCodeActions,
 4839        window: &mut Window,
 4840        cx: &mut Context<Self>,
 4841    ) {
 4842        let mut context_menu = self.context_menu.borrow_mut();
 4843        if let Some(CodeContextMenu::CodeActions(code_actions)) = context_menu.as_ref() {
 4844            if code_actions.deployed_from_indicator == action.deployed_from_indicator {
 4845                // Toggle if we're selecting the same one
 4846                *context_menu = None;
 4847                cx.notify();
 4848                return;
 4849            } else {
 4850                // Otherwise, clear it and start a new one
 4851                *context_menu = None;
 4852                cx.notify();
 4853            }
 4854        }
 4855        drop(context_menu);
 4856        let snapshot = self.snapshot(window, cx);
 4857        let deployed_from_indicator = action.deployed_from_indicator;
 4858        let mut task = self.code_actions_task.take();
 4859        let action = action.clone();
 4860        cx.spawn_in(window, async move |editor, cx| {
 4861            while let Some(prev_task) = task {
 4862                prev_task.await.log_err();
 4863                task = editor.update(cx, |this, _| this.code_actions_task.take())?;
 4864            }
 4865
 4866            let spawned_test_task = editor.update_in(cx, |editor, window, cx| {
 4867                if editor.focus_handle.is_focused(window) {
 4868                    let multibuffer_point = action
 4869                        .deployed_from_indicator
 4870                        .map(|row| DisplayPoint::new(row, 0).to_point(&snapshot))
 4871                        .unwrap_or_else(|| editor.selections.newest::<Point>(cx).head());
 4872                    let (buffer, buffer_row) = snapshot
 4873                        .buffer_snapshot
 4874                        .buffer_line_for_row(MultiBufferRow(multibuffer_point.row))
 4875                        .and_then(|(buffer_snapshot, range)| {
 4876                            editor
 4877                                .buffer
 4878                                .read(cx)
 4879                                .buffer(buffer_snapshot.remote_id())
 4880                                .map(|buffer| (buffer, range.start.row))
 4881                        })?;
 4882                    let (_, code_actions) = editor
 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                    let buffer_id = buffer.read(cx).remote_id();
 4897                    let tasks = editor
 4898                        .tasks
 4899                        .get(&(buffer_id, buffer_row))
 4900                        .map(|t| Arc::new(t.to_owned()));
 4901                    if tasks.is_none() && code_actions.is_none() {
 4902                        return None;
 4903                    }
 4904
 4905                    editor.completion_tasks.clear();
 4906                    editor.discard_inline_completion(false, cx);
 4907                    let task_context =
 4908                        tasks
 4909                            .as_ref()
 4910                            .zip(editor.project.clone())
 4911                            .map(|(tasks, project)| {
 4912                                Self::build_tasks_context(&project, &buffer, buffer_row, tasks, cx)
 4913                            });
 4914
 4915                    let debugger_flag = cx.has_flag::<Debugger>();
 4916
 4917                    Some(cx.spawn_in(window, async move |editor, cx| {
 4918                        let task_context = match task_context {
 4919                            Some(task_context) => task_context.await,
 4920                            None => None,
 4921                        };
 4922                        let resolved_tasks =
 4923                            tasks.zip(task_context).map(|(tasks, task_context)| {
 4924                                Rc::new(ResolvedTasks {
 4925                                    templates: tasks.resolve(&task_context).collect(),
 4926                                    position: snapshot.buffer_snapshot.anchor_before(Point::new(
 4927                                        multibuffer_point.row,
 4928                                        tasks.column,
 4929                                    )),
 4930                                })
 4931                            });
 4932                        let spawn_straight_away = resolved_tasks.as_ref().map_or(false, |tasks| {
 4933                            tasks
 4934                                .templates
 4935                                .iter()
 4936                                .filter(|task| {
 4937                                    if matches!(task.1.task_type(), task::TaskType::Debug(_)) {
 4938                                        debugger_flag
 4939                                    } else {
 4940                                        true
 4941                                    }
 4942                                })
 4943                                .count()
 4944                                == 1
 4945                        }) && code_actions
 4946                            .as_ref()
 4947                            .map_or(true, |actions| actions.is_empty());
 4948                        if let Ok(task) = editor.update_in(cx, |editor, window, cx| {
 4949                            *editor.context_menu.borrow_mut() =
 4950                                Some(CodeContextMenu::CodeActions(CodeActionsMenu {
 4951                                    buffer,
 4952                                    actions: CodeActionContents {
 4953                                        tasks: resolved_tasks,
 4954                                        actions: code_actions,
 4955                                    },
 4956                                    selected_item: Default::default(),
 4957                                    scroll_handle: UniformListScrollHandle::default(),
 4958                                    deployed_from_indicator,
 4959                                }));
 4960                            if spawn_straight_away {
 4961                                if let Some(task) = editor.confirm_code_action(
 4962                                    &ConfirmCodeAction { item_ix: Some(0) },
 4963                                    window,
 4964                                    cx,
 4965                                ) {
 4966                                    cx.notify();
 4967                                    return task;
 4968                                }
 4969                            }
 4970                            cx.notify();
 4971                            Task::ready(Ok(()))
 4972                        }) {
 4973                            task.await
 4974                        } else {
 4975                            Ok(())
 4976                        }
 4977                    }))
 4978                } else {
 4979                    Some(Task::ready(Ok(())))
 4980                }
 4981            })?;
 4982            if let Some(task) = spawned_test_task {
 4983                task.await?;
 4984            }
 4985
 4986            Ok::<_, anyhow::Error>(())
 4987        })
 4988        .detach_and_log_err(cx);
 4989    }
 4990
 4991    pub fn confirm_code_action(
 4992        &mut self,
 4993        action: &ConfirmCodeAction,
 4994        window: &mut Window,
 4995        cx: &mut Context<Self>,
 4996    ) -> Option<Task<Result<()>>> {
 4997        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
 4998
 4999        let actions_menu =
 5000            if let CodeContextMenu::CodeActions(menu) = self.hide_context_menu(window, cx)? {
 5001                menu
 5002            } else {
 5003                return None;
 5004            };
 5005
 5006        let action_ix = action.item_ix.unwrap_or(actions_menu.selected_item);
 5007        let action = actions_menu.actions.get(action_ix)?;
 5008        let title = action.label();
 5009        let buffer = actions_menu.buffer;
 5010        let workspace = self.workspace()?;
 5011
 5012        match action {
 5013            CodeActionsItem::Task(task_source_kind, resolved_task) => {
 5014                match resolved_task.task_type() {
 5015                    task::TaskType::Script => workspace.update(cx, |workspace, cx| {
 5016                        workspace::tasks::schedule_resolved_task(
 5017                            workspace,
 5018                            task_source_kind,
 5019                            resolved_task,
 5020                            false,
 5021                            cx,
 5022                        );
 5023
 5024                        Some(Task::ready(Ok(())))
 5025                    }),
 5026                    task::TaskType::Debug(debug_args) => {
 5027                        if debug_args.locator.is_some() {
 5028                            workspace.update(cx, |workspace, cx| {
 5029                                workspace::tasks::schedule_resolved_task(
 5030                                    workspace,
 5031                                    task_source_kind,
 5032                                    resolved_task,
 5033                                    false,
 5034                                    cx,
 5035                                );
 5036                            });
 5037
 5038                            return Some(Task::ready(Ok(())));
 5039                        }
 5040
 5041                        if let Some(project) = self.project.as_ref() {
 5042                            project
 5043                                .update(cx, |project, cx| {
 5044                                    project.start_debug_session(
 5045                                        resolved_task.resolved_debug_adapter_config().unwrap(),
 5046                                        cx,
 5047                                    )
 5048                                })
 5049                                .detach_and_log_err(cx);
 5050                            Some(Task::ready(Ok(())))
 5051                        } else {
 5052                            Some(Task::ready(Ok(())))
 5053                        }
 5054                    }
 5055                }
 5056            }
 5057            CodeActionsItem::CodeAction {
 5058                excerpt_id,
 5059                action,
 5060                provider,
 5061            } => {
 5062                let apply_code_action =
 5063                    provider.apply_code_action(buffer, action, excerpt_id, true, window, cx);
 5064                let workspace = workspace.downgrade();
 5065                Some(cx.spawn_in(window, async move |editor, cx| {
 5066                    let project_transaction = apply_code_action.await?;
 5067                    Self::open_project_transaction(
 5068                        &editor,
 5069                        workspace,
 5070                        project_transaction,
 5071                        title,
 5072                        cx,
 5073                    )
 5074                    .await
 5075                }))
 5076            }
 5077        }
 5078    }
 5079
 5080    pub async fn open_project_transaction(
 5081        this: &WeakEntity<Editor>,
 5082        workspace: WeakEntity<Workspace>,
 5083        transaction: ProjectTransaction,
 5084        title: String,
 5085        cx: &mut AsyncWindowContext,
 5086    ) -> Result<()> {
 5087        let mut entries = transaction.0.into_iter().collect::<Vec<_>>();
 5088        cx.update(|_, cx| {
 5089            entries.sort_unstable_by_key(|(buffer, _)| {
 5090                buffer.read(cx).file().map(|f| f.path().clone())
 5091            });
 5092        })?;
 5093
 5094        // If the project transaction's edits are all contained within this editor, then
 5095        // avoid opening a new editor to display them.
 5096
 5097        if let Some((buffer, transaction)) = entries.first() {
 5098            if entries.len() == 1 {
 5099                let excerpt = this.update(cx, |editor, cx| {
 5100                    editor
 5101                        .buffer()
 5102                        .read(cx)
 5103                        .excerpt_containing(editor.selections.newest_anchor().head(), cx)
 5104                })?;
 5105                if let Some((_, excerpted_buffer, excerpt_range)) = excerpt {
 5106                    if excerpted_buffer == *buffer {
 5107                        let all_edits_within_excerpt = buffer.read_with(cx, |buffer, _| {
 5108                            let excerpt_range = excerpt_range.to_offset(buffer);
 5109                            buffer
 5110                                .edited_ranges_for_transaction::<usize>(transaction)
 5111                                .all(|range| {
 5112                                    excerpt_range.start <= range.start
 5113                                        && excerpt_range.end >= range.end
 5114                                })
 5115                        })?;
 5116
 5117                        if all_edits_within_excerpt {
 5118                            return Ok(());
 5119                        }
 5120                    }
 5121                }
 5122            }
 5123        } else {
 5124            return Ok(());
 5125        }
 5126
 5127        let mut ranges_to_highlight = Vec::new();
 5128        let excerpt_buffer = cx.new(|cx| {
 5129            let mut multibuffer = MultiBuffer::new(Capability::ReadWrite).with_title(title);
 5130            for (buffer_handle, transaction) in &entries {
 5131                let edited_ranges = buffer_handle
 5132                    .read(cx)
 5133                    .edited_ranges_for_transaction::<Point>(transaction)
 5134                    .collect::<Vec<_>>();
 5135                let (ranges, _) = multibuffer.set_excerpts_for_path(
 5136                    PathKey::for_buffer(buffer_handle, cx),
 5137                    buffer_handle.clone(),
 5138                    edited_ranges,
 5139                    DEFAULT_MULTIBUFFER_CONTEXT,
 5140                    cx,
 5141                );
 5142
 5143                ranges_to_highlight.extend(ranges);
 5144            }
 5145            multibuffer.push_transaction(entries.iter().map(|(b, t)| (b, t)), cx);
 5146            multibuffer
 5147        })?;
 5148
 5149        workspace.update_in(cx, |workspace, window, cx| {
 5150            let project = workspace.project().clone();
 5151            let editor =
 5152                cx.new(|cx| Editor::for_multibuffer(excerpt_buffer, Some(project), window, cx));
 5153            workspace.add_item_to_active_pane(Box::new(editor.clone()), None, true, window, cx);
 5154            editor.update(cx, |editor, cx| {
 5155                editor.highlight_background::<Self>(
 5156                    &ranges_to_highlight,
 5157                    |theme| theme.editor_highlighted_line_background,
 5158                    cx,
 5159                );
 5160            });
 5161        })?;
 5162
 5163        Ok(())
 5164    }
 5165
 5166    pub fn clear_code_action_providers(&mut self) {
 5167        self.code_action_providers.clear();
 5168        self.available_code_actions.take();
 5169    }
 5170
 5171    pub fn add_code_action_provider(
 5172        &mut self,
 5173        provider: Rc<dyn CodeActionProvider>,
 5174        window: &mut Window,
 5175        cx: &mut Context<Self>,
 5176    ) {
 5177        if self
 5178            .code_action_providers
 5179            .iter()
 5180            .any(|existing_provider| existing_provider.id() == provider.id())
 5181        {
 5182            return;
 5183        }
 5184
 5185        self.code_action_providers.push(provider);
 5186        self.refresh_code_actions(window, cx);
 5187    }
 5188
 5189    pub fn remove_code_action_provider(
 5190        &mut self,
 5191        id: Arc<str>,
 5192        window: &mut Window,
 5193        cx: &mut Context<Self>,
 5194    ) {
 5195        self.code_action_providers
 5196            .retain(|provider| provider.id() != id);
 5197        self.refresh_code_actions(window, cx);
 5198    }
 5199
 5200    fn refresh_code_actions(&mut self, window: &mut Window, cx: &mut Context<Self>) -> Option<()> {
 5201        let newest_selection = self.selections.newest_anchor().clone();
 5202        let newest_selection_adjusted = self.selections.newest_adjusted(cx).clone();
 5203        let buffer = self.buffer.read(cx);
 5204        if newest_selection.head().diff_base_anchor.is_some() {
 5205            return None;
 5206        }
 5207        let (start_buffer, start) =
 5208            buffer.text_anchor_for_position(newest_selection_adjusted.start, cx)?;
 5209        let (end_buffer, end) =
 5210            buffer.text_anchor_for_position(newest_selection_adjusted.end, cx)?;
 5211        if start_buffer != end_buffer {
 5212            return None;
 5213        }
 5214
 5215        self.code_actions_task = Some(cx.spawn_in(window, async move |this, cx| {
 5216            cx.background_executor()
 5217                .timer(CODE_ACTIONS_DEBOUNCE_TIMEOUT)
 5218                .await;
 5219
 5220            let (providers, tasks) = this.update_in(cx, |this, window, cx| {
 5221                let providers = this.code_action_providers.clone();
 5222                let tasks = this
 5223                    .code_action_providers
 5224                    .iter()
 5225                    .map(|provider| provider.code_actions(&start_buffer, start..end, window, cx))
 5226                    .collect::<Vec<_>>();
 5227                (providers, tasks)
 5228            })?;
 5229
 5230            let mut actions = Vec::new();
 5231            for (provider, provider_actions) in
 5232                providers.into_iter().zip(future::join_all(tasks).await)
 5233            {
 5234                if let Some(provider_actions) = provider_actions.log_err() {
 5235                    actions.extend(provider_actions.into_iter().map(|action| {
 5236                        AvailableCodeAction {
 5237                            excerpt_id: newest_selection.start.excerpt_id,
 5238                            action,
 5239                            provider: provider.clone(),
 5240                        }
 5241                    }));
 5242                }
 5243            }
 5244
 5245            this.update(cx, |this, cx| {
 5246                this.available_code_actions = if actions.is_empty() {
 5247                    None
 5248                } else {
 5249                    Some((
 5250                        Location {
 5251                            buffer: start_buffer,
 5252                            range: start..end,
 5253                        },
 5254                        actions.into(),
 5255                    ))
 5256                };
 5257                cx.notify();
 5258            })
 5259        }));
 5260        None
 5261    }
 5262
 5263    fn start_inline_blame_timer(&mut self, window: &mut Window, cx: &mut Context<Self>) {
 5264        if let Some(delay) = ProjectSettings::get_global(cx).git.inline_blame_delay() {
 5265            self.show_git_blame_inline = false;
 5266
 5267            self.show_git_blame_inline_delay_task =
 5268                Some(cx.spawn_in(window, async move |this, cx| {
 5269                    cx.background_executor().timer(delay).await;
 5270
 5271                    this.update(cx, |this, cx| {
 5272                        this.show_git_blame_inline = true;
 5273                        cx.notify();
 5274                    })
 5275                    .log_err();
 5276                }));
 5277        }
 5278    }
 5279
 5280    fn refresh_document_highlights(&mut self, cx: &mut Context<Self>) -> Option<()> {
 5281        if self.pending_rename.is_some() {
 5282            return None;
 5283        }
 5284
 5285        let provider = self.semantics_provider.clone()?;
 5286        let buffer = self.buffer.read(cx);
 5287        let newest_selection = self.selections.newest_anchor().clone();
 5288        let cursor_position = newest_selection.head();
 5289        let (cursor_buffer, cursor_buffer_position) =
 5290            buffer.text_anchor_for_position(cursor_position, cx)?;
 5291        let (tail_buffer, _) = buffer.text_anchor_for_position(newest_selection.tail(), cx)?;
 5292        if cursor_buffer != tail_buffer {
 5293            return None;
 5294        }
 5295        let debounce = EditorSettings::get_global(cx).lsp_highlight_debounce;
 5296        self.document_highlights_task = Some(cx.spawn(async move |this, cx| {
 5297            cx.background_executor()
 5298                .timer(Duration::from_millis(debounce))
 5299                .await;
 5300
 5301            let highlights = if let Some(highlights) = cx
 5302                .update(|cx| {
 5303                    provider.document_highlights(&cursor_buffer, cursor_buffer_position, cx)
 5304                })
 5305                .ok()
 5306                .flatten()
 5307            {
 5308                highlights.await.log_err()
 5309            } else {
 5310                None
 5311            };
 5312
 5313            if let Some(highlights) = highlights {
 5314                this.update(cx, |this, cx| {
 5315                    if this.pending_rename.is_some() {
 5316                        return;
 5317                    }
 5318
 5319                    let buffer_id = cursor_position.buffer_id;
 5320                    let buffer = this.buffer.read(cx);
 5321                    if !buffer
 5322                        .text_anchor_for_position(cursor_position, cx)
 5323                        .map_or(false, |(buffer, _)| buffer == cursor_buffer)
 5324                    {
 5325                        return;
 5326                    }
 5327
 5328                    let cursor_buffer_snapshot = cursor_buffer.read(cx);
 5329                    let mut write_ranges = Vec::new();
 5330                    let mut read_ranges = Vec::new();
 5331                    for highlight in highlights {
 5332                        for (excerpt_id, excerpt_range) in
 5333                            buffer.excerpts_for_buffer(cursor_buffer.read(cx).remote_id(), cx)
 5334                        {
 5335                            let start = highlight
 5336                                .range
 5337                                .start
 5338                                .max(&excerpt_range.context.start, cursor_buffer_snapshot);
 5339                            let end = highlight
 5340                                .range
 5341                                .end
 5342                                .min(&excerpt_range.context.end, cursor_buffer_snapshot);
 5343                            if start.cmp(&end, cursor_buffer_snapshot).is_ge() {
 5344                                continue;
 5345                            }
 5346
 5347                            let range = Anchor {
 5348                                buffer_id,
 5349                                excerpt_id,
 5350                                text_anchor: start,
 5351                                diff_base_anchor: None,
 5352                            }..Anchor {
 5353                                buffer_id,
 5354                                excerpt_id,
 5355                                text_anchor: end,
 5356                                diff_base_anchor: None,
 5357                            };
 5358                            if highlight.kind == lsp::DocumentHighlightKind::WRITE {
 5359                                write_ranges.push(range);
 5360                            } else {
 5361                                read_ranges.push(range);
 5362                            }
 5363                        }
 5364                    }
 5365
 5366                    this.highlight_background::<DocumentHighlightRead>(
 5367                        &read_ranges,
 5368                        |theme| theme.editor_document_highlight_read_background,
 5369                        cx,
 5370                    );
 5371                    this.highlight_background::<DocumentHighlightWrite>(
 5372                        &write_ranges,
 5373                        |theme| theme.editor_document_highlight_write_background,
 5374                        cx,
 5375                    );
 5376                    cx.notify();
 5377                })
 5378                .log_err();
 5379            }
 5380        }));
 5381        None
 5382    }
 5383
 5384    pub fn refresh_selected_text_highlights(
 5385        &mut self,
 5386        window: &mut Window,
 5387        cx: &mut Context<Editor>,
 5388    ) {
 5389        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 5390            return;
 5391        }
 5392        self.selection_highlight_task.take();
 5393        if !EditorSettings::get_global(cx).selection_highlight {
 5394            self.clear_background_highlights::<SelectedTextHighlight>(cx);
 5395            return;
 5396        }
 5397        if self.selections.count() != 1 || self.selections.line_mode {
 5398            self.clear_background_highlights::<SelectedTextHighlight>(cx);
 5399            return;
 5400        }
 5401        let selection = self.selections.newest::<Point>(cx);
 5402        if selection.is_empty() || selection.start.row != selection.end.row {
 5403            self.clear_background_highlights::<SelectedTextHighlight>(cx);
 5404            return;
 5405        }
 5406        let debounce = EditorSettings::get_global(cx).selection_highlight_debounce;
 5407        self.selection_highlight_task = Some(cx.spawn_in(window, async move |editor, cx| {
 5408            cx.background_executor()
 5409                .timer(Duration::from_millis(debounce))
 5410                .await;
 5411            let Some(Some(matches_task)) = editor
 5412                .update_in(cx, |editor, _, cx| {
 5413                    if editor.selections.count() != 1 || editor.selections.line_mode {
 5414                        editor.clear_background_highlights::<SelectedTextHighlight>(cx);
 5415                        return None;
 5416                    }
 5417                    let selection = editor.selections.newest::<Point>(cx);
 5418                    if selection.is_empty() || selection.start.row != selection.end.row {
 5419                        editor.clear_background_highlights::<SelectedTextHighlight>(cx);
 5420                        return None;
 5421                    }
 5422                    let buffer = editor.buffer().read(cx).snapshot(cx);
 5423                    let query = buffer.text_for_range(selection.range()).collect::<String>();
 5424                    if query.trim().is_empty() {
 5425                        editor.clear_background_highlights::<SelectedTextHighlight>(cx);
 5426                        return None;
 5427                    }
 5428                    Some(cx.background_spawn(async move {
 5429                        let mut ranges = Vec::new();
 5430                        let selection_anchors = selection.range().to_anchors(&buffer);
 5431                        for range in [buffer.anchor_before(0)..buffer.anchor_after(buffer.len())] {
 5432                            for (search_buffer, search_range, excerpt_id) in
 5433                                buffer.range_to_buffer_ranges(range)
 5434                            {
 5435                                ranges.extend(
 5436                                    project::search::SearchQuery::text(
 5437                                        query.clone(),
 5438                                        false,
 5439                                        false,
 5440                                        false,
 5441                                        Default::default(),
 5442                                        Default::default(),
 5443                                        None,
 5444                                    )
 5445                                    .unwrap()
 5446                                    .search(search_buffer, Some(search_range.clone()))
 5447                                    .await
 5448                                    .into_iter()
 5449                                    .filter_map(
 5450                                        |match_range| {
 5451                                            let start = search_buffer.anchor_after(
 5452                                                search_range.start + match_range.start,
 5453                                            );
 5454                                            let end = search_buffer.anchor_before(
 5455                                                search_range.start + match_range.end,
 5456                                            );
 5457                                            let range = Anchor::range_in_buffer(
 5458                                                excerpt_id,
 5459                                                search_buffer.remote_id(),
 5460                                                start..end,
 5461                                            );
 5462                                            (range != selection_anchors).then_some(range)
 5463                                        },
 5464                                    ),
 5465                                );
 5466                            }
 5467                        }
 5468                        ranges
 5469                    }))
 5470                })
 5471                .log_err()
 5472            else {
 5473                return;
 5474            };
 5475            let matches = matches_task.await;
 5476            editor
 5477                .update_in(cx, |editor, _, cx| {
 5478                    editor.clear_background_highlights::<SelectedTextHighlight>(cx);
 5479                    if !matches.is_empty() {
 5480                        editor.highlight_background::<SelectedTextHighlight>(
 5481                            &matches,
 5482                            |theme| theme.editor_document_highlight_bracket_background,
 5483                            cx,
 5484                        )
 5485                    }
 5486                })
 5487                .log_err();
 5488        }));
 5489    }
 5490
 5491    pub fn refresh_inline_completion(
 5492        &mut self,
 5493        debounce: bool,
 5494        user_requested: bool,
 5495        window: &mut Window,
 5496        cx: &mut Context<Self>,
 5497    ) -> Option<()> {
 5498        let provider = self.edit_prediction_provider()?;
 5499        let cursor = self.selections.newest_anchor().head();
 5500        let (buffer, cursor_buffer_position) =
 5501            self.buffer.read(cx).text_anchor_for_position(cursor, cx)?;
 5502
 5503        if !self.edit_predictions_enabled_in_buffer(&buffer, cursor_buffer_position, cx) {
 5504            self.discard_inline_completion(false, cx);
 5505            return None;
 5506        }
 5507
 5508        if !user_requested
 5509            && (!self.should_show_edit_predictions()
 5510                || !self.is_focused(window)
 5511                || buffer.read(cx).is_empty())
 5512        {
 5513            self.discard_inline_completion(false, cx);
 5514            return None;
 5515        }
 5516
 5517        self.update_visible_inline_completion(window, cx);
 5518        provider.refresh(
 5519            self.project.clone(),
 5520            buffer,
 5521            cursor_buffer_position,
 5522            debounce,
 5523            cx,
 5524        );
 5525        Some(())
 5526    }
 5527
 5528    fn show_edit_predictions_in_menu(&self) -> bool {
 5529        match self.edit_prediction_settings {
 5530            EditPredictionSettings::Disabled => false,
 5531            EditPredictionSettings::Enabled { show_in_menu, .. } => show_in_menu,
 5532        }
 5533    }
 5534
 5535    pub fn edit_predictions_enabled(&self) -> bool {
 5536        match self.edit_prediction_settings {
 5537            EditPredictionSettings::Disabled => false,
 5538            EditPredictionSettings::Enabled { .. } => true,
 5539        }
 5540    }
 5541
 5542    fn edit_prediction_requires_modifier(&self) -> bool {
 5543        match self.edit_prediction_settings {
 5544            EditPredictionSettings::Disabled => false,
 5545            EditPredictionSettings::Enabled {
 5546                preview_requires_modifier,
 5547                ..
 5548            } => preview_requires_modifier,
 5549        }
 5550    }
 5551
 5552    pub fn update_edit_prediction_settings(&mut self, cx: &mut Context<Self>) {
 5553        if self.edit_prediction_provider.is_none() {
 5554            self.edit_prediction_settings = EditPredictionSettings::Disabled;
 5555        } else {
 5556            let selection = self.selections.newest_anchor();
 5557            let cursor = selection.head();
 5558
 5559            if let Some((buffer, cursor_buffer_position)) =
 5560                self.buffer.read(cx).text_anchor_for_position(cursor, cx)
 5561            {
 5562                self.edit_prediction_settings =
 5563                    self.edit_prediction_settings_at_position(&buffer, cursor_buffer_position, cx);
 5564            }
 5565        }
 5566    }
 5567
 5568    fn edit_prediction_settings_at_position(
 5569        &self,
 5570        buffer: &Entity<Buffer>,
 5571        buffer_position: language::Anchor,
 5572        cx: &App,
 5573    ) -> EditPredictionSettings {
 5574        if !self.mode.is_full()
 5575            || !self.show_inline_completions_override.unwrap_or(true)
 5576            || self.inline_completions_disabled_in_scope(buffer, buffer_position, cx)
 5577        {
 5578            return EditPredictionSettings::Disabled;
 5579        }
 5580
 5581        let buffer = buffer.read(cx);
 5582
 5583        let file = buffer.file();
 5584
 5585        if !language_settings(buffer.language().map(|l| l.name()), file, cx).show_edit_predictions {
 5586            return EditPredictionSettings::Disabled;
 5587        };
 5588
 5589        let by_provider = matches!(
 5590            self.menu_inline_completions_policy,
 5591            MenuInlineCompletionsPolicy::ByProvider
 5592        );
 5593
 5594        let show_in_menu = by_provider
 5595            && self
 5596                .edit_prediction_provider
 5597                .as_ref()
 5598                .map_or(false, |provider| {
 5599                    provider.provider.show_completions_in_menu()
 5600                });
 5601
 5602        let preview_requires_modifier =
 5603            all_language_settings(file, cx).edit_predictions_mode() == EditPredictionsMode::Subtle;
 5604
 5605        EditPredictionSettings::Enabled {
 5606            show_in_menu,
 5607            preview_requires_modifier,
 5608        }
 5609    }
 5610
 5611    fn should_show_edit_predictions(&self) -> bool {
 5612        self.snippet_stack.is_empty() && self.edit_predictions_enabled()
 5613    }
 5614
 5615    pub fn edit_prediction_preview_is_active(&self) -> bool {
 5616        matches!(
 5617            self.edit_prediction_preview,
 5618            EditPredictionPreview::Active { .. }
 5619        )
 5620    }
 5621
 5622    pub fn edit_predictions_enabled_at_cursor(&self, cx: &App) -> bool {
 5623        let cursor = self.selections.newest_anchor().head();
 5624        if let Some((buffer, cursor_position)) =
 5625            self.buffer.read(cx).text_anchor_for_position(cursor, cx)
 5626        {
 5627            self.edit_predictions_enabled_in_buffer(&buffer, cursor_position, cx)
 5628        } else {
 5629            false
 5630        }
 5631    }
 5632
 5633    fn edit_predictions_enabled_in_buffer(
 5634        &self,
 5635        buffer: &Entity<Buffer>,
 5636        buffer_position: language::Anchor,
 5637        cx: &App,
 5638    ) -> bool {
 5639        maybe!({
 5640            if self.read_only(cx) {
 5641                return Some(false);
 5642            }
 5643            let provider = self.edit_prediction_provider()?;
 5644            if !provider.is_enabled(&buffer, buffer_position, cx) {
 5645                return Some(false);
 5646            }
 5647            let buffer = buffer.read(cx);
 5648            let Some(file) = buffer.file() else {
 5649                return Some(true);
 5650            };
 5651            let settings = all_language_settings(Some(file), cx);
 5652            Some(settings.edit_predictions_enabled_for_file(file, cx))
 5653        })
 5654        .unwrap_or(false)
 5655    }
 5656
 5657    fn cycle_inline_completion(
 5658        &mut self,
 5659        direction: Direction,
 5660        window: &mut Window,
 5661        cx: &mut Context<Self>,
 5662    ) -> Option<()> {
 5663        let provider = self.edit_prediction_provider()?;
 5664        let cursor = self.selections.newest_anchor().head();
 5665        let (buffer, cursor_buffer_position) =
 5666            self.buffer.read(cx).text_anchor_for_position(cursor, cx)?;
 5667        if self.inline_completions_hidden_for_vim_mode || !self.should_show_edit_predictions() {
 5668            return None;
 5669        }
 5670
 5671        provider.cycle(buffer, cursor_buffer_position, direction, cx);
 5672        self.update_visible_inline_completion(window, cx);
 5673
 5674        Some(())
 5675    }
 5676
 5677    pub fn show_inline_completion(
 5678        &mut self,
 5679        _: &ShowEditPrediction,
 5680        window: &mut Window,
 5681        cx: &mut Context<Self>,
 5682    ) {
 5683        if !self.has_active_inline_completion() {
 5684            self.refresh_inline_completion(false, true, window, cx);
 5685            return;
 5686        }
 5687
 5688        self.update_visible_inline_completion(window, cx);
 5689    }
 5690
 5691    pub fn display_cursor_names(
 5692        &mut self,
 5693        _: &DisplayCursorNames,
 5694        window: &mut Window,
 5695        cx: &mut Context<Self>,
 5696    ) {
 5697        self.show_cursor_names(window, cx);
 5698    }
 5699
 5700    fn show_cursor_names(&mut self, window: &mut Window, cx: &mut Context<Self>) {
 5701        self.show_cursor_names = true;
 5702        cx.notify();
 5703        cx.spawn_in(window, async move |this, cx| {
 5704            cx.background_executor().timer(CURSORS_VISIBLE_FOR).await;
 5705            this.update(cx, |this, cx| {
 5706                this.show_cursor_names = false;
 5707                cx.notify()
 5708            })
 5709            .ok()
 5710        })
 5711        .detach();
 5712    }
 5713
 5714    pub fn next_edit_prediction(
 5715        &mut self,
 5716        _: &NextEditPrediction,
 5717        window: &mut Window,
 5718        cx: &mut Context<Self>,
 5719    ) {
 5720        if self.has_active_inline_completion() {
 5721            self.cycle_inline_completion(Direction::Next, window, cx);
 5722        } else {
 5723            let is_copilot_disabled = self
 5724                .refresh_inline_completion(false, true, window, cx)
 5725                .is_none();
 5726            if is_copilot_disabled {
 5727                cx.propagate();
 5728            }
 5729        }
 5730    }
 5731
 5732    pub fn previous_edit_prediction(
 5733        &mut self,
 5734        _: &PreviousEditPrediction,
 5735        window: &mut Window,
 5736        cx: &mut Context<Self>,
 5737    ) {
 5738        if self.has_active_inline_completion() {
 5739            self.cycle_inline_completion(Direction::Prev, window, cx);
 5740        } else {
 5741            let is_copilot_disabled = self
 5742                .refresh_inline_completion(false, true, window, cx)
 5743                .is_none();
 5744            if is_copilot_disabled {
 5745                cx.propagate();
 5746            }
 5747        }
 5748    }
 5749
 5750    pub fn accept_edit_prediction(
 5751        &mut self,
 5752        _: &AcceptEditPrediction,
 5753        window: &mut Window,
 5754        cx: &mut Context<Self>,
 5755    ) {
 5756        if self.show_edit_predictions_in_menu() {
 5757            self.hide_context_menu(window, cx);
 5758        }
 5759
 5760        let Some(active_inline_completion) = self.active_inline_completion.as_ref() else {
 5761            return;
 5762        };
 5763
 5764        self.report_inline_completion_event(
 5765            active_inline_completion.completion_id.clone(),
 5766            true,
 5767            cx,
 5768        );
 5769
 5770        match &active_inline_completion.completion {
 5771            InlineCompletion::Move { target, .. } => {
 5772                let target = *target;
 5773
 5774                if let Some(position_map) = &self.last_position_map {
 5775                    if position_map
 5776                        .visible_row_range
 5777                        .contains(&target.to_display_point(&position_map.snapshot).row())
 5778                        || !self.edit_prediction_requires_modifier()
 5779                    {
 5780                        self.unfold_ranges(&[target..target], true, false, cx);
 5781                        // Note that this is also done in vim's handler of the Tab action.
 5782                        self.change_selections(
 5783                            Some(Autoscroll::newest()),
 5784                            window,
 5785                            cx,
 5786                            |selections| {
 5787                                selections.select_anchor_ranges([target..target]);
 5788                            },
 5789                        );
 5790                        self.clear_row_highlights::<EditPredictionPreview>();
 5791
 5792                        self.edit_prediction_preview
 5793                            .set_previous_scroll_position(None);
 5794                    } else {
 5795                        self.edit_prediction_preview
 5796                            .set_previous_scroll_position(Some(
 5797                                position_map.snapshot.scroll_anchor,
 5798                            ));
 5799
 5800                        self.highlight_rows::<EditPredictionPreview>(
 5801                            target..target,
 5802                            cx.theme().colors().editor_highlighted_line_background,
 5803                            true,
 5804                            cx,
 5805                        );
 5806                        self.request_autoscroll(Autoscroll::fit(), cx);
 5807                    }
 5808                }
 5809            }
 5810            InlineCompletion::Edit { edits, .. } => {
 5811                if let Some(provider) = self.edit_prediction_provider() {
 5812                    provider.accept(cx);
 5813                }
 5814
 5815                let snapshot = self.buffer.read(cx).snapshot(cx);
 5816                let last_edit_end = edits.last().unwrap().0.end.bias_right(&snapshot);
 5817
 5818                self.buffer.update(cx, |buffer, cx| {
 5819                    buffer.edit(edits.iter().cloned(), None, cx)
 5820                });
 5821
 5822                self.change_selections(None, window, cx, |s| {
 5823                    s.select_anchor_ranges([last_edit_end..last_edit_end])
 5824                });
 5825
 5826                self.update_visible_inline_completion(window, cx);
 5827                if self.active_inline_completion.is_none() {
 5828                    self.refresh_inline_completion(true, true, window, cx);
 5829                }
 5830
 5831                cx.notify();
 5832            }
 5833        }
 5834
 5835        self.edit_prediction_requires_modifier_in_indent_conflict = false;
 5836    }
 5837
 5838    pub fn accept_partial_inline_completion(
 5839        &mut self,
 5840        _: &AcceptPartialEditPrediction,
 5841        window: &mut Window,
 5842        cx: &mut Context<Self>,
 5843    ) {
 5844        let Some(active_inline_completion) = self.active_inline_completion.as_ref() else {
 5845            return;
 5846        };
 5847        if self.selections.count() != 1 {
 5848            return;
 5849        }
 5850
 5851        self.report_inline_completion_event(
 5852            active_inline_completion.completion_id.clone(),
 5853            true,
 5854            cx,
 5855        );
 5856
 5857        match &active_inline_completion.completion {
 5858            InlineCompletion::Move { target, .. } => {
 5859                let target = *target;
 5860                self.change_selections(Some(Autoscroll::newest()), window, cx, |selections| {
 5861                    selections.select_anchor_ranges([target..target]);
 5862                });
 5863            }
 5864            InlineCompletion::Edit { edits, .. } => {
 5865                // Find an insertion that starts at the cursor position.
 5866                let snapshot = self.buffer.read(cx).snapshot(cx);
 5867                let cursor_offset = self.selections.newest::<usize>(cx).head();
 5868                let insertion = edits.iter().find_map(|(range, text)| {
 5869                    let range = range.to_offset(&snapshot);
 5870                    if range.is_empty() && range.start == cursor_offset {
 5871                        Some(text)
 5872                    } else {
 5873                        None
 5874                    }
 5875                });
 5876
 5877                if let Some(text) = insertion {
 5878                    let mut partial_completion = text
 5879                        .chars()
 5880                        .by_ref()
 5881                        .take_while(|c| c.is_alphabetic())
 5882                        .collect::<String>();
 5883                    if partial_completion.is_empty() {
 5884                        partial_completion = text
 5885                            .chars()
 5886                            .by_ref()
 5887                            .take_while(|c| c.is_whitespace() || !c.is_alphabetic())
 5888                            .collect::<String>();
 5889                    }
 5890
 5891                    cx.emit(EditorEvent::InputHandled {
 5892                        utf16_range_to_replace: None,
 5893                        text: partial_completion.clone().into(),
 5894                    });
 5895
 5896                    self.insert_with_autoindent_mode(&partial_completion, None, window, cx);
 5897
 5898                    self.refresh_inline_completion(true, true, window, cx);
 5899                    cx.notify();
 5900                } else {
 5901                    self.accept_edit_prediction(&Default::default(), window, cx);
 5902                }
 5903            }
 5904        }
 5905    }
 5906
 5907    fn discard_inline_completion(
 5908        &mut self,
 5909        should_report_inline_completion_event: bool,
 5910        cx: &mut Context<Self>,
 5911    ) -> bool {
 5912        if should_report_inline_completion_event {
 5913            let completion_id = self
 5914                .active_inline_completion
 5915                .as_ref()
 5916                .and_then(|active_completion| active_completion.completion_id.clone());
 5917
 5918            self.report_inline_completion_event(completion_id, false, cx);
 5919        }
 5920
 5921        if let Some(provider) = self.edit_prediction_provider() {
 5922            provider.discard(cx);
 5923        }
 5924
 5925        self.take_active_inline_completion(cx)
 5926    }
 5927
 5928    fn report_inline_completion_event(&self, id: Option<SharedString>, accepted: bool, cx: &App) {
 5929        let Some(provider) = self.edit_prediction_provider() else {
 5930            return;
 5931        };
 5932
 5933        let Some((_, buffer, _)) = self
 5934            .buffer
 5935            .read(cx)
 5936            .excerpt_containing(self.selections.newest_anchor().head(), cx)
 5937        else {
 5938            return;
 5939        };
 5940
 5941        let extension = buffer
 5942            .read(cx)
 5943            .file()
 5944            .and_then(|file| Some(file.path().extension()?.to_string_lossy().to_string()));
 5945
 5946        let event_type = match accepted {
 5947            true => "Edit Prediction Accepted",
 5948            false => "Edit Prediction Discarded",
 5949        };
 5950        telemetry::event!(
 5951            event_type,
 5952            provider = provider.name(),
 5953            prediction_id = id,
 5954            suggestion_accepted = accepted,
 5955            file_extension = extension,
 5956        );
 5957    }
 5958
 5959    pub fn has_active_inline_completion(&self) -> bool {
 5960        self.active_inline_completion.is_some()
 5961    }
 5962
 5963    fn take_active_inline_completion(&mut self, cx: &mut Context<Self>) -> bool {
 5964        let Some(active_inline_completion) = self.active_inline_completion.take() else {
 5965            return false;
 5966        };
 5967
 5968        self.splice_inlays(&active_inline_completion.inlay_ids, Default::default(), cx);
 5969        self.clear_highlights::<InlineCompletionHighlight>(cx);
 5970        self.stale_inline_completion_in_menu = Some(active_inline_completion);
 5971        true
 5972    }
 5973
 5974    /// Returns true when we're displaying the edit prediction popover below the cursor
 5975    /// like we are not previewing and the LSP autocomplete menu is visible
 5976    /// or we are in `when_holding_modifier` mode.
 5977    pub fn edit_prediction_visible_in_cursor_popover(&self, has_completion: bool) -> bool {
 5978        if self.edit_prediction_preview_is_active()
 5979            || !self.show_edit_predictions_in_menu()
 5980            || !self.edit_predictions_enabled()
 5981        {
 5982            return false;
 5983        }
 5984
 5985        if self.has_visible_completions_menu() {
 5986            return true;
 5987        }
 5988
 5989        has_completion && self.edit_prediction_requires_modifier()
 5990    }
 5991
 5992    fn handle_modifiers_changed(
 5993        &mut self,
 5994        modifiers: Modifiers,
 5995        position_map: &PositionMap,
 5996        window: &mut Window,
 5997        cx: &mut Context<Self>,
 5998    ) {
 5999        if self.show_edit_predictions_in_menu() {
 6000            self.update_edit_prediction_preview(&modifiers, window, cx);
 6001        }
 6002
 6003        self.update_selection_mode(&modifiers, position_map, window, cx);
 6004
 6005        let mouse_position = window.mouse_position();
 6006        if !position_map.text_hitbox.is_hovered(window) {
 6007            return;
 6008        }
 6009
 6010        self.update_hovered_link(
 6011            position_map.point_for_position(mouse_position),
 6012            &position_map.snapshot,
 6013            modifiers,
 6014            window,
 6015            cx,
 6016        )
 6017    }
 6018
 6019    fn update_selection_mode(
 6020        &mut self,
 6021        modifiers: &Modifiers,
 6022        position_map: &PositionMap,
 6023        window: &mut Window,
 6024        cx: &mut Context<Self>,
 6025    ) {
 6026        if modifiers != &COLUMNAR_SELECTION_MODIFIERS || self.selections.pending.is_none() {
 6027            return;
 6028        }
 6029
 6030        let mouse_position = window.mouse_position();
 6031        let point_for_position = position_map.point_for_position(mouse_position);
 6032        let position = point_for_position.previous_valid;
 6033
 6034        self.select(
 6035            SelectPhase::BeginColumnar {
 6036                position,
 6037                reset: false,
 6038                goal_column: point_for_position.exact_unclipped.column(),
 6039            },
 6040            window,
 6041            cx,
 6042        );
 6043    }
 6044
 6045    fn update_edit_prediction_preview(
 6046        &mut self,
 6047        modifiers: &Modifiers,
 6048        window: &mut Window,
 6049        cx: &mut Context<Self>,
 6050    ) {
 6051        let accept_keybind = self.accept_edit_prediction_keybind(window, cx);
 6052        let Some(accept_keystroke) = accept_keybind.keystroke() else {
 6053            return;
 6054        };
 6055
 6056        if &accept_keystroke.modifiers == modifiers && accept_keystroke.modifiers.modified() {
 6057            if matches!(
 6058                self.edit_prediction_preview,
 6059                EditPredictionPreview::Inactive { .. }
 6060            ) {
 6061                self.edit_prediction_preview = EditPredictionPreview::Active {
 6062                    previous_scroll_position: None,
 6063                    since: Instant::now(),
 6064                };
 6065
 6066                self.update_visible_inline_completion(window, cx);
 6067                cx.notify();
 6068            }
 6069        } else if let EditPredictionPreview::Active {
 6070            previous_scroll_position,
 6071            since,
 6072        } = self.edit_prediction_preview
 6073        {
 6074            if let (Some(previous_scroll_position), Some(position_map)) =
 6075                (previous_scroll_position, self.last_position_map.as_ref())
 6076            {
 6077                self.set_scroll_position(
 6078                    previous_scroll_position
 6079                        .scroll_position(&position_map.snapshot.display_snapshot),
 6080                    window,
 6081                    cx,
 6082                );
 6083            }
 6084
 6085            self.edit_prediction_preview = EditPredictionPreview::Inactive {
 6086                released_too_fast: since.elapsed() < Duration::from_millis(200),
 6087            };
 6088            self.clear_row_highlights::<EditPredictionPreview>();
 6089            self.update_visible_inline_completion(window, cx);
 6090            cx.notify();
 6091        }
 6092    }
 6093
 6094    fn update_visible_inline_completion(
 6095        &mut self,
 6096        _window: &mut Window,
 6097        cx: &mut Context<Self>,
 6098    ) -> Option<()> {
 6099        let selection = self.selections.newest_anchor();
 6100        let cursor = selection.head();
 6101        let multibuffer = self.buffer.read(cx).snapshot(cx);
 6102        let offset_selection = selection.map(|endpoint| endpoint.to_offset(&multibuffer));
 6103        let excerpt_id = cursor.excerpt_id;
 6104
 6105        let show_in_menu = self.show_edit_predictions_in_menu();
 6106        let completions_menu_has_precedence = !show_in_menu
 6107            && (self.context_menu.borrow().is_some()
 6108                || (!self.completion_tasks.is_empty() && !self.has_active_inline_completion()));
 6109
 6110        if completions_menu_has_precedence
 6111            || !offset_selection.is_empty()
 6112            || self
 6113                .active_inline_completion
 6114                .as_ref()
 6115                .map_or(false, |completion| {
 6116                    let invalidation_range = completion.invalidation_range.to_offset(&multibuffer);
 6117                    let invalidation_range = invalidation_range.start..=invalidation_range.end;
 6118                    !invalidation_range.contains(&offset_selection.head())
 6119                })
 6120        {
 6121            self.discard_inline_completion(false, cx);
 6122            return None;
 6123        }
 6124
 6125        self.take_active_inline_completion(cx);
 6126        let Some(provider) = self.edit_prediction_provider() else {
 6127            self.edit_prediction_settings = EditPredictionSettings::Disabled;
 6128            return None;
 6129        };
 6130
 6131        let (buffer, cursor_buffer_position) =
 6132            self.buffer.read(cx).text_anchor_for_position(cursor, cx)?;
 6133
 6134        self.edit_prediction_settings =
 6135            self.edit_prediction_settings_at_position(&buffer, cursor_buffer_position, cx);
 6136
 6137        self.edit_prediction_indent_conflict = multibuffer.is_line_whitespace_upto(cursor);
 6138
 6139        if self.edit_prediction_indent_conflict {
 6140            let cursor_point = cursor.to_point(&multibuffer);
 6141
 6142            let indents = multibuffer.suggested_indents(cursor_point.row..cursor_point.row + 1, cx);
 6143
 6144            if let Some((_, indent)) = indents.iter().next() {
 6145                if indent.len == cursor_point.column {
 6146                    self.edit_prediction_indent_conflict = false;
 6147                }
 6148            }
 6149        }
 6150
 6151        let inline_completion = provider.suggest(&buffer, cursor_buffer_position, cx)?;
 6152        let edits = inline_completion
 6153            .edits
 6154            .into_iter()
 6155            .flat_map(|(range, new_text)| {
 6156                let start = multibuffer.anchor_in_excerpt(excerpt_id, range.start)?;
 6157                let end = multibuffer.anchor_in_excerpt(excerpt_id, range.end)?;
 6158                Some((start..end, new_text))
 6159            })
 6160            .collect::<Vec<_>>();
 6161        if edits.is_empty() {
 6162            return None;
 6163        }
 6164
 6165        let first_edit_start = edits.first().unwrap().0.start;
 6166        let first_edit_start_point = first_edit_start.to_point(&multibuffer);
 6167        let edit_start_row = first_edit_start_point.row.saturating_sub(2);
 6168
 6169        let last_edit_end = edits.last().unwrap().0.end;
 6170        let last_edit_end_point = last_edit_end.to_point(&multibuffer);
 6171        let edit_end_row = cmp::min(multibuffer.max_point().row, last_edit_end_point.row + 2);
 6172
 6173        let cursor_row = cursor.to_point(&multibuffer).row;
 6174
 6175        let snapshot = multibuffer.buffer_for_excerpt(excerpt_id).cloned()?;
 6176
 6177        let mut inlay_ids = Vec::new();
 6178        let invalidation_row_range;
 6179        let move_invalidation_row_range = if cursor_row < edit_start_row {
 6180            Some(cursor_row..edit_end_row)
 6181        } else if cursor_row > edit_end_row {
 6182            Some(edit_start_row..cursor_row)
 6183        } else {
 6184            None
 6185        };
 6186        let is_move =
 6187            move_invalidation_row_range.is_some() || self.inline_completions_hidden_for_vim_mode;
 6188        let completion = if is_move {
 6189            invalidation_row_range =
 6190                move_invalidation_row_range.unwrap_or(edit_start_row..edit_end_row);
 6191            let target = first_edit_start;
 6192            InlineCompletion::Move { target, snapshot }
 6193        } else {
 6194            let show_completions_in_buffer = !self.edit_prediction_visible_in_cursor_popover(true)
 6195                && !self.inline_completions_hidden_for_vim_mode;
 6196
 6197            if show_completions_in_buffer {
 6198                if edits
 6199                    .iter()
 6200                    .all(|(range, _)| range.to_offset(&multibuffer).is_empty())
 6201                {
 6202                    let mut inlays = Vec::new();
 6203                    for (range, new_text) in &edits {
 6204                        let inlay = Inlay::inline_completion(
 6205                            post_inc(&mut self.next_inlay_id),
 6206                            range.start,
 6207                            new_text.as_str(),
 6208                        );
 6209                        inlay_ids.push(inlay.id);
 6210                        inlays.push(inlay);
 6211                    }
 6212
 6213                    self.splice_inlays(&[], inlays, cx);
 6214                } else {
 6215                    let background_color = cx.theme().status().deleted_background;
 6216                    self.highlight_text::<InlineCompletionHighlight>(
 6217                        edits.iter().map(|(range, _)| range.clone()).collect(),
 6218                        HighlightStyle {
 6219                            background_color: Some(background_color),
 6220                            ..Default::default()
 6221                        },
 6222                        cx,
 6223                    );
 6224                }
 6225            }
 6226
 6227            invalidation_row_range = edit_start_row..edit_end_row;
 6228
 6229            let display_mode = if all_edits_insertions_or_deletions(&edits, &multibuffer) {
 6230                if provider.show_tab_accept_marker() {
 6231                    EditDisplayMode::TabAccept
 6232                } else {
 6233                    EditDisplayMode::Inline
 6234                }
 6235            } else {
 6236                EditDisplayMode::DiffPopover
 6237            };
 6238
 6239            InlineCompletion::Edit {
 6240                edits,
 6241                edit_preview: inline_completion.edit_preview,
 6242                display_mode,
 6243                snapshot,
 6244            }
 6245        };
 6246
 6247        let invalidation_range = multibuffer
 6248            .anchor_before(Point::new(invalidation_row_range.start, 0))
 6249            ..multibuffer.anchor_after(Point::new(
 6250                invalidation_row_range.end,
 6251                multibuffer.line_len(MultiBufferRow(invalidation_row_range.end)),
 6252            ));
 6253
 6254        self.stale_inline_completion_in_menu = None;
 6255        self.active_inline_completion = Some(InlineCompletionState {
 6256            inlay_ids,
 6257            completion,
 6258            completion_id: inline_completion.id,
 6259            invalidation_range,
 6260        });
 6261
 6262        cx.notify();
 6263
 6264        Some(())
 6265    }
 6266
 6267    pub fn edit_prediction_provider(&self) -> Option<Arc<dyn InlineCompletionProviderHandle>> {
 6268        Some(self.edit_prediction_provider.as_ref()?.provider.clone())
 6269    }
 6270
 6271    fn render_code_actions_indicator(
 6272        &self,
 6273        _style: &EditorStyle,
 6274        row: DisplayRow,
 6275        is_active: bool,
 6276        breakpoint: Option<&(Anchor, Breakpoint)>,
 6277        cx: &mut Context<Self>,
 6278    ) -> Option<IconButton> {
 6279        let color = Color::Muted;
 6280        let position = breakpoint.as_ref().map(|(anchor, _)| *anchor);
 6281        let show_tooltip = !self.context_menu_visible();
 6282
 6283        if self.available_code_actions.is_some() {
 6284            Some(
 6285                IconButton::new("code_actions_indicator", ui::IconName::Bolt)
 6286                    .shape(ui::IconButtonShape::Square)
 6287                    .icon_size(IconSize::XSmall)
 6288                    .icon_color(color)
 6289                    .toggle_state(is_active)
 6290                    .when(show_tooltip, |this| {
 6291                        this.tooltip({
 6292                            let focus_handle = self.focus_handle.clone();
 6293                            move |window, cx| {
 6294                                Tooltip::for_action_in(
 6295                                    "Toggle Code Actions",
 6296                                    &ToggleCodeActions {
 6297                                        deployed_from_indicator: None,
 6298                                    },
 6299                                    &focus_handle,
 6300                                    window,
 6301                                    cx,
 6302                                )
 6303                            }
 6304                        })
 6305                    })
 6306                    .on_click(cx.listener(move |editor, _e, window, cx| {
 6307                        window.focus(&editor.focus_handle(cx));
 6308                        editor.toggle_code_actions(
 6309                            &ToggleCodeActions {
 6310                                deployed_from_indicator: Some(row),
 6311                            },
 6312                            window,
 6313                            cx,
 6314                        );
 6315                    }))
 6316                    .on_right_click(cx.listener(move |editor, event: &ClickEvent, window, cx| {
 6317                        editor.set_breakpoint_context_menu(
 6318                            row,
 6319                            position,
 6320                            event.down.position,
 6321                            window,
 6322                            cx,
 6323                        );
 6324                    })),
 6325            )
 6326        } else {
 6327            None
 6328        }
 6329    }
 6330
 6331    fn clear_tasks(&mut self) {
 6332        self.tasks.clear()
 6333    }
 6334
 6335    fn insert_tasks(&mut self, key: (BufferId, BufferRow), value: RunnableTasks) {
 6336        if self.tasks.insert(key, value).is_some() {
 6337            // This case should hopefully be rare, but just in case...
 6338            log::error!(
 6339                "multiple different run targets found on a single line, only the last target will be rendered"
 6340            )
 6341        }
 6342    }
 6343
 6344    /// Get all display points of breakpoints that will be rendered within editor
 6345    ///
 6346    /// This function is used to handle overlaps between breakpoints and Code action/runner symbol.
 6347    /// It's also used to set the color of line numbers with breakpoints to the breakpoint color.
 6348    /// TODO debugger: Use this function to color toggle symbols that house nested breakpoints
 6349    fn active_breakpoints(
 6350        &self,
 6351        range: Range<DisplayRow>,
 6352        window: &mut Window,
 6353        cx: &mut Context<Self>,
 6354    ) -> HashMap<DisplayRow, (Anchor, Breakpoint)> {
 6355        let mut breakpoint_display_points = HashMap::default();
 6356
 6357        let Some(breakpoint_store) = self.breakpoint_store.clone() else {
 6358            return breakpoint_display_points;
 6359        };
 6360
 6361        let snapshot = self.snapshot(window, cx);
 6362
 6363        let multi_buffer_snapshot = &snapshot.display_snapshot.buffer_snapshot;
 6364        let Some(project) = self.project.as_ref() else {
 6365            return breakpoint_display_points;
 6366        };
 6367
 6368        let range = snapshot.display_point_to_point(DisplayPoint::new(range.start, 0), Bias::Left)
 6369            ..snapshot.display_point_to_point(DisplayPoint::new(range.end, 0), Bias::Right);
 6370
 6371        for (buffer_snapshot, range, excerpt_id) in
 6372            multi_buffer_snapshot.range_to_buffer_ranges(range)
 6373        {
 6374            let Some(buffer) = project.read_with(cx, |this, cx| {
 6375                this.buffer_for_id(buffer_snapshot.remote_id(), cx)
 6376            }) else {
 6377                continue;
 6378            };
 6379            let breakpoints = breakpoint_store.read(cx).breakpoints(
 6380                &buffer,
 6381                Some(
 6382                    buffer_snapshot.anchor_before(range.start)
 6383                        ..buffer_snapshot.anchor_after(range.end),
 6384                ),
 6385                buffer_snapshot,
 6386                cx,
 6387            );
 6388            for (anchor, breakpoint) in breakpoints {
 6389                let multi_buffer_anchor =
 6390                    Anchor::in_buffer(excerpt_id, buffer_snapshot.remote_id(), *anchor);
 6391                let position = multi_buffer_anchor
 6392                    .to_point(&multi_buffer_snapshot)
 6393                    .to_display_point(&snapshot);
 6394
 6395                breakpoint_display_points
 6396                    .insert(position.row(), (multi_buffer_anchor, breakpoint.clone()));
 6397            }
 6398        }
 6399
 6400        breakpoint_display_points
 6401    }
 6402
 6403    fn breakpoint_context_menu(
 6404        &self,
 6405        anchor: Anchor,
 6406        window: &mut Window,
 6407        cx: &mut Context<Self>,
 6408    ) -> Entity<ui::ContextMenu> {
 6409        let weak_editor = cx.weak_entity();
 6410        let focus_handle = self.focus_handle(cx);
 6411
 6412        let row = self
 6413            .buffer
 6414            .read(cx)
 6415            .snapshot(cx)
 6416            .summary_for_anchor::<Point>(&anchor)
 6417            .row;
 6418
 6419        let breakpoint = self
 6420            .breakpoint_at_row(row, window, cx)
 6421            .map(|(anchor, bp)| (anchor, Arc::from(bp)));
 6422
 6423        let log_breakpoint_msg = if breakpoint.as_ref().is_some_and(|bp| bp.1.message.is_some()) {
 6424            "Edit Log Breakpoint"
 6425        } else {
 6426            "Set Log Breakpoint"
 6427        };
 6428
 6429        let condition_breakpoint_msg = if breakpoint
 6430            .as_ref()
 6431            .is_some_and(|bp| bp.1.condition.is_some())
 6432        {
 6433            "Edit Condition Breakpoint"
 6434        } else {
 6435            "Set Condition Breakpoint"
 6436        };
 6437
 6438        let hit_condition_breakpoint_msg = if breakpoint
 6439            .as_ref()
 6440            .is_some_and(|bp| bp.1.hit_condition.is_some())
 6441        {
 6442            "Edit Hit Condition Breakpoint"
 6443        } else {
 6444            "Set Hit Condition Breakpoint"
 6445        };
 6446
 6447        let set_breakpoint_msg = if breakpoint.as_ref().is_some() {
 6448            "Unset Breakpoint"
 6449        } else {
 6450            "Set Breakpoint"
 6451        };
 6452
 6453        let run_to_cursor = command_palette_hooks::CommandPaletteFilter::try_global(cx)
 6454            .map_or(false, |filter| !filter.is_hidden(&DebuggerRunToCursor));
 6455
 6456        let toggle_state_msg = breakpoint.as_ref().map_or(None, |bp| match bp.1.state {
 6457            BreakpointState::Enabled => Some("Disable"),
 6458            BreakpointState::Disabled => Some("Enable"),
 6459        });
 6460
 6461        let (anchor, breakpoint) =
 6462            breakpoint.unwrap_or_else(|| (anchor, Arc::new(Breakpoint::new_standard())));
 6463
 6464        ui::ContextMenu::build(window, cx, |menu, _, _cx| {
 6465            menu.on_blur_subscription(Subscription::new(|| {}))
 6466                .context(focus_handle)
 6467                .when(run_to_cursor, |this| {
 6468                    let weak_editor = weak_editor.clone();
 6469                    this.entry("Run to cursor", None, move |window, cx| {
 6470                        weak_editor
 6471                            .update(cx, |editor, cx| {
 6472                                editor.change_selections(None, window, cx, |s| {
 6473                                    s.select_ranges([Point::new(row, 0)..Point::new(row, 0)])
 6474                                });
 6475                            })
 6476                            .ok();
 6477
 6478                        window.dispatch_action(Box::new(DebuggerRunToCursor), cx);
 6479                    })
 6480                    .separator()
 6481                })
 6482                .when_some(toggle_state_msg, |this, msg| {
 6483                    this.entry(msg, None, {
 6484                        let weak_editor = weak_editor.clone();
 6485                        let breakpoint = breakpoint.clone();
 6486                        move |_window, cx| {
 6487                            weak_editor
 6488                                .update(cx, |this, cx| {
 6489                                    this.edit_breakpoint_at_anchor(
 6490                                        anchor,
 6491                                        breakpoint.as_ref().clone(),
 6492                                        BreakpointEditAction::InvertState,
 6493                                        cx,
 6494                                    );
 6495                                })
 6496                                .log_err();
 6497                        }
 6498                    })
 6499                })
 6500                .entry(set_breakpoint_msg, None, {
 6501                    let weak_editor = weak_editor.clone();
 6502                    let breakpoint = breakpoint.clone();
 6503                    move |_window, cx| {
 6504                        weak_editor
 6505                            .update(cx, |this, cx| {
 6506                                this.edit_breakpoint_at_anchor(
 6507                                    anchor,
 6508                                    breakpoint.as_ref().clone(),
 6509                                    BreakpointEditAction::Toggle,
 6510                                    cx,
 6511                                );
 6512                            })
 6513                            .log_err();
 6514                    }
 6515                })
 6516                .entry(log_breakpoint_msg, None, {
 6517                    let breakpoint = breakpoint.clone();
 6518                    let weak_editor = weak_editor.clone();
 6519                    move |window, cx| {
 6520                        weak_editor
 6521                            .update(cx, |this, cx| {
 6522                                this.add_edit_breakpoint_block(
 6523                                    anchor,
 6524                                    breakpoint.as_ref(),
 6525                                    BreakpointPromptEditAction::Log,
 6526                                    window,
 6527                                    cx,
 6528                                );
 6529                            })
 6530                            .log_err();
 6531                    }
 6532                })
 6533                .entry(condition_breakpoint_msg, None, {
 6534                    let breakpoint = breakpoint.clone();
 6535                    let weak_editor = weak_editor.clone();
 6536                    move |window, cx| {
 6537                        weak_editor
 6538                            .update(cx, |this, cx| {
 6539                                this.add_edit_breakpoint_block(
 6540                                    anchor,
 6541                                    breakpoint.as_ref(),
 6542                                    BreakpointPromptEditAction::Condition,
 6543                                    window,
 6544                                    cx,
 6545                                );
 6546                            })
 6547                            .log_err();
 6548                    }
 6549                })
 6550                .entry(hit_condition_breakpoint_msg, None, move |window, cx| {
 6551                    weak_editor
 6552                        .update(cx, |this, cx| {
 6553                            this.add_edit_breakpoint_block(
 6554                                anchor,
 6555                                breakpoint.as_ref(),
 6556                                BreakpointPromptEditAction::HitCondition,
 6557                                window,
 6558                                cx,
 6559                            );
 6560                        })
 6561                        .log_err();
 6562                })
 6563        })
 6564    }
 6565
 6566    fn render_breakpoint(
 6567        &self,
 6568        position: Anchor,
 6569        row: DisplayRow,
 6570        breakpoint: &Breakpoint,
 6571        cx: &mut Context<Self>,
 6572    ) -> IconButton {
 6573        let (color, icon) = {
 6574            let icon = match (&breakpoint.message.is_some(), breakpoint.is_disabled()) {
 6575                (false, false) => ui::IconName::DebugBreakpoint,
 6576                (true, false) => ui::IconName::DebugLogBreakpoint,
 6577                (false, true) => ui::IconName::DebugDisabledBreakpoint,
 6578                (true, true) => ui::IconName::DebugDisabledLogBreakpoint,
 6579            };
 6580
 6581            let color = if self
 6582                .gutter_breakpoint_indicator
 6583                .0
 6584                .is_some_and(|(point, is_visible)| is_visible && point.row() == row)
 6585            {
 6586                Color::Hint
 6587            } else {
 6588                Color::Debugger
 6589            };
 6590
 6591            (color, icon)
 6592        };
 6593
 6594        let breakpoint = Arc::from(breakpoint.clone());
 6595
 6596        IconButton::new(("breakpoint_indicator", row.0 as usize), icon)
 6597            .icon_size(IconSize::XSmall)
 6598            .size(ui::ButtonSize::None)
 6599            .icon_color(color)
 6600            .style(ButtonStyle::Transparent)
 6601            .on_click(cx.listener({
 6602                let breakpoint = breakpoint.clone();
 6603
 6604                move |editor, event: &ClickEvent, window, cx| {
 6605                    let edit_action = if event.modifiers().platform || breakpoint.is_disabled() {
 6606                        BreakpointEditAction::InvertState
 6607                    } else {
 6608                        BreakpointEditAction::Toggle
 6609                    };
 6610
 6611                    window.focus(&editor.focus_handle(cx));
 6612                    editor.edit_breakpoint_at_anchor(
 6613                        position,
 6614                        breakpoint.as_ref().clone(),
 6615                        edit_action,
 6616                        cx,
 6617                    );
 6618                }
 6619            }))
 6620            .on_right_click(cx.listener(move |editor, event: &ClickEvent, window, cx| {
 6621                editor.set_breakpoint_context_menu(
 6622                    row,
 6623                    Some(position),
 6624                    event.down.position,
 6625                    window,
 6626                    cx,
 6627                );
 6628            }))
 6629    }
 6630
 6631    fn build_tasks_context(
 6632        project: &Entity<Project>,
 6633        buffer: &Entity<Buffer>,
 6634        buffer_row: u32,
 6635        tasks: &Arc<RunnableTasks>,
 6636        cx: &mut Context<Self>,
 6637    ) -> Task<Option<task::TaskContext>> {
 6638        let position = Point::new(buffer_row, tasks.column);
 6639        let range_start = buffer.read(cx).anchor_at(position, Bias::Right);
 6640        let location = Location {
 6641            buffer: buffer.clone(),
 6642            range: range_start..range_start,
 6643        };
 6644        // Fill in the environmental variables from the tree-sitter captures
 6645        let mut captured_task_variables = TaskVariables::default();
 6646        for (capture_name, value) in tasks.extra_variables.clone() {
 6647            captured_task_variables.insert(
 6648                task::VariableName::Custom(capture_name.into()),
 6649                value.clone(),
 6650            );
 6651        }
 6652        project.update(cx, |project, cx| {
 6653            project.task_store().update(cx, |task_store, cx| {
 6654                task_store.task_context_for_location(captured_task_variables, location, cx)
 6655            })
 6656        })
 6657    }
 6658
 6659    pub fn spawn_nearest_task(
 6660        &mut self,
 6661        action: &SpawnNearestTask,
 6662        window: &mut Window,
 6663        cx: &mut Context<Self>,
 6664    ) {
 6665        let Some((workspace, _)) = self.workspace.clone() else {
 6666            return;
 6667        };
 6668        let Some(project) = self.project.clone() else {
 6669            return;
 6670        };
 6671
 6672        // Try to find a closest, enclosing node using tree-sitter that has a
 6673        // task
 6674        let Some((buffer, buffer_row, tasks)) = self
 6675            .find_enclosing_node_task(cx)
 6676            // Or find the task that's closest in row-distance.
 6677            .or_else(|| self.find_closest_task(cx))
 6678        else {
 6679            return;
 6680        };
 6681
 6682        let reveal_strategy = action.reveal;
 6683        let task_context = Self::build_tasks_context(&project, &buffer, buffer_row, &tasks, cx);
 6684        cx.spawn_in(window, async move |_, cx| {
 6685            let context = task_context.await?;
 6686            let (task_source_kind, mut resolved_task) = tasks.resolve(&context).next()?;
 6687
 6688            let resolved = resolved_task.resolved.as_mut()?;
 6689            resolved.reveal = reveal_strategy;
 6690
 6691            workspace
 6692                .update(cx, |workspace, cx| {
 6693                    workspace::tasks::schedule_resolved_task(
 6694                        workspace,
 6695                        task_source_kind,
 6696                        resolved_task,
 6697                        false,
 6698                        cx,
 6699                    );
 6700                })
 6701                .ok()
 6702        })
 6703        .detach();
 6704    }
 6705
 6706    fn find_closest_task(
 6707        &mut self,
 6708        cx: &mut Context<Self>,
 6709    ) -> Option<(Entity<Buffer>, u32, Arc<RunnableTasks>)> {
 6710        let cursor_row = self.selections.newest_adjusted(cx).head().row;
 6711
 6712        let ((buffer_id, row), tasks) = self
 6713            .tasks
 6714            .iter()
 6715            .min_by_key(|((_, row), _)| cursor_row.abs_diff(*row))?;
 6716
 6717        let buffer = self.buffer.read(cx).buffer(*buffer_id)?;
 6718        let tasks = Arc::new(tasks.to_owned());
 6719        Some((buffer, *row, tasks))
 6720    }
 6721
 6722    fn find_enclosing_node_task(
 6723        &mut self,
 6724        cx: &mut Context<Self>,
 6725    ) -> Option<(Entity<Buffer>, u32, Arc<RunnableTasks>)> {
 6726        let snapshot = self.buffer.read(cx).snapshot(cx);
 6727        let offset = self.selections.newest::<usize>(cx).head();
 6728        let excerpt = snapshot.excerpt_containing(offset..offset)?;
 6729        let buffer_id = excerpt.buffer().remote_id();
 6730
 6731        let layer = excerpt.buffer().syntax_layer_at(offset)?;
 6732        let mut cursor = layer.node().walk();
 6733
 6734        while cursor.goto_first_child_for_byte(offset).is_some() {
 6735            if cursor.node().end_byte() == offset {
 6736                cursor.goto_next_sibling();
 6737            }
 6738        }
 6739
 6740        // Ascend to the smallest ancestor that contains the range and has a task.
 6741        loop {
 6742            let node = cursor.node();
 6743            let node_range = node.byte_range();
 6744            let symbol_start_row = excerpt.buffer().offset_to_point(node.start_byte()).row;
 6745
 6746            // Check if this node contains our offset
 6747            if node_range.start <= offset && node_range.end >= offset {
 6748                // If it contains offset, check for task
 6749                if let Some(tasks) = self.tasks.get(&(buffer_id, symbol_start_row)) {
 6750                    let buffer = self.buffer.read(cx).buffer(buffer_id)?;
 6751                    return Some((buffer, symbol_start_row, Arc::new(tasks.to_owned())));
 6752                }
 6753            }
 6754
 6755            if !cursor.goto_parent() {
 6756                break;
 6757            }
 6758        }
 6759        None
 6760    }
 6761
 6762    fn render_run_indicator(
 6763        &self,
 6764        _style: &EditorStyle,
 6765        is_active: bool,
 6766        row: DisplayRow,
 6767        breakpoint: Option<(Anchor, Breakpoint)>,
 6768        cx: &mut Context<Self>,
 6769    ) -> IconButton {
 6770        let color = Color::Muted;
 6771        let position = breakpoint.as_ref().map(|(anchor, _)| *anchor);
 6772
 6773        IconButton::new(("run_indicator", row.0 as usize), ui::IconName::Play)
 6774            .shape(ui::IconButtonShape::Square)
 6775            .icon_size(IconSize::XSmall)
 6776            .icon_color(color)
 6777            .toggle_state(is_active)
 6778            .on_click(cx.listener(move |editor, _e, window, cx| {
 6779                window.focus(&editor.focus_handle(cx));
 6780                editor.toggle_code_actions(
 6781                    &ToggleCodeActions {
 6782                        deployed_from_indicator: Some(row),
 6783                    },
 6784                    window,
 6785                    cx,
 6786                );
 6787            }))
 6788            .on_right_click(cx.listener(move |editor, event: &ClickEvent, window, cx| {
 6789                editor.set_breakpoint_context_menu(row, position, event.down.position, window, cx);
 6790            }))
 6791    }
 6792
 6793    pub fn context_menu_visible(&self) -> bool {
 6794        !self.edit_prediction_preview_is_active()
 6795            && self
 6796                .context_menu
 6797                .borrow()
 6798                .as_ref()
 6799                .map_or(false, |menu| menu.visible())
 6800    }
 6801
 6802    fn context_menu_origin(&self) -> Option<ContextMenuOrigin> {
 6803        self.context_menu
 6804            .borrow()
 6805            .as_ref()
 6806            .map(|menu| menu.origin())
 6807    }
 6808
 6809    pub fn set_context_menu_options(&mut self, options: ContextMenuOptions) {
 6810        self.context_menu_options = Some(options);
 6811    }
 6812
 6813    const EDIT_PREDICTION_POPOVER_PADDING_X: Pixels = Pixels(24.);
 6814    const EDIT_PREDICTION_POPOVER_PADDING_Y: Pixels = Pixels(2.);
 6815
 6816    fn render_edit_prediction_popover(
 6817        &mut self,
 6818        text_bounds: &Bounds<Pixels>,
 6819        content_origin: gpui::Point<Pixels>,
 6820        editor_snapshot: &EditorSnapshot,
 6821        visible_row_range: Range<DisplayRow>,
 6822        scroll_top: f32,
 6823        scroll_bottom: f32,
 6824        line_layouts: &[LineWithInvisibles],
 6825        line_height: Pixels,
 6826        scroll_pixel_position: gpui::Point<Pixels>,
 6827        newest_selection_head: Option<DisplayPoint>,
 6828        editor_width: Pixels,
 6829        style: &EditorStyle,
 6830        window: &mut Window,
 6831        cx: &mut App,
 6832    ) -> Option<(AnyElement, gpui::Point<Pixels>)> {
 6833        let active_inline_completion = self.active_inline_completion.as_ref()?;
 6834
 6835        if self.edit_prediction_visible_in_cursor_popover(true) {
 6836            return None;
 6837        }
 6838
 6839        match &active_inline_completion.completion {
 6840            InlineCompletion::Move { target, .. } => {
 6841                let target_display_point = target.to_display_point(editor_snapshot);
 6842
 6843                if self.edit_prediction_requires_modifier() {
 6844                    if !self.edit_prediction_preview_is_active() {
 6845                        return None;
 6846                    }
 6847
 6848                    self.render_edit_prediction_modifier_jump_popover(
 6849                        text_bounds,
 6850                        content_origin,
 6851                        visible_row_range,
 6852                        line_layouts,
 6853                        line_height,
 6854                        scroll_pixel_position,
 6855                        newest_selection_head,
 6856                        target_display_point,
 6857                        window,
 6858                        cx,
 6859                    )
 6860                } else {
 6861                    self.render_edit_prediction_eager_jump_popover(
 6862                        text_bounds,
 6863                        content_origin,
 6864                        editor_snapshot,
 6865                        visible_row_range,
 6866                        scroll_top,
 6867                        scroll_bottom,
 6868                        line_height,
 6869                        scroll_pixel_position,
 6870                        target_display_point,
 6871                        editor_width,
 6872                        window,
 6873                        cx,
 6874                    )
 6875                }
 6876            }
 6877            InlineCompletion::Edit {
 6878                display_mode: EditDisplayMode::Inline,
 6879                ..
 6880            } => None,
 6881            InlineCompletion::Edit {
 6882                display_mode: EditDisplayMode::TabAccept,
 6883                edits,
 6884                ..
 6885            } => {
 6886                let range = &edits.first()?.0;
 6887                let target_display_point = range.end.to_display_point(editor_snapshot);
 6888
 6889                self.render_edit_prediction_end_of_line_popover(
 6890                    "Accept",
 6891                    editor_snapshot,
 6892                    visible_row_range,
 6893                    target_display_point,
 6894                    line_height,
 6895                    scroll_pixel_position,
 6896                    content_origin,
 6897                    editor_width,
 6898                    window,
 6899                    cx,
 6900                )
 6901            }
 6902            InlineCompletion::Edit {
 6903                edits,
 6904                edit_preview,
 6905                display_mode: EditDisplayMode::DiffPopover,
 6906                snapshot,
 6907            } => self.render_edit_prediction_diff_popover(
 6908                text_bounds,
 6909                content_origin,
 6910                editor_snapshot,
 6911                visible_row_range,
 6912                line_layouts,
 6913                line_height,
 6914                scroll_pixel_position,
 6915                newest_selection_head,
 6916                editor_width,
 6917                style,
 6918                edits,
 6919                edit_preview,
 6920                snapshot,
 6921                window,
 6922                cx,
 6923            ),
 6924        }
 6925    }
 6926
 6927    fn render_edit_prediction_modifier_jump_popover(
 6928        &mut self,
 6929        text_bounds: &Bounds<Pixels>,
 6930        content_origin: gpui::Point<Pixels>,
 6931        visible_row_range: Range<DisplayRow>,
 6932        line_layouts: &[LineWithInvisibles],
 6933        line_height: Pixels,
 6934        scroll_pixel_position: gpui::Point<Pixels>,
 6935        newest_selection_head: Option<DisplayPoint>,
 6936        target_display_point: DisplayPoint,
 6937        window: &mut Window,
 6938        cx: &mut App,
 6939    ) -> Option<(AnyElement, gpui::Point<Pixels>)> {
 6940        let scrolled_content_origin =
 6941            content_origin - gpui::Point::new(scroll_pixel_position.x, Pixels(0.0));
 6942
 6943        const SCROLL_PADDING_Y: Pixels = px(12.);
 6944
 6945        if target_display_point.row() < visible_row_range.start {
 6946            return self.render_edit_prediction_scroll_popover(
 6947                |_| SCROLL_PADDING_Y,
 6948                IconName::ArrowUp,
 6949                visible_row_range,
 6950                line_layouts,
 6951                newest_selection_head,
 6952                scrolled_content_origin,
 6953                window,
 6954                cx,
 6955            );
 6956        } else if target_display_point.row() >= visible_row_range.end {
 6957            return self.render_edit_prediction_scroll_popover(
 6958                |size| text_bounds.size.height - size.height - SCROLL_PADDING_Y,
 6959                IconName::ArrowDown,
 6960                visible_row_range,
 6961                line_layouts,
 6962                newest_selection_head,
 6963                scrolled_content_origin,
 6964                window,
 6965                cx,
 6966            );
 6967        }
 6968
 6969        const POLE_WIDTH: Pixels = px(2.);
 6970
 6971        let line_layout =
 6972            line_layouts.get(target_display_point.row().minus(visible_row_range.start) as usize)?;
 6973        let target_column = target_display_point.column() as usize;
 6974
 6975        let target_x = line_layout.x_for_index(target_column);
 6976        let target_y =
 6977            (target_display_point.row().as_f32() * line_height) - scroll_pixel_position.y;
 6978
 6979        let flag_on_right = target_x < text_bounds.size.width / 2.;
 6980
 6981        let mut border_color = Self::edit_prediction_callout_popover_border_color(cx);
 6982        border_color.l += 0.001;
 6983
 6984        let mut element = v_flex()
 6985            .items_end()
 6986            .when(flag_on_right, |el| el.items_start())
 6987            .child(if flag_on_right {
 6988                self.render_edit_prediction_line_popover("Jump", None, window, cx)?
 6989                    .rounded_bl(px(0.))
 6990                    .rounded_tl(px(0.))
 6991                    .border_l_2()
 6992                    .border_color(border_color)
 6993            } else {
 6994                self.render_edit_prediction_line_popover("Jump", None, window, cx)?
 6995                    .rounded_br(px(0.))
 6996                    .rounded_tr(px(0.))
 6997                    .border_r_2()
 6998                    .border_color(border_color)
 6999            })
 7000            .child(div().w(POLE_WIDTH).bg(border_color).h(line_height))
 7001            .into_any();
 7002
 7003        let size = element.layout_as_root(AvailableSpace::min_size(), window, cx);
 7004
 7005        let mut origin = scrolled_content_origin + point(target_x, target_y)
 7006            - point(
 7007                if flag_on_right {
 7008                    POLE_WIDTH
 7009                } else {
 7010                    size.width - POLE_WIDTH
 7011                },
 7012                size.height - line_height,
 7013            );
 7014
 7015        origin.x = origin.x.max(content_origin.x);
 7016
 7017        element.prepaint_at(origin, window, cx);
 7018
 7019        Some((element, origin))
 7020    }
 7021
 7022    fn render_edit_prediction_scroll_popover(
 7023        &mut self,
 7024        to_y: impl Fn(Size<Pixels>) -> Pixels,
 7025        scroll_icon: IconName,
 7026        visible_row_range: Range<DisplayRow>,
 7027        line_layouts: &[LineWithInvisibles],
 7028        newest_selection_head: Option<DisplayPoint>,
 7029        scrolled_content_origin: gpui::Point<Pixels>,
 7030        window: &mut Window,
 7031        cx: &mut App,
 7032    ) -> Option<(AnyElement, gpui::Point<Pixels>)> {
 7033        let mut element = self
 7034            .render_edit_prediction_line_popover("Scroll", Some(scroll_icon), window, cx)?
 7035            .into_any();
 7036
 7037        let size = element.layout_as_root(AvailableSpace::min_size(), window, cx);
 7038
 7039        let cursor = newest_selection_head?;
 7040        let cursor_row_layout =
 7041            line_layouts.get(cursor.row().minus(visible_row_range.start) as usize)?;
 7042        let cursor_column = cursor.column() as usize;
 7043
 7044        let cursor_character_x = cursor_row_layout.x_for_index(cursor_column);
 7045
 7046        let origin = scrolled_content_origin + point(cursor_character_x, to_y(size));
 7047
 7048        element.prepaint_at(origin, window, cx);
 7049        Some((element, origin))
 7050    }
 7051
 7052    fn render_edit_prediction_eager_jump_popover(
 7053        &mut self,
 7054        text_bounds: &Bounds<Pixels>,
 7055        content_origin: gpui::Point<Pixels>,
 7056        editor_snapshot: &EditorSnapshot,
 7057        visible_row_range: Range<DisplayRow>,
 7058        scroll_top: f32,
 7059        scroll_bottom: f32,
 7060        line_height: Pixels,
 7061        scroll_pixel_position: gpui::Point<Pixels>,
 7062        target_display_point: DisplayPoint,
 7063        editor_width: Pixels,
 7064        window: &mut Window,
 7065        cx: &mut App,
 7066    ) -> Option<(AnyElement, gpui::Point<Pixels>)> {
 7067        if target_display_point.row().as_f32() < scroll_top {
 7068            let mut element = self
 7069                .render_edit_prediction_line_popover(
 7070                    "Jump to Edit",
 7071                    Some(IconName::ArrowUp),
 7072                    window,
 7073                    cx,
 7074                )?
 7075                .into_any();
 7076
 7077            let size = element.layout_as_root(AvailableSpace::min_size(), window, cx);
 7078            let offset = point(
 7079                (text_bounds.size.width - size.width) / 2.,
 7080                Self::EDIT_PREDICTION_POPOVER_PADDING_Y,
 7081            );
 7082
 7083            let origin = text_bounds.origin + offset;
 7084            element.prepaint_at(origin, window, cx);
 7085            Some((element, origin))
 7086        } else if (target_display_point.row().as_f32() + 1.) > scroll_bottom {
 7087            let mut element = self
 7088                .render_edit_prediction_line_popover(
 7089                    "Jump to Edit",
 7090                    Some(IconName::ArrowDown),
 7091                    window,
 7092                    cx,
 7093                )?
 7094                .into_any();
 7095
 7096            let size = element.layout_as_root(AvailableSpace::min_size(), window, cx);
 7097            let offset = point(
 7098                (text_bounds.size.width - size.width) / 2.,
 7099                text_bounds.size.height - size.height - Self::EDIT_PREDICTION_POPOVER_PADDING_Y,
 7100            );
 7101
 7102            let origin = text_bounds.origin + offset;
 7103            element.prepaint_at(origin, window, cx);
 7104            Some((element, origin))
 7105        } else {
 7106            self.render_edit_prediction_end_of_line_popover(
 7107                "Jump to Edit",
 7108                editor_snapshot,
 7109                visible_row_range,
 7110                target_display_point,
 7111                line_height,
 7112                scroll_pixel_position,
 7113                content_origin,
 7114                editor_width,
 7115                window,
 7116                cx,
 7117            )
 7118        }
 7119    }
 7120
 7121    fn render_edit_prediction_end_of_line_popover(
 7122        self: &mut Editor,
 7123        label: &'static str,
 7124        editor_snapshot: &EditorSnapshot,
 7125        visible_row_range: Range<DisplayRow>,
 7126        target_display_point: DisplayPoint,
 7127        line_height: Pixels,
 7128        scroll_pixel_position: gpui::Point<Pixels>,
 7129        content_origin: gpui::Point<Pixels>,
 7130        editor_width: Pixels,
 7131        window: &mut Window,
 7132        cx: &mut App,
 7133    ) -> Option<(AnyElement, gpui::Point<Pixels>)> {
 7134        let target_line_end = DisplayPoint::new(
 7135            target_display_point.row(),
 7136            editor_snapshot.line_len(target_display_point.row()),
 7137        );
 7138
 7139        let mut element = self
 7140            .render_edit_prediction_line_popover(label, None, window, cx)?
 7141            .into_any();
 7142
 7143        let size = element.layout_as_root(AvailableSpace::min_size(), window, cx);
 7144
 7145        let line_origin = self.display_to_pixel_point(target_line_end, editor_snapshot, window)?;
 7146
 7147        let start_point = content_origin - point(scroll_pixel_position.x, Pixels::ZERO);
 7148        let mut origin = start_point
 7149            + line_origin
 7150            + point(Self::EDIT_PREDICTION_POPOVER_PADDING_X, Pixels::ZERO);
 7151        origin.x = origin.x.max(content_origin.x);
 7152
 7153        let max_x = content_origin.x + editor_width - size.width;
 7154
 7155        if origin.x > max_x {
 7156            let offset = line_height + Self::EDIT_PREDICTION_POPOVER_PADDING_Y;
 7157
 7158            let icon = if visible_row_range.contains(&(target_display_point.row() + 2)) {
 7159                origin.y += offset;
 7160                IconName::ArrowUp
 7161            } else {
 7162                origin.y -= offset;
 7163                IconName::ArrowDown
 7164            };
 7165
 7166            element = self
 7167                .render_edit_prediction_line_popover(label, Some(icon), window, cx)?
 7168                .into_any();
 7169
 7170            let size = element.layout_as_root(AvailableSpace::min_size(), window, cx);
 7171
 7172            origin.x = content_origin.x + editor_width - size.width - px(2.);
 7173        }
 7174
 7175        element.prepaint_at(origin, window, cx);
 7176        Some((element, origin))
 7177    }
 7178
 7179    fn render_edit_prediction_diff_popover(
 7180        self: &Editor,
 7181        text_bounds: &Bounds<Pixels>,
 7182        content_origin: gpui::Point<Pixels>,
 7183        editor_snapshot: &EditorSnapshot,
 7184        visible_row_range: Range<DisplayRow>,
 7185        line_layouts: &[LineWithInvisibles],
 7186        line_height: Pixels,
 7187        scroll_pixel_position: gpui::Point<Pixels>,
 7188        newest_selection_head: Option<DisplayPoint>,
 7189        editor_width: Pixels,
 7190        style: &EditorStyle,
 7191        edits: &Vec<(Range<Anchor>, String)>,
 7192        edit_preview: &Option<language::EditPreview>,
 7193        snapshot: &language::BufferSnapshot,
 7194        window: &mut Window,
 7195        cx: &mut App,
 7196    ) -> Option<(AnyElement, gpui::Point<Pixels>)> {
 7197        let edit_start = edits
 7198            .first()
 7199            .unwrap()
 7200            .0
 7201            .start
 7202            .to_display_point(editor_snapshot);
 7203        let edit_end = edits
 7204            .last()
 7205            .unwrap()
 7206            .0
 7207            .end
 7208            .to_display_point(editor_snapshot);
 7209
 7210        let is_visible = visible_row_range.contains(&edit_start.row())
 7211            || visible_row_range.contains(&edit_end.row());
 7212        if !is_visible {
 7213            return None;
 7214        }
 7215
 7216        let highlighted_edits =
 7217            crate::inline_completion_edit_text(&snapshot, edits, edit_preview.as_ref()?, false, cx);
 7218
 7219        let styled_text = highlighted_edits.to_styled_text(&style.text);
 7220        let line_count = highlighted_edits.text.lines().count();
 7221
 7222        const BORDER_WIDTH: Pixels = px(1.);
 7223
 7224        let keybind = self.render_edit_prediction_accept_keybind(window, cx);
 7225        let has_keybind = keybind.is_some();
 7226
 7227        let mut element = h_flex()
 7228            .items_start()
 7229            .child(
 7230                h_flex()
 7231                    .bg(cx.theme().colors().editor_background)
 7232                    .border(BORDER_WIDTH)
 7233                    .shadow_sm()
 7234                    .border_color(cx.theme().colors().border)
 7235                    .rounded_l_lg()
 7236                    .when(line_count > 1, |el| el.rounded_br_lg())
 7237                    .pr_1()
 7238                    .child(styled_text),
 7239            )
 7240            .child(
 7241                h_flex()
 7242                    .h(line_height + BORDER_WIDTH * 2.)
 7243                    .px_1p5()
 7244                    .gap_1()
 7245                    // Workaround: For some reason, there's a gap if we don't do this
 7246                    .ml(-BORDER_WIDTH)
 7247                    .shadow(smallvec![gpui::BoxShadow {
 7248                        color: gpui::black().opacity(0.05),
 7249                        offset: point(px(1.), px(1.)),
 7250                        blur_radius: px(2.),
 7251                        spread_radius: px(0.),
 7252                    }])
 7253                    .bg(Editor::edit_prediction_line_popover_bg_color(cx))
 7254                    .border(BORDER_WIDTH)
 7255                    .border_color(cx.theme().colors().border)
 7256                    .rounded_r_lg()
 7257                    .id("edit_prediction_diff_popover_keybind")
 7258                    .when(!has_keybind, |el| {
 7259                        let status_colors = cx.theme().status();
 7260
 7261                        el.bg(status_colors.error_background)
 7262                            .border_color(status_colors.error.opacity(0.6))
 7263                            .child(Icon::new(IconName::Info).color(Color::Error))
 7264                            .cursor_default()
 7265                            .hoverable_tooltip(move |_window, cx| {
 7266                                cx.new(|_| MissingEditPredictionKeybindingTooltip).into()
 7267                            })
 7268                    })
 7269                    .children(keybind),
 7270            )
 7271            .into_any();
 7272
 7273        let longest_row =
 7274            editor_snapshot.longest_row_in_range(edit_start.row()..edit_end.row() + 1);
 7275        let longest_line_width = if visible_row_range.contains(&longest_row) {
 7276            line_layouts[(longest_row.0 - visible_row_range.start.0) as usize].width
 7277        } else {
 7278            layout_line(
 7279                longest_row,
 7280                editor_snapshot,
 7281                style,
 7282                editor_width,
 7283                |_| false,
 7284                window,
 7285                cx,
 7286            )
 7287            .width
 7288        };
 7289
 7290        let viewport_bounds =
 7291            Bounds::new(Default::default(), window.viewport_size()).extend(Edges {
 7292                right: -EditorElement::SCROLLBAR_WIDTH,
 7293                ..Default::default()
 7294            });
 7295
 7296        let x_after_longest =
 7297            text_bounds.origin.x + longest_line_width + Self::EDIT_PREDICTION_POPOVER_PADDING_X
 7298                - scroll_pixel_position.x;
 7299
 7300        let element_bounds = element.layout_as_root(AvailableSpace::min_size(), window, cx);
 7301
 7302        // Fully visible if it can be displayed within the window (allow overlapping other
 7303        // panes). However, this is only allowed if the popover starts within text_bounds.
 7304        let can_position_to_the_right = x_after_longest < text_bounds.right()
 7305            && x_after_longest + element_bounds.width < viewport_bounds.right();
 7306
 7307        let mut origin = if can_position_to_the_right {
 7308            point(
 7309                x_after_longest,
 7310                text_bounds.origin.y + edit_start.row().as_f32() * line_height
 7311                    - scroll_pixel_position.y,
 7312            )
 7313        } else {
 7314            let cursor_row = newest_selection_head.map(|head| head.row());
 7315            let above_edit = edit_start
 7316                .row()
 7317                .0
 7318                .checked_sub(line_count as u32)
 7319                .map(DisplayRow);
 7320            let below_edit = Some(edit_end.row() + 1);
 7321            let above_cursor =
 7322                cursor_row.and_then(|row| row.0.checked_sub(line_count as u32).map(DisplayRow));
 7323            let below_cursor = cursor_row.map(|cursor_row| cursor_row + 1);
 7324
 7325            // Place the edit popover adjacent to the edit if there is a location
 7326            // available that is onscreen and does not obscure the cursor. Otherwise,
 7327            // place it adjacent to the cursor.
 7328            let row_target = [above_edit, below_edit, above_cursor, below_cursor]
 7329                .into_iter()
 7330                .flatten()
 7331                .find(|&start_row| {
 7332                    let end_row = start_row + line_count as u32;
 7333                    visible_row_range.contains(&start_row)
 7334                        && visible_row_range.contains(&end_row)
 7335                        && cursor_row.map_or(true, |cursor_row| {
 7336                            !((start_row..end_row).contains(&cursor_row))
 7337                        })
 7338                })?;
 7339
 7340            content_origin
 7341                + point(
 7342                    -scroll_pixel_position.x,
 7343                    row_target.as_f32() * line_height - scroll_pixel_position.y,
 7344                )
 7345        };
 7346
 7347        origin.x -= BORDER_WIDTH;
 7348
 7349        window.defer_draw(element, origin, 1);
 7350
 7351        // Do not return an element, since it will already be drawn due to defer_draw.
 7352        None
 7353    }
 7354
 7355    fn edit_prediction_cursor_popover_height(&self) -> Pixels {
 7356        px(30.)
 7357    }
 7358
 7359    fn current_user_player_color(&self, cx: &mut App) -> PlayerColor {
 7360        if self.read_only(cx) {
 7361            cx.theme().players().read_only()
 7362        } else {
 7363            self.style.as_ref().unwrap().local_player
 7364        }
 7365    }
 7366
 7367    fn render_edit_prediction_accept_keybind(
 7368        &self,
 7369        window: &mut Window,
 7370        cx: &App,
 7371    ) -> Option<AnyElement> {
 7372        let accept_binding = self.accept_edit_prediction_keybind(window, cx);
 7373        let accept_keystroke = accept_binding.keystroke()?;
 7374
 7375        let is_platform_style_mac = PlatformStyle::platform() == PlatformStyle::Mac;
 7376
 7377        let modifiers_color = if accept_keystroke.modifiers == window.modifiers() {
 7378            Color::Accent
 7379        } else {
 7380            Color::Muted
 7381        };
 7382
 7383        h_flex()
 7384            .px_0p5()
 7385            .when(is_platform_style_mac, |parent| parent.gap_0p5())
 7386            .font(theme::ThemeSettings::get_global(cx).buffer_font.clone())
 7387            .text_size(TextSize::XSmall.rems(cx))
 7388            .child(h_flex().children(ui::render_modifiers(
 7389                &accept_keystroke.modifiers,
 7390                PlatformStyle::platform(),
 7391                Some(modifiers_color),
 7392                Some(IconSize::XSmall.rems().into()),
 7393                true,
 7394            )))
 7395            .when(is_platform_style_mac, |parent| {
 7396                parent.child(accept_keystroke.key.clone())
 7397            })
 7398            .when(!is_platform_style_mac, |parent| {
 7399                parent.child(
 7400                    Key::new(
 7401                        util::capitalize(&accept_keystroke.key),
 7402                        Some(Color::Default),
 7403                    )
 7404                    .size(Some(IconSize::XSmall.rems().into())),
 7405                )
 7406            })
 7407            .into_any()
 7408            .into()
 7409    }
 7410
 7411    fn render_edit_prediction_line_popover(
 7412        &self,
 7413        label: impl Into<SharedString>,
 7414        icon: Option<IconName>,
 7415        window: &mut Window,
 7416        cx: &App,
 7417    ) -> Option<Stateful<Div>> {
 7418        let padding_right = if icon.is_some() { px(4.) } else { px(8.) };
 7419
 7420        let keybind = self.render_edit_prediction_accept_keybind(window, cx);
 7421        let has_keybind = keybind.is_some();
 7422
 7423        let result = h_flex()
 7424            .id("ep-line-popover")
 7425            .py_0p5()
 7426            .pl_1()
 7427            .pr(padding_right)
 7428            .gap_1()
 7429            .rounded_md()
 7430            .border_1()
 7431            .bg(Self::edit_prediction_line_popover_bg_color(cx))
 7432            .border_color(Self::edit_prediction_callout_popover_border_color(cx))
 7433            .shadow_sm()
 7434            .when(!has_keybind, |el| {
 7435                let status_colors = cx.theme().status();
 7436
 7437                el.bg(status_colors.error_background)
 7438                    .border_color(status_colors.error.opacity(0.6))
 7439                    .pl_2()
 7440                    .child(Icon::new(IconName::ZedPredictError).color(Color::Error))
 7441                    .cursor_default()
 7442                    .hoverable_tooltip(move |_window, cx| {
 7443                        cx.new(|_| MissingEditPredictionKeybindingTooltip).into()
 7444                    })
 7445            })
 7446            .children(keybind)
 7447            .child(
 7448                Label::new(label)
 7449                    .size(LabelSize::Small)
 7450                    .when(!has_keybind, |el| {
 7451                        el.color(cx.theme().status().error.into()).strikethrough()
 7452                    }),
 7453            )
 7454            .when(!has_keybind, |el| {
 7455                el.child(
 7456                    h_flex().ml_1().child(
 7457                        Icon::new(IconName::Info)
 7458                            .size(IconSize::Small)
 7459                            .color(cx.theme().status().error.into()),
 7460                    ),
 7461                )
 7462            })
 7463            .when_some(icon, |element, icon| {
 7464                element.child(
 7465                    div()
 7466                        .mt(px(1.5))
 7467                        .child(Icon::new(icon).size(IconSize::Small)),
 7468                )
 7469            });
 7470
 7471        Some(result)
 7472    }
 7473
 7474    fn edit_prediction_line_popover_bg_color(cx: &App) -> Hsla {
 7475        let accent_color = cx.theme().colors().text_accent;
 7476        let editor_bg_color = cx.theme().colors().editor_background;
 7477        editor_bg_color.blend(accent_color.opacity(0.1))
 7478    }
 7479
 7480    fn edit_prediction_callout_popover_border_color(cx: &App) -> Hsla {
 7481        let accent_color = cx.theme().colors().text_accent;
 7482        let editor_bg_color = cx.theme().colors().editor_background;
 7483        editor_bg_color.blend(accent_color.opacity(0.6))
 7484    }
 7485
 7486    fn render_edit_prediction_cursor_popover(
 7487        &self,
 7488        min_width: Pixels,
 7489        max_width: Pixels,
 7490        cursor_point: Point,
 7491        style: &EditorStyle,
 7492        accept_keystroke: Option<&gpui::Keystroke>,
 7493        _window: &Window,
 7494        cx: &mut Context<Editor>,
 7495    ) -> Option<AnyElement> {
 7496        let provider = self.edit_prediction_provider.as_ref()?;
 7497
 7498        if provider.provider.needs_terms_acceptance(cx) {
 7499            return Some(
 7500                h_flex()
 7501                    .min_w(min_width)
 7502                    .flex_1()
 7503                    .px_2()
 7504                    .py_1()
 7505                    .gap_3()
 7506                    .elevation_2(cx)
 7507                    .hover(|style| style.bg(cx.theme().colors().element_hover))
 7508                    .id("accept-terms")
 7509                    .cursor_pointer()
 7510                    .on_mouse_down(MouseButton::Left, |_, window, _| window.prevent_default())
 7511                    .on_click(cx.listener(|this, _event, window, cx| {
 7512                        cx.stop_propagation();
 7513                        this.report_editor_event("Edit Prediction Provider ToS Clicked", None, cx);
 7514                        window.dispatch_action(
 7515                            zed_actions::OpenZedPredictOnboarding.boxed_clone(),
 7516                            cx,
 7517                        );
 7518                    }))
 7519                    .child(
 7520                        h_flex()
 7521                            .flex_1()
 7522                            .gap_2()
 7523                            .child(Icon::new(IconName::ZedPredict))
 7524                            .child(Label::new("Accept Terms of Service"))
 7525                            .child(div().w_full())
 7526                            .child(
 7527                                Icon::new(IconName::ArrowUpRight)
 7528                                    .color(Color::Muted)
 7529                                    .size(IconSize::Small),
 7530                            )
 7531                            .into_any_element(),
 7532                    )
 7533                    .into_any(),
 7534            );
 7535        }
 7536
 7537        let is_refreshing = provider.provider.is_refreshing(cx);
 7538
 7539        fn pending_completion_container() -> Div {
 7540            h_flex()
 7541                .h_full()
 7542                .flex_1()
 7543                .gap_2()
 7544                .child(Icon::new(IconName::ZedPredict))
 7545        }
 7546
 7547        let completion = match &self.active_inline_completion {
 7548            Some(prediction) => {
 7549                if !self.has_visible_completions_menu() {
 7550                    const RADIUS: Pixels = px(6.);
 7551                    const BORDER_WIDTH: Pixels = px(1.);
 7552
 7553                    return Some(
 7554                        h_flex()
 7555                            .elevation_2(cx)
 7556                            .border(BORDER_WIDTH)
 7557                            .border_color(cx.theme().colors().border)
 7558                            .when(accept_keystroke.is_none(), |el| {
 7559                                el.border_color(cx.theme().status().error)
 7560                            })
 7561                            .rounded(RADIUS)
 7562                            .rounded_tl(px(0.))
 7563                            .overflow_hidden()
 7564                            .child(div().px_1p5().child(match &prediction.completion {
 7565                                InlineCompletion::Move { target, snapshot } => {
 7566                                    use text::ToPoint as _;
 7567                                    if target.text_anchor.to_point(&snapshot).row > cursor_point.row
 7568                                    {
 7569                                        Icon::new(IconName::ZedPredictDown)
 7570                                    } else {
 7571                                        Icon::new(IconName::ZedPredictUp)
 7572                                    }
 7573                                }
 7574                                InlineCompletion::Edit { .. } => Icon::new(IconName::ZedPredict),
 7575                            }))
 7576                            .child(
 7577                                h_flex()
 7578                                    .gap_1()
 7579                                    .py_1()
 7580                                    .px_2()
 7581                                    .rounded_r(RADIUS - BORDER_WIDTH)
 7582                                    .border_l_1()
 7583                                    .border_color(cx.theme().colors().border)
 7584                                    .bg(Self::edit_prediction_line_popover_bg_color(cx))
 7585                                    .when(self.edit_prediction_preview.released_too_fast(), |el| {
 7586                                        el.child(
 7587                                            Label::new("Hold")
 7588                                                .size(LabelSize::Small)
 7589                                                .when(accept_keystroke.is_none(), |el| {
 7590                                                    el.strikethrough()
 7591                                                })
 7592                                                .line_height_style(LineHeightStyle::UiLabel),
 7593                                        )
 7594                                    })
 7595                                    .id("edit_prediction_cursor_popover_keybind")
 7596                                    .when(accept_keystroke.is_none(), |el| {
 7597                                        let status_colors = cx.theme().status();
 7598
 7599                                        el.bg(status_colors.error_background)
 7600                                            .border_color(status_colors.error.opacity(0.6))
 7601                                            .child(Icon::new(IconName::Info).color(Color::Error))
 7602                                            .cursor_default()
 7603                                            .hoverable_tooltip(move |_window, cx| {
 7604                                                cx.new(|_| MissingEditPredictionKeybindingTooltip)
 7605                                                    .into()
 7606                                            })
 7607                                    })
 7608                                    .when_some(
 7609                                        accept_keystroke.as_ref(),
 7610                                        |el, accept_keystroke| {
 7611                                            el.child(h_flex().children(ui::render_modifiers(
 7612                                                &accept_keystroke.modifiers,
 7613                                                PlatformStyle::platform(),
 7614                                                Some(Color::Default),
 7615                                                Some(IconSize::XSmall.rems().into()),
 7616                                                false,
 7617                                            )))
 7618                                        },
 7619                                    ),
 7620                            )
 7621                            .into_any(),
 7622                    );
 7623                }
 7624
 7625                self.render_edit_prediction_cursor_popover_preview(
 7626                    prediction,
 7627                    cursor_point,
 7628                    style,
 7629                    cx,
 7630                )?
 7631            }
 7632
 7633            None if is_refreshing => match &self.stale_inline_completion_in_menu {
 7634                Some(stale_completion) => self.render_edit_prediction_cursor_popover_preview(
 7635                    stale_completion,
 7636                    cursor_point,
 7637                    style,
 7638                    cx,
 7639                )?,
 7640
 7641                None => {
 7642                    pending_completion_container().child(Label::new("...").size(LabelSize::Small))
 7643                }
 7644            },
 7645
 7646            None => pending_completion_container().child(Label::new("No Prediction")),
 7647        };
 7648
 7649        let completion = if is_refreshing {
 7650            completion
 7651                .with_animation(
 7652                    "loading-completion",
 7653                    Animation::new(Duration::from_secs(2))
 7654                        .repeat()
 7655                        .with_easing(pulsating_between(0.4, 0.8)),
 7656                    |label, delta| label.opacity(delta),
 7657                )
 7658                .into_any_element()
 7659        } else {
 7660            completion.into_any_element()
 7661        };
 7662
 7663        let has_completion = self.active_inline_completion.is_some();
 7664
 7665        let is_platform_style_mac = PlatformStyle::platform() == PlatformStyle::Mac;
 7666        Some(
 7667            h_flex()
 7668                .min_w(min_width)
 7669                .max_w(max_width)
 7670                .flex_1()
 7671                .elevation_2(cx)
 7672                .border_color(cx.theme().colors().border)
 7673                .child(
 7674                    div()
 7675                        .flex_1()
 7676                        .py_1()
 7677                        .px_2()
 7678                        .overflow_hidden()
 7679                        .child(completion),
 7680                )
 7681                .when_some(accept_keystroke, |el, accept_keystroke| {
 7682                    if !accept_keystroke.modifiers.modified() {
 7683                        return el;
 7684                    }
 7685
 7686                    el.child(
 7687                        h_flex()
 7688                            .h_full()
 7689                            .border_l_1()
 7690                            .rounded_r_lg()
 7691                            .border_color(cx.theme().colors().border)
 7692                            .bg(Self::edit_prediction_line_popover_bg_color(cx))
 7693                            .gap_1()
 7694                            .py_1()
 7695                            .px_2()
 7696                            .child(
 7697                                h_flex()
 7698                                    .font(theme::ThemeSettings::get_global(cx).buffer_font.clone())
 7699                                    .when(is_platform_style_mac, |parent| parent.gap_1())
 7700                                    .child(h_flex().children(ui::render_modifiers(
 7701                                        &accept_keystroke.modifiers,
 7702                                        PlatformStyle::platform(),
 7703                                        Some(if !has_completion {
 7704                                            Color::Muted
 7705                                        } else {
 7706                                            Color::Default
 7707                                        }),
 7708                                        None,
 7709                                        false,
 7710                                    ))),
 7711                            )
 7712                            .child(Label::new("Preview").into_any_element())
 7713                            .opacity(if has_completion { 1.0 } else { 0.4 }),
 7714                    )
 7715                })
 7716                .into_any(),
 7717        )
 7718    }
 7719
 7720    fn render_edit_prediction_cursor_popover_preview(
 7721        &self,
 7722        completion: &InlineCompletionState,
 7723        cursor_point: Point,
 7724        style: &EditorStyle,
 7725        cx: &mut Context<Editor>,
 7726    ) -> Option<Div> {
 7727        use text::ToPoint as _;
 7728
 7729        fn render_relative_row_jump(
 7730            prefix: impl Into<String>,
 7731            current_row: u32,
 7732            target_row: u32,
 7733        ) -> Div {
 7734            let (row_diff, arrow) = if target_row < current_row {
 7735                (current_row - target_row, IconName::ArrowUp)
 7736            } else {
 7737                (target_row - current_row, IconName::ArrowDown)
 7738            };
 7739
 7740            h_flex()
 7741                .child(
 7742                    Label::new(format!("{}{}", prefix.into(), row_diff))
 7743                        .color(Color::Muted)
 7744                        .size(LabelSize::Small),
 7745                )
 7746                .child(Icon::new(arrow).color(Color::Muted).size(IconSize::Small))
 7747        }
 7748
 7749        match &completion.completion {
 7750            InlineCompletion::Move {
 7751                target, snapshot, ..
 7752            } => Some(
 7753                h_flex()
 7754                    .px_2()
 7755                    .gap_2()
 7756                    .flex_1()
 7757                    .child(
 7758                        if target.text_anchor.to_point(&snapshot).row > cursor_point.row {
 7759                            Icon::new(IconName::ZedPredictDown)
 7760                        } else {
 7761                            Icon::new(IconName::ZedPredictUp)
 7762                        },
 7763                    )
 7764                    .child(Label::new("Jump to Edit")),
 7765            ),
 7766
 7767            InlineCompletion::Edit {
 7768                edits,
 7769                edit_preview,
 7770                snapshot,
 7771                display_mode: _,
 7772            } => {
 7773                let first_edit_row = edits.first()?.0.start.text_anchor.to_point(&snapshot).row;
 7774
 7775                let (highlighted_edits, has_more_lines) = crate::inline_completion_edit_text(
 7776                    &snapshot,
 7777                    &edits,
 7778                    edit_preview.as_ref()?,
 7779                    true,
 7780                    cx,
 7781                )
 7782                .first_line_preview();
 7783
 7784                let styled_text = gpui::StyledText::new(highlighted_edits.text)
 7785                    .with_default_highlights(&style.text, highlighted_edits.highlights);
 7786
 7787                let preview = h_flex()
 7788                    .gap_1()
 7789                    .min_w_16()
 7790                    .child(styled_text)
 7791                    .when(has_more_lines, |parent| parent.child(""));
 7792
 7793                let left = if first_edit_row != cursor_point.row {
 7794                    render_relative_row_jump("", cursor_point.row, first_edit_row)
 7795                        .into_any_element()
 7796                } else {
 7797                    Icon::new(IconName::ZedPredict).into_any_element()
 7798                };
 7799
 7800                Some(
 7801                    h_flex()
 7802                        .h_full()
 7803                        .flex_1()
 7804                        .gap_2()
 7805                        .pr_1()
 7806                        .overflow_x_hidden()
 7807                        .font(theme::ThemeSettings::get_global(cx).buffer_font.clone())
 7808                        .child(left)
 7809                        .child(preview),
 7810                )
 7811            }
 7812        }
 7813    }
 7814
 7815    fn render_context_menu(
 7816        &self,
 7817        style: &EditorStyle,
 7818        max_height_in_lines: u32,
 7819        window: &mut Window,
 7820        cx: &mut Context<Editor>,
 7821    ) -> Option<AnyElement> {
 7822        let menu = self.context_menu.borrow();
 7823        let menu = menu.as_ref()?;
 7824        if !menu.visible() {
 7825            return None;
 7826        };
 7827        Some(menu.render(style, max_height_in_lines, window, cx))
 7828    }
 7829
 7830    fn render_context_menu_aside(
 7831        &mut self,
 7832        max_size: Size<Pixels>,
 7833        window: &mut Window,
 7834        cx: &mut Context<Editor>,
 7835    ) -> Option<AnyElement> {
 7836        self.context_menu.borrow_mut().as_mut().and_then(|menu| {
 7837            if menu.visible() {
 7838                menu.render_aside(self, max_size, window, cx)
 7839            } else {
 7840                None
 7841            }
 7842        })
 7843    }
 7844
 7845    fn hide_context_menu(
 7846        &mut self,
 7847        window: &mut Window,
 7848        cx: &mut Context<Self>,
 7849    ) -> Option<CodeContextMenu> {
 7850        cx.notify();
 7851        self.completion_tasks.clear();
 7852        let context_menu = self.context_menu.borrow_mut().take();
 7853        self.stale_inline_completion_in_menu.take();
 7854        self.update_visible_inline_completion(window, cx);
 7855        context_menu
 7856    }
 7857
 7858    fn show_snippet_choices(
 7859        &mut self,
 7860        choices: &Vec<String>,
 7861        selection: Range<Anchor>,
 7862        cx: &mut Context<Self>,
 7863    ) {
 7864        if selection.start.buffer_id.is_none() {
 7865            return;
 7866        }
 7867        let buffer_id = selection.start.buffer_id.unwrap();
 7868        let buffer = self.buffer().read(cx).buffer(buffer_id);
 7869        let id = post_inc(&mut self.next_completion_id);
 7870
 7871        if let Some(buffer) = buffer {
 7872            *self.context_menu.borrow_mut() = Some(CodeContextMenu::Completions(
 7873                CompletionsMenu::new_snippet_choices(id, true, choices, selection, buffer),
 7874            ));
 7875        }
 7876    }
 7877
 7878    pub fn insert_snippet(
 7879        &mut self,
 7880        insertion_ranges: &[Range<usize>],
 7881        snippet: Snippet,
 7882        window: &mut Window,
 7883        cx: &mut Context<Self>,
 7884    ) -> Result<()> {
 7885        struct Tabstop<T> {
 7886            is_end_tabstop: bool,
 7887            ranges: Vec<Range<T>>,
 7888            choices: Option<Vec<String>>,
 7889        }
 7890
 7891        let tabstops = self.buffer.update(cx, |buffer, cx| {
 7892            let snippet_text: Arc<str> = snippet.text.clone().into();
 7893            let edits = insertion_ranges
 7894                .iter()
 7895                .cloned()
 7896                .map(|range| (range, snippet_text.clone()));
 7897            buffer.edit(edits, Some(AutoindentMode::EachLine), cx);
 7898
 7899            let snapshot = &*buffer.read(cx);
 7900            let snippet = &snippet;
 7901            snippet
 7902                .tabstops
 7903                .iter()
 7904                .map(|tabstop| {
 7905                    let is_end_tabstop = tabstop.ranges.first().map_or(false, |tabstop| {
 7906                        tabstop.is_empty() && tabstop.start == snippet.text.len() as isize
 7907                    });
 7908                    let mut tabstop_ranges = tabstop
 7909                        .ranges
 7910                        .iter()
 7911                        .flat_map(|tabstop_range| {
 7912                            let mut delta = 0_isize;
 7913                            insertion_ranges.iter().map(move |insertion_range| {
 7914                                let insertion_start = insertion_range.start as isize + delta;
 7915                                delta +=
 7916                                    snippet.text.len() as isize - insertion_range.len() as isize;
 7917
 7918                                let start = ((insertion_start + tabstop_range.start) as usize)
 7919                                    .min(snapshot.len());
 7920                                let end = ((insertion_start + tabstop_range.end) as usize)
 7921                                    .min(snapshot.len());
 7922                                snapshot.anchor_before(start)..snapshot.anchor_after(end)
 7923                            })
 7924                        })
 7925                        .collect::<Vec<_>>();
 7926                    tabstop_ranges.sort_unstable_by(|a, b| a.start.cmp(&b.start, snapshot));
 7927
 7928                    Tabstop {
 7929                        is_end_tabstop,
 7930                        ranges: tabstop_ranges,
 7931                        choices: tabstop.choices.clone(),
 7932                    }
 7933                })
 7934                .collect::<Vec<_>>()
 7935        });
 7936        if let Some(tabstop) = tabstops.first() {
 7937            self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 7938                s.select_ranges(tabstop.ranges.iter().cloned());
 7939            });
 7940
 7941            if let Some(choices) = &tabstop.choices {
 7942                if let Some(selection) = tabstop.ranges.first() {
 7943                    self.show_snippet_choices(choices, selection.clone(), cx)
 7944                }
 7945            }
 7946
 7947            // If we're already at the last tabstop and it's at the end of the snippet,
 7948            // we're done, we don't need to keep the state around.
 7949            if !tabstop.is_end_tabstop {
 7950                let choices = tabstops
 7951                    .iter()
 7952                    .map(|tabstop| tabstop.choices.clone())
 7953                    .collect();
 7954
 7955                let ranges = tabstops
 7956                    .into_iter()
 7957                    .map(|tabstop| tabstop.ranges)
 7958                    .collect::<Vec<_>>();
 7959
 7960                self.snippet_stack.push(SnippetState {
 7961                    active_index: 0,
 7962                    ranges,
 7963                    choices,
 7964                });
 7965            }
 7966
 7967            // Check whether the just-entered snippet ends with an auto-closable bracket.
 7968            if self.autoclose_regions.is_empty() {
 7969                let snapshot = self.buffer.read(cx).snapshot(cx);
 7970                for selection in &mut self.selections.all::<Point>(cx) {
 7971                    let selection_head = selection.head();
 7972                    let Some(scope) = snapshot.language_scope_at(selection_head) else {
 7973                        continue;
 7974                    };
 7975
 7976                    let mut bracket_pair = None;
 7977                    let next_chars = snapshot.chars_at(selection_head).collect::<String>();
 7978                    let prev_chars = snapshot
 7979                        .reversed_chars_at(selection_head)
 7980                        .collect::<String>();
 7981                    for (pair, enabled) in scope.brackets() {
 7982                        if enabled
 7983                            && pair.close
 7984                            && prev_chars.starts_with(pair.start.as_str())
 7985                            && next_chars.starts_with(pair.end.as_str())
 7986                        {
 7987                            bracket_pair = Some(pair.clone());
 7988                            break;
 7989                        }
 7990                    }
 7991                    if let Some(pair) = bracket_pair {
 7992                        let snapshot_settings = snapshot.language_settings_at(selection_head, cx);
 7993                        let autoclose_enabled =
 7994                            self.use_autoclose && snapshot_settings.use_autoclose;
 7995                        if autoclose_enabled {
 7996                            let start = snapshot.anchor_after(selection_head);
 7997                            let end = snapshot.anchor_after(selection_head);
 7998                            self.autoclose_regions.push(AutocloseRegion {
 7999                                selection_id: selection.id,
 8000                                range: start..end,
 8001                                pair,
 8002                            });
 8003                        }
 8004                    }
 8005                }
 8006            }
 8007        }
 8008        Ok(())
 8009    }
 8010
 8011    pub fn move_to_next_snippet_tabstop(
 8012        &mut self,
 8013        window: &mut Window,
 8014        cx: &mut Context<Self>,
 8015    ) -> bool {
 8016        self.move_to_snippet_tabstop(Bias::Right, window, cx)
 8017    }
 8018
 8019    pub fn move_to_prev_snippet_tabstop(
 8020        &mut self,
 8021        window: &mut Window,
 8022        cx: &mut Context<Self>,
 8023    ) -> bool {
 8024        self.move_to_snippet_tabstop(Bias::Left, window, cx)
 8025    }
 8026
 8027    pub fn move_to_snippet_tabstop(
 8028        &mut self,
 8029        bias: Bias,
 8030        window: &mut Window,
 8031        cx: &mut Context<Self>,
 8032    ) -> bool {
 8033        if let Some(mut snippet) = self.snippet_stack.pop() {
 8034            match bias {
 8035                Bias::Left => {
 8036                    if snippet.active_index > 0 {
 8037                        snippet.active_index -= 1;
 8038                    } else {
 8039                        self.snippet_stack.push(snippet);
 8040                        return false;
 8041                    }
 8042                }
 8043                Bias::Right => {
 8044                    if snippet.active_index + 1 < snippet.ranges.len() {
 8045                        snippet.active_index += 1;
 8046                    } else {
 8047                        self.snippet_stack.push(snippet);
 8048                        return false;
 8049                    }
 8050                }
 8051            }
 8052            if let Some(current_ranges) = snippet.ranges.get(snippet.active_index) {
 8053                self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8054                    s.select_anchor_ranges(current_ranges.iter().cloned())
 8055                });
 8056
 8057                if let Some(choices) = &snippet.choices[snippet.active_index] {
 8058                    if let Some(selection) = current_ranges.first() {
 8059                        self.show_snippet_choices(&choices, selection.clone(), cx);
 8060                    }
 8061                }
 8062
 8063                // If snippet state is not at the last tabstop, push it back on the stack
 8064                if snippet.active_index + 1 < snippet.ranges.len() {
 8065                    self.snippet_stack.push(snippet);
 8066                }
 8067                return true;
 8068            }
 8069        }
 8070
 8071        false
 8072    }
 8073
 8074    pub fn clear(&mut self, window: &mut Window, cx: &mut Context<Self>) {
 8075        self.transact(window, cx, |this, window, cx| {
 8076            this.select_all(&SelectAll, window, cx);
 8077            this.insert("", window, cx);
 8078        });
 8079    }
 8080
 8081    pub fn backspace(&mut self, _: &Backspace, window: &mut Window, cx: &mut Context<Self>) {
 8082        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
 8083        self.transact(window, cx, |this, window, cx| {
 8084            this.select_autoclose_pair(window, cx);
 8085            let mut linked_ranges = HashMap::<_, Vec<_>>::default();
 8086            if !this.linked_edit_ranges.is_empty() {
 8087                let selections = this.selections.all::<MultiBufferPoint>(cx);
 8088                let snapshot = this.buffer.read(cx).snapshot(cx);
 8089
 8090                for selection in selections.iter() {
 8091                    let selection_start = snapshot.anchor_before(selection.start).text_anchor;
 8092                    let selection_end = snapshot.anchor_after(selection.end).text_anchor;
 8093                    if selection_start.buffer_id != selection_end.buffer_id {
 8094                        continue;
 8095                    }
 8096                    if let Some(ranges) =
 8097                        this.linked_editing_ranges_for(selection_start..selection_end, cx)
 8098                    {
 8099                        for (buffer, entries) in ranges {
 8100                            linked_ranges.entry(buffer).or_default().extend(entries);
 8101                        }
 8102                    }
 8103                }
 8104            }
 8105
 8106            let mut selections = this.selections.all::<MultiBufferPoint>(cx);
 8107            let display_map = this.display_map.update(cx, |map, cx| map.snapshot(cx));
 8108            for selection in &mut selections {
 8109                if selection.is_empty() {
 8110                    let old_head = selection.head();
 8111                    let mut new_head =
 8112                        movement::left(&display_map, old_head.to_display_point(&display_map))
 8113                            .to_point(&display_map);
 8114                    if let Some((buffer, line_buffer_range)) = display_map
 8115                        .buffer_snapshot
 8116                        .buffer_line_for_row(MultiBufferRow(old_head.row))
 8117                    {
 8118                        let indent_size = buffer.indent_size_for_line(line_buffer_range.start.row);
 8119                        let indent_len = match indent_size.kind {
 8120                            IndentKind::Space => {
 8121                                buffer.settings_at(line_buffer_range.start, cx).tab_size
 8122                            }
 8123                            IndentKind::Tab => NonZeroU32::new(1).unwrap(),
 8124                        };
 8125                        if old_head.column <= indent_size.len && old_head.column > 0 {
 8126                            let indent_len = indent_len.get();
 8127                            new_head = cmp::min(
 8128                                new_head,
 8129                                MultiBufferPoint::new(
 8130                                    old_head.row,
 8131                                    ((old_head.column - 1) / indent_len) * indent_len,
 8132                                ),
 8133                            );
 8134                        }
 8135                    }
 8136
 8137                    selection.set_head(new_head, SelectionGoal::None);
 8138                }
 8139            }
 8140
 8141            this.signature_help_state.set_backspace_pressed(true);
 8142            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8143                s.select(selections)
 8144            });
 8145            this.insert("", window, cx);
 8146            let empty_str: Arc<str> = Arc::from("");
 8147            for (buffer, edits) in linked_ranges {
 8148                let snapshot = buffer.read(cx).snapshot();
 8149                use text::ToPoint as TP;
 8150
 8151                let edits = edits
 8152                    .into_iter()
 8153                    .map(|range| {
 8154                        let end_point = TP::to_point(&range.end, &snapshot);
 8155                        let mut start_point = TP::to_point(&range.start, &snapshot);
 8156
 8157                        if end_point == start_point {
 8158                            let offset = text::ToOffset::to_offset(&range.start, &snapshot)
 8159                                .saturating_sub(1);
 8160                            start_point =
 8161                                snapshot.clip_point(TP::to_point(&offset, &snapshot), Bias::Left);
 8162                        };
 8163
 8164                        (start_point..end_point, empty_str.clone())
 8165                    })
 8166                    .sorted_by_key(|(range, _)| range.start)
 8167                    .collect::<Vec<_>>();
 8168                buffer.update(cx, |this, cx| {
 8169                    this.edit(edits, None, cx);
 8170                })
 8171            }
 8172            this.refresh_inline_completion(true, false, window, cx);
 8173            linked_editing_ranges::refresh_linked_ranges(this, window, cx);
 8174        });
 8175    }
 8176
 8177    pub fn delete(&mut self, _: &Delete, window: &mut Window, cx: &mut Context<Self>) {
 8178        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
 8179        self.transact(window, cx, |this, window, cx| {
 8180            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8181                s.move_with(|map, selection| {
 8182                    if selection.is_empty() {
 8183                        let cursor = movement::right(map, selection.head());
 8184                        selection.end = cursor;
 8185                        selection.reversed = true;
 8186                        selection.goal = SelectionGoal::None;
 8187                    }
 8188                })
 8189            });
 8190            this.insert("", window, cx);
 8191            this.refresh_inline_completion(true, false, window, cx);
 8192        });
 8193    }
 8194
 8195    pub fn backtab(&mut self, _: &Backtab, window: &mut Window, cx: &mut Context<Self>) {
 8196        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
 8197        if self.move_to_prev_snippet_tabstop(window, cx) {
 8198            return;
 8199        }
 8200        self.outdent(&Outdent, window, cx);
 8201    }
 8202
 8203    pub fn tab(&mut self, _: &Tab, window: &mut Window, cx: &mut Context<Self>) {
 8204        if self.move_to_next_snippet_tabstop(window, cx) {
 8205            self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
 8206            return;
 8207        }
 8208        if self.read_only(cx) {
 8209            return;
 8210        }
 8211        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
 8212        let mut selections = self.selections.all_adjusted(cx);
 8213        let buffer = self.buffer.read(cx);
 8214        let snapshot = buffer.snapshot(cx);
 8215        let rows_iter = selections.iter().map(|s| s.head().row);
 8216        let suggested_indents = snapshot.suggested_indents(rows_iter, cx);
 8217
 8218        let mut edits = Vec::new();
 8219        let mut prev_edited_row = 0;
 8220        let mut row_delta = 0;
 8221        for selection in &mut selections {
 8222            if selection.start.row != prev_edited_row {
 8223                row_delta = 0;
 8224            }
 8225            prev_edited_row = selection.end.row;
 8226
 8227            // If the selection is non-empty, then increase the indentation of the selected lines.
 8228            if !selection.is_empty() {
 8229                row_delta =
 8230                    Self::indent_selection(buffer, &snapshot, selection, &mut edits, row_delta, cx);
 8231                continue;
 8232            }
 8233
 8234            // If the selection is empty and the cursor is in the leading whitespace before the
 8235            // suggested indentation, then auto-indent the line.
 8236            let cursor = selection.head();
 8237            let current_indent = snapshot.indent_size_for_line(MultiBufferRow(cursor.row));
 8238            if let Some(suggested_indent) =
 8239                suggested_indents.get(&MultiBufferRow(cursor.row)).copied()
 8240            {
 8241                if cursor.column < suggested_indent.len
 8242                    && cursor.column <= current_indent.len
 8243                    && current_indent.len <= suggested_indent.len
 8244                {
 8245                    selection.start = Point::new(cursor.row, suggested_indent.len);
 8246                    selection.end = selection.start;
 8247                    if row_delta == 0 {
 8248                        edits.extend(Buffer::edit_for_indent_size_adjustment(
 8249                            cursor.row,
 8250                            current_indent,
 8251                            suggested_indent,
 8252                        ));
 8253                        row_delta = suggested_indent.len - current_indent.len;
 8254                    }
 8255                    continue;
 8256                }
 8257            }
 8258
 8259            // Otherwise, insert a hard or soft tab.
 8260            let settings = buffer.language_settings_at(cursor, cx);
 8261            let tab_size = if settings.hard_tabs {
 8262                IndentSize::tab()
 8263            } else {
 8264                let tab_size = settings.tab_size.get();
 8265                let indent_remainder = snapshot
 8266                    .text_for_range(Point::new(cursor.row, 0)..cursor)
 8267                    .flat_map(str::chars)
 8268                    .fold(row_delta % tab_size, |counter: u32, c| {
 8269                        if c == '\t' {
 8270                            0
 8271                        } else {
 8272                            (counter + 1) % tab_size
 8273                        }
 8274                    });
 8275
 8276                let chars_to_next_tab_stop = tab_size - indent_remainder;
 8277                IndentSize::spaces(chars_to_next_tab_stop)
 8278            };
 8279            selection.start = Point::new(cursor.row, cursor.column + row_delta + tab_size.len);
 8280            selection.end = selection.start;
 8281            edits.push((cursor..cursor, tab_size.chars().collect::<String>()));
 8282            row_delta += tab_size.len;
 8283        }
 8284
 8285        self.transact(window, cx, |this, window, cx| {
 8286            this.buffer.update(cx, |b, cx| b.edit(edits, None, cx));
 8287            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8288                s.select(selections)
 8289            });
 8290            this.refresh_inline_completion(true, false, window, cx);
 8291        });
 8292    }
 8293
 8294    pub fn indent(&mut self, _: &Indent, window: &mut Window, cx: &mut Context<Self>) {
 8295        if self.read_only(cx) {
 8296            return;
 8297        }
 8298        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
 8299        let mut selections = self.selections.all::<Point>(cx);
 8300        let mut prev_edited_row = 0;
 8301        let mut row_delta = 0;
 8302        let mut edits = Vec::new();
 8303        let buffer = self.buffer.read(cx);
 8304        let snapshot = buffer.snapshot(cx);
 8305        for selection in &mut selections {
 8306            if selection.start.row != prev_edited_row {
 8307                row_delta = 0;
 8308            }
 8309            prev_edited_row = selection.end.row;
 8310
 8311            row_delta =
 8312                Self::indent_selection(buffer, &snapshot, selection, &mut edits, row_delta, cx);
 8313        }
 8314
 8315        self.transact(window, cx, |this, window, cx| {
 8316            this.buffer.update(cx, |b, cx| b.edit(edits, None, cx));
 8317            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8318                s.select(selections)
 8319            });
 8320        });
 8321    }
 8322
 8323    fn indent_selection(
 8324        buffer: &MultiBuffer,
 8325        snapshot: &MultiBufferSnapshot,
 8326        selection: &mut Selection<Point>,
 8327        edits: &mut Vec<(Range<Point>, String)>,
 8328        delta_for_start_row: u32,
 8329        cx: &App,
 8330    ) -> u32 {
 8331        let settings = buffer.language_settings_at(selection.start, cx);
 8332        let tab_size = settings.tab_size.get();
 8333        let indent_kind = if settings.hard_tabs {
 8334            IndentKind::Tab
 8335        } else {
 8336            IndentKind::Space
 8337        };
 8338        let mut start_row = selection.start.row;
 8339        let mut end_row = selection.end.row + 1;
 8340
 8341        // If a selection ends at the beginning of a line, don't indent
 8342        // that last line.
 8343        if selection.end.column == 0 && selection.end.row > selection.start.row {
 8344            end_row -= 1;
 8345        }
 8346
 8347        // Avoid re-indenting a row that has already been indented by a
 8348        // previous selection, but still update this selection's column
 8349        // to reflect that indentation.
 8350        if delta_for_start_row > 0 {
 8351            start_row += 1;
 8352            selection.start.column += delta_for_start_row;
 8353            if selection.end.row == selection.start.row {
 8354                selection.end.column += delta_for_start_row;
 8355            }
 8356        }
 8357
 8358        let mut delta_for_end_row = 0;
 8359        let has_multiple_rows = start_row + 1 != end_row;
 8360        for row in start_row..end_row {
 8361            let current_indent = snapshot.indent_size_for_line(MultiBufferRow(row));
 8362            let indent_delta = match (current_indent.kind, indent_kind) {
 8363                (IndentKind::Space, IndentKind::Space) => {
 8364                    let columns_to_next_tab_stop = tab_size - (current_indent.len % tab_size);
 8365                    IndentSize::spaces(columns_to_next_tab_stop)
 8366                }
 8367                (IndentKind::Tab, IndentKind::Space) => IndentSize::spaces(tab_size),
 8368                (_, IndentKind::Tab) => IndentSize::tab(),
 8369            };
 8370
 8371            let start = if has_multiple_rows || current_indent.len < selection.start.column {
 8372                0
 8373            } else {
 8374                selection.start.column
 8375            };
 8376            let row_start = Point::new(row, start);
 8377            edits.push((
 8378                row_start..row_start,
 8379                indent_delta.chars().collect::<String>(),
 8380            ));
 8381
 8382            // Update this selection's endpoints to reflect the indentation.
 8383            if row == selection.start.row {
 8384                selection.start.column += indent_delta.len;
 8385            }
 8386            if row == selection.end.row {
 8387                selection.end.column += indent_delta.len;
 8388                delta_for_end_row = indent_delta.len;
 8389            }
 8390        }
 8391
 8392        if selection.start.row == selection.end.row {
 8393            delta_for_start_row + delta_for_end_row
 8394        } else {
 8395            delta_for_end_row
 8396        }
 8397    }
 8398
 8399    pub fn outdent(&mut self, _: &Outdent, window: &mut Window, cx: &mut Context<Self>) {
 8400        if self.read_only(cx) {
 8401            return;
 8402        }
 8403        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
 8404        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 8405        let selections = self.selections.all::<Point>(cx);
 8406        let mut deletion_ranges = Vec::new();
 8407        let mut last_outdent = None;
 8408        {
 8409            let buffer = self.buffer.read(cx);
 8410            let snapshot = buffer.snapshot(cx);
 8411            for selection in &selections {
 8412                let settings = buffer.language_settings_at(selection.start, cx);
 8413                let tab_size = settings.tab_size.get();
 8414                let mut rows = selection.spanned_rows(false, &display_map);
 8415
 8416                // Avoid re-outdenting a row that has already been outdented by a
 8417                // previous selection.
 8418                if let Some(last_row) = last_outdent {
 8419                    if last_row == rows.start {
 8420                        rows.start = rows.start.next_row();
 8421                    }
 8422                }
 8423                let has_multiple_rows = rows.len() > 1;
 8424                for row in rows.iter_rows() {
 8425                    let indent_size = snapshot.indent_size_for_line(row);
 8426                    if indent_size.len > 0 {
 8427                        let deletion_len = match indent_size.kind {
 8428                            IndentKind::Space => {
 8429                                let columns_to_prev_tab_stop = indent_size.len % tab_size;
 8430                                if columns_to_prev_tab_stop == 0 {
 8431                                    tab_size
 8432                                } else {
 8433                                    columns_to_prev_tab_stop
 8434                                }
 8435                            }
 8436                            IndentKind::Tab => 1,
 8437                        };
 8438                        let start = if has_multiple_rows
 8439                            || deletion_len > selection.start.column
 8440                            || indent_size.len < selection.start.column
 8441                        {
 8442                            0
 8443                        } else {
 8444                            selection.start.column - deletion_len
 8445                        };
 8446                        deletion_ranges.push(
 8447                            Point::new(row.0, start)..Point::new(row.0, start + deletion_len),
 8448                        );
 8449                        last_outdent = Some(row);
 8450                    }
 8451                }
 8452            }
 8453        }
 8454
 8455        self.transact(window, cx, |this, window, cx| {
 8456            this.buffer.update(cx, |buffer, cx| {
 8457                let empty_str: Arc<str> = Arc::default();
 8458                buffer.edit(
 8459                    deletion_ranges
 8460                        .into_iter()
 8461                        .map(|range| (range, empty_str.clone())),
 8462                    None,
 8463                    cx,
 8464                );
 8465            });
 8466            let selections = this.selections.all::<usize>(cx);
 8467            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8468                s.select(selections)
 8469            });
 8470        });
 8471    }
 8472
 8473    pub fn autoindent(&mut self, _: &AutoIndent, window: &mut Window, cx: &mut Context<Self>) {
 8474        if self.read_only(cx) {
 8475            return;
 8476        }
 8477        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
 8478        let selections = self
 8479            .selections
 8480            .all::<usize>(cx)
 8481            .into_iter()
 8482            .map(|s| s.range());
 8483
 8484        self.transact(window, cx, |this, window, cx| {
 8485            this.buffer.update(cx, |buffer, cx| {
 8486                buffer.autoindent_ranges(selections, cx);
 8487            });
 8488            let selections = this.selections.all::<usize>(cx);
 8489            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8490                s.select(selections)
 8491            });
 8492        });
 8493    }
 8494
 8495    pub fn delete_line(&mut self, _: &DeleteLine, window: &mut Window, cx: &mut Context<Self>) {
 8496        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
 8497        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 8498        let selections = self.selections.all::<Point>(cx);
 8499
 8500        let mut new_cursors = Vec::new();
 8501        let mut edit_ranges = Vec::new();
 8502        let mut selections = selections.iter().peekable();
 8503        while let Some(selection) = selections.next() {
 8504            let mut rows = selection.spanned_rows(false, &display_map);
 8505            let goal_display_column = selection.head().to_display_point(&display_map).column();
 8506
 8507            // Accumulate contiguous regions of rows that we want to delete.
 8508            while let Some(next_selection) = selections.peek() {
 8509                let next_rows = next_selection.spanned_rows(false, &display_map);
 8510                if next_rows.start <= rows.end {
 8511                    rows.end = next_rows.end;
 8512                    selections.next().unwrap();
 8513                } else {
 8514                    break;
 8515                }
 8516            }
 8517
 8518            let buffer = &display_map.buffer_snapshot;
 8519            let mut edit_start = Point::new(rows.start.0, 0).to_offset(buffer);
 8520            let edit_end;
 8521            let cursor_buffer_row;
 8522            if buffer.max_point().row >= rows.end.0 {
 8523                // If there's a line after the range, delete the \n from the end of the row range
 8524                // and position the cursor on the next line.
 8525                edit_end = Point::new(rows.end.0, 0).to_offset(buffer);
 8526                cursor_buffer_row = rows.end;
 8527            } else {
 8528                // If there isn't a line after the range, delete the \n from the line before the
 8529                // start of the row range and position the cursor there.
 8530                edit_start = edit_start.saturating_sub(1);
 8531                edit_end = buffer.len();
 8532                cursor_buffer_row = rows.start.previous_row();
 8533            }
 8534
 8535            let mut cursor = Point::new(cursor_buffer_row.0, 0).to_display_point(&display_map);
 8536            *cursor.column_mut() =
 8537                cmp::min(goal_display_column, display_map.line_len(cursor.row()));
 8538
 8539            new_cursors.push((
 8540                selection.id,
 8541                buffer.anchor_after(cursor.to_point(&display_map)),
 8542            ));
 8543            edit_ranges.push(edit_start..edit_end);
 8544        }
 8545
 8546        self.transact(window, cx, |this, window, cx| {
 8547            let buffer = this.buffer.update(cx, |buffer, cx| {
 8548                let empty_str: Arc<str> = Arc::default();
 8549                buffer.edit(
 8550                    edit_ranges
 8551                        .into_iter()
 8552                        .map(|range| (range, empty_str.clone())),
 8553                    None,
 8554                    cx,
 8555                );
 8556                buffer.snapshot(cx)
 8557            });
 8558            let new_selections = new_cursors
 8559                .into_iter()
 8560                .map(|(id, cursor)| {
 8561                    let cursor = cursor.to_point(&buffer);
 8562                    Selection {
 8563                        id,
 8564                        start: cursor,
 8565                        end: cursor,
 8566                        reversed: false,
 8567                        goal: SelectionGoal::None,
 8568                    }
 8569                })
 8570                .collect();
 8571
 8572            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8573                s.select(new_selections);
 8574            });
 8575        });
 8576    }
 8577
 8578    pub fn join_lines_impl(
 8579        &mut self,
 8580        insert_whitespace: bool,
 8581        window: &mut Window,
 8582        cx: &mut Context<Self>,
 8583    ) {
 8584        if self.read_only(cx) {
 8585            return;
 8586        }
 8587        let mut row_ranges = Vec::<Range<MultiBufferRow>>::new();
 8588        for selection in self.selections.all::<Point>(cx) {
 8589            let start = MultiBufferRow(selection.start.row);
 8590            // Treat single line selections as if they include the next line. Otherwise this action
 8591            // would do nothing for single line selections individual cursors.
 8592            let end = if selection.start.row == selection.end.row {
 8593                MultiBufferRow(selection.start.row + 1)
 8594            } else {
 8595                MultiBufferRow(selection.end.row)
 8596            };
 8597
 8598            if let Some(last_row_range) = row_ranges.last_mut() {
 8599                if start <= last_row_range.end {
 8600                    last_row_range.end = end;
 8601                    continue;
 8602                }
 8603            }
 8604            row_ranges.push(start..end);
 8605        }
 8606
 8607        let snapshot = self.buffer.read(cx).snapshot(cx);
 8608        let mut cursor_positions = Vec::new();
 8609        for row_range in &row_ranges {
 8610            let anchor = snapshot.anchor_before(Point::new(
 8611                row_range.end.previous_row().0,
 8612                snapshot.line_len(row_range.end.previous_row()),
 8613            ));
 8614            cursor_positions.push(anchor..anchor);
 8615        }
 8616
 8617        self.transact(window, cx, |this, window, cx| {
 8618            for row_range in row_ranges.into_iter().rev() {
 8619                for row in row_range.iter_rows().rev() {
 8620                    let end_of_line = Point::new(row.0, snapshot.line_len(row));
 8621                    let next_line_row = row.next_row();
 8622                    let indent = snapshot.indent_size_for_line(next_line_row);
 8623                    let start_of_next_line = Point::new(next_line_row.0, indent.len);
 8624
 8625                    let replace =
 8626                        if snapshot.line_len(next_line_row) > indent.len && insert_whitespace {
 8627                            " "
 8628                        } else {
 8629                            ""
 8630                        };
 8631
 8632                    this.buffer.update(cx, |buffer, cx| {
 8633                        buffer.edit([(end_of_line..start_of_next_line, replace)], None, cx)
 8634                    });
 8635                }
 8636            }
 8637
 8638            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8639                s.select_anchor_ranges(cursor_positions)
 8640            });
 8641        });
 8642    }
 8643
 8644    pub fn join_lines(&mut self, _: &JoinLines, window: &mut Window, cx: &mut Context<Self>) {
 8645        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
 8646        self.join_lines_impl(true, window, cx);
 8647    }
 8648
 8649    pub fn sort_lines_case_sensitive(
 8650        &mut self,
 8651        _: &SortLinesCaseSensitive,
 8652        window: &mut Window,
 8653        cx: &mut Context<Self>,
 8654    ) {
 8655        self.manipulate_lines(window, cx, |lines| lines.sort())
 8656    }
 8657
 8658    pub fn sort_lines_case_insensitive(
 8659        &mut self,
 8660        _: &SortLinesCaseInsensitive,
 8661        window: &mut Window,
 8662        cx: &mut Context<Self>,
 8663    ) {
 8664        self.manipulate_lines(window, cx, |lines| {
 8665            lines.sort_by_key(|line| line.to_lowercase())
 8666        })
 8667    }
 8668
 8669    pub fn unique_lines_case_insensitive(
 8670        &mut self,
 8671        _: &UniqueLinesCaseInsensitive,
 8672        window: &mut Window,
 8673        cx: &mut Context<Self>,
 8674    ) {
 8675        self.manipulate_lines(window, cx, |lines| {
 8676            let mut seen = HashSet::default();
 8677            lines.retain(|line| seen.insert(line.to_lowercase()));
 8678        })
 8679    }
 8680
 8681    pub fn unique_lines_case_sensitive(
 8682        &mut self,
 8683        _: &UniqueLinesCaseSensitive,
 8684        window: &mut Window,
 8685        cx: &mut Context<Self>,
 8686    ) {
 8687        self.manipulate_lines(window, cx, |lines| {
 8688            let mut seen = HashSet::default();
 8689            lines.retain(|line| seen.insert(*line));
 8690        })
 8691    }
 8692
 8693    pub fn reload_file(&mut self, _: &ReloadFile, window: &mut Window, cx: &mut Context<Self>) {
 8694        let Some(project) = self.project.clone() else {
 8695            return;
 8696        };
 8697        self.reload(project, window, cx)
 8698            .detach_and_notify_err(window, cx);
 8699    }
 8700
 8701    pub fn restore_file(
 8702        &mut self,
 8703        _: &::git::RestoreFile,
 8704        window: &mut Window,
 8705        cx: &mut Context<Self>,
 8706    ) {
 8707        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
 8708        let mut buffer_ids = HashSet::default();
 8709        let snapshot = self.buffer().read(cx).snapshot(cx);
 8710        for selection in self.selections.all::<usize>(cx) {
 8711            buffer_ids.extend(snapshot.buffer_ids_for_range(selection.range()))
 8712        }
 8713
 8714        let buffer = self.buffer().read(cx);
 8715        let ranges = buffer_ids
 8716            .into_iter()
 8717            .flat_map(|buffer_id| buffer.excerpt_ranges_for_buffer(buffer_id, cx))
 8718            .collect::<Vec<_>>();
 8719
 8720        self.restore_hunks_in_ranges(ranges, window, cx);
 8721    }
 8722
 8723    pub fn git_restore(&mut self, _: &Restore, window: &mut Window, cx: &mut Context<Self>) {
 8724        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
 8725        let selections = self
 8726            .selections
 8727            .all(cx)
 8728            .into_iter()
 8729            .map(|s| s.range())
 8730            .collect();
 8731        self.restore_hunks_in_ranges(selections, window, cx);
 8732    }
 8733
 8734    pub fn restore_hunks_in_ranges(
 8735        &mut self,
 8736        ranges: Vec<Range<Point>>,
 8737        window: &mut Window,
 8738        cx: &mut Context<Editor>,
 8739    ) {
 8740        let mut revert_changes = HashMap::default();
 8741        let chunk_by = self
 8742            .snapshot(window, cx)
 8743            .hunks_for_ranges(ranges)
 8744            .into_iter()
 8745            .chunk_by(|hunk| hunk.buffer_id);
 8746        for (buffer_id, hunks) in &chunk_by {
 8747            let hunks = hunks.collect::<Vec<_>>();
 8748            for hunk in &hunks {
 8749                self.prepare_restore_change(&mut revert_changes, hunk, cx);
 8750            }
 8751            self.do_stage_or_unstage(false, buffer_id, hunks.into_iter(), cx);
 8752        }
 8753        drop(chunk_by);
 8754        if !revert_changes.is_empty() {
 8755            self.transact(window, cx, |editor, window, cx| {
 8756                editor.restore(revert_changes, window, cx);
 8757            });
 8758        }
 8759    }
 8760
 8761    pub fn open_active_item_in_terminal(
 8762        &mut self,
 8763        _: &OpenInTerminal,
 8764        window: &mut Window,
 8765        cx: &mut Context<Self>,
 8766    ) {
 8767        if let Some(working_directory) = self.active_excerpt(cx).and_then(|(_, buffer, _)| {
 8768            let project_path = buffer.read(cx).project_path(cx)?;
 8769            let project = self.project.as_ref()?.read(cx);
 8770            let entry = project.entry_for_path(&project_path, cx)?;
 8771            let parent = match &entry.canonical_path {
 8772                Some(canonical_path) => canonical_path.to_path_buf(),
 8773                None => project.absolute_path(&project_path, cx)?,
 8774            }
 8775            .parent()?
 8776            .to_path_buf();
 8777            Some(parent)
 8778        }) {
 8779            window.dispatch_action(OpenTerminal { working_directory }.boxed_clone(), cx);
 8780        }
 8781    }
 8782
 8783    fn set_breakpoint_context_menu(
 8784        &mut self,
 8785        display_row: DisplayRow,
 8786        position: Option<Anchor>,
 8787        clicked_point: gpui::Point<Pixels>,
 8788        window: &mut Window,
 8789        cx: &mut Context<Self>,
 8790    ) {
 8791        if !cx.has_flag::<Debugger>() {
 8792            return;
 8793        }
 8794        let source = self
 8795            .buffer
 8796            .read(cx)
 8797            .snapshot(cx)
 8798            .anchor_before(Point::new(display_row.0, 0u32));
 8799
 8800        let context_menu = self.breakpoint_context_menu(position.unwrap_or(source), window, cx);
 8801
 8802        self.mouse_context_menu = MouseContextMenu::pinned_to_editor(
 8803            self,
 8804            source,
 8805            clicked_point,
 8806            context_menu,
 8807            window,
 8808            cx,
 8809        );
 8810    }
 8811
 8812    fn add_edit_breakpoint_block(
 8813        &mut self,
 8814        anchor: Anchor,
 8815        breakpoint: &Breakpoint,
 8816        edit_action: BreakpointPromptEditAction,
 8817        window: &mut Window,
 8818        cx: &mut Context<Self>,
 8819    ) {
 8820        let weak_editor = cx.weak_entity();
 8821        let bp_prompt = cx.new(|cx| {
 8822            BreakpointPromptEditor::new(
 8823                weak_editor,
 8824                anchor,
 8825                breakpoint.clone(),
 8826                edit_action,
 8827                window,
 8828                cx,
 8829            )
 8830        });
 8831
 8832        let height = bp_prompt.update(cx, |this, cx| {
 8833            this.prompt
 8834                .update(cx, |prompt, cx| prompt.max_point(cx).row().0 + 1 + 2)
 8835        });
 8836        let cloned_prompt = bp_prompt.clone();
 8837        let blocks = vec![BlockProperties {
 8838            style: BlockStyle::Sticky,
 8839            placement: BlockPlacement::Above(anchor),
 8840            height: Some(height),
 8841            render: Arc::new(move |cx| {
 8842                *cloned_prompt.read(cx).gutter_dimensions.lock() = *cx.gutter_dimensions;
 8843                cloned_prompt.clone().into_any_element()
 8844            }),
 8845            priority: 0,
 8846        }];
 8847
 8848        let focus_handle = bp_prompt.focus_handle(cx);
 8849        window.focus(&focus_handle);
 8850
 8851        let block_ids = self.insert_blocks(blocks, None, cx);
 8852        bp_prompt.update(cx, |prompt, _| {
 8853            prompt.add_block_ids(block_ids);
 8854        });
 8855    }
 8856
 8857    pub(crate) fn breakpoint_at_row(
 8858        &self,
 8859        row: u32,
 8860        window: &mut Window,
 8861        cx: &mut Context<Self>,
 8862    ) -> Option<(Anchor, Breakpoint)> {
 8863        let snapshot = self.snapshot(window, cx);
 8864        let breakpoint_position = snapshot.buffer_snapshot.anchor_before(Point::new(row, 0));
 8865
 8866        self.breakpoint_at_anchor(breakpoint_position, &snapshot, cx)
 8867    }
 8868
 8869    pub(crate) fn breakpoint_at_anchor(
 8870        &self,
 8871        breakpoint_position: Anchor,
 8872        snapshot: &EditorSnapshot,
 8873        cx: &mut Context<Self>,
 8874    ) -> Option<(Anchor, Breakpoint)> {
 8875        let project = self.project.clone()?;
 8876
 8877        let buffer_id = breakpoint_position.buffer_id.or_else(|| {
 8878            snapshot
 8879                .buffer_snapshot
 8880                .buffer_id_for_excerpt(breakpoint_position.excerpt_id)
 8881        })?;
 8882
 8883        let enclosing_excerpt = breakpoint_position.excerpt_id;
 8884        let buffer = project.read_with(cx, |project, cx| project.buffer_for_id(buffer_id, cx))?;
 8885        let buffer_snapshot = buffer.read(cx).snapshot();
 8886
 8887        let row = buffer_snapshot
 8888            .summary_for_anchor::<text::PointUtf16>(&breakpoint_position.text_anchor)
 8889            .row;
 8890
 8891        let line_len = snapshot.buffer_snapshot.line_len(MultiBufferRow(row));
 8892        let anchor_end = snapshot
 8893            .buffer_snapshot
 8894            .anchor_after(Point::new(row, line_len));
 8895
 8896        let bp = self
 8897            .breakpoint_store
 8898            .as_ref()?
 8899            .read_with(cx, |breakpoint_store, cx| {
 8900                breakpoint_store
 8901                    .breakpoints(
 8902                        &buffer,
 8903                        Some(breakpoint_position.text_anchor..anchor_end.text_anchor),
 8904                        &buffer_snapshot,
 8905                        cx,
 8906                    )
 8907                    .next()
 8908                    .and_then(|(anchor, bp)| {
 8909                        let breakpoint_row = buffer_snapshot
 8910                            .summary_for_anchor::<text::PointUtf16>(anchor)
 8911                            .row;
 8912
 8913                        if breakpoint_row == row {
 8914                            snapshot
 8915                                .buffer_snapshot
 8916                                .anchor_in_excerpt(enclosing_excerpt, *anchor)
 8917                                .map(|anchor| (anchor, bp.clone()))
 8918                        } else {
 8919                            None
 8920                        }
 8921                    })
 8922            });
 8923        bp
 8924    }
 8925
 8926    pub fn edit_log_breakpoint(
 8927        &mut self,
 8928        _: &EditLogBreakpoint,
 8929        window: &mut Window,
 8930        cx: &mut Context<Self>,
 8931    ) {
 8932        for (anchor, breakpoint) in self.breakpoints_at_cursors(window, cx) {
 8933            let breakpoint = breakpoint.unwrap_or_else(|| Breakpoint {
 8934                message: None,
 8935                state: BreakpointState::Enabled,
 8936                condition: None,
 8937                hit_condition: None,
 8938            });
 8939
 8940            self.add_edit_breakpoint_block(
 8941                anchor,
 8942                &breakpoint,
 8943                BreakpointPromptEditAction::Log,
 8944                window,
 8945                cx,
 8946            );
 8947        }
 8948    }
 8949
 8950    fn breakpoints_at_cursors(
 8951        &self,
 8952        window: &mut Window,
 8953        cx: &mut Context<Self>,
 8954    ) -> Vec<(Anchor, Option<Breakpoint>)> {
 8955        let snapshot = self.snapshot(window, cx);
 8956        let cursors = self
 8957            .selections
 8958            .disjoint_anchors()
 8959            .into_iter()
 8960            .map(|selection| {
 8961                let cursor_position: Point = selection.head().to_point(&snapshot.buffer_snapshot);
 8962
 8963                let breakpoint_position = snapshot
 8964                    .display_snapshot
 8965                    .buffer_snapshot
 8966                    .anchor_after(Point::new(cursor_position.row, 0));
 8967                let breakpoint = self
 8968                    .breakpoint_at_anchor(breakpoint_position, &snapshot, cx)
 8969                    .map(|(anchor, breakpoint)| (anchor, Some(breakpoint)));
 8970
 8971                breakpoint.unwrap_or_else(|| (breakpoint_position, None))
 8972            })
 8973            // 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.
 8974            .collect::<HashMap<Anchor, _>>();
 8975
 8976        cursors.into_iter().collect()
 8977    }
 8978
 8979    pub fn enable_breakpoint(
 8980        &mut self,
 8981        _: &crate::actions::EnableBreakpoint,
 8982        window: &mut Window,
 8983        cx: &mut Context<Self>,
 8984    ) {
 8985        for (anchor, breakpoint) in self.breakpoints_at_cursors(window, cx) {
 8986            let Some(breakpoint) = breakpoint.filter(|breakpoint| breakpoint.is_disabled()) else {
 8987                continue;
 8988            };
 8989            self.edit_breakpoint_at_anchor(
 8990                anchor,
 8991                breakpoint,
 8992                BreakpointEditAction::InvertState,
 8993                cx,
 8994            );
 8995        }
 8996    }
 8997
 8998    pub fn disable_breakpoint(
 8999        &mut self,
 9000        _: &crate::actions::DisableBreakpoint,
 9001        window: &mut Window,
 9002        cx: &mut Context<Self>,
 9003    ) {
 9004        for (anchor, breakpoint) in self.breakpoints_at_cursors(window, cx) {
 9005            let Some(breakpoint) = breakpoint.filter(|breakpoint| breakpoint.is_enabled()) else {
 9006                continue;
 9007            };
 9008            self.edit_breakpoint_at_anchor(
 9009                anchor,
 9010                breakpoint,
 9011                BreakpointEditAction::InvertState,
 9012                cx,
 9013            );
 9014        }
 9015    }
 9016
 9017    pub fn toggle_breakpoint(
 9018        &mut self,
 9019        _: &crate::actions::ToggleBreakpoint,
 9020        window: &mut Window,
 9021        cx: &mut Context<Self>,
 9022    ) {
 9023        for (anchor, breakpoint) in self.breakpoints_at_cursors(window, cx) {
 9024            if let Some(breakpoint) = breakpoint {
 9025                self.edit_breakpoint_at_anchor(
 9026                    anchor,
 9027                    breakpoint,
 9028                    BreakpointEditAction::Toggle,
 9029                    cx,
 9030                );
 9031            } else {
 9032                self.edit_breakpoint_at_anchor(
 9033                    anchor,
 9034                    Breakpoint::new_standard(),
 9035                    BreakpointEditAction::Toggle,
 9036                    cx,
 9037                );
 9038            }
 9039        }
 9040    }
 9041
 9042    pub fn edit_breakpoint_at_anchor(
 9043        &mut self,
 9044        breakpoint_position: Anchor,
 9045        breakpoint: Breakpoint,
 9046        edit_action: BreakpointEditAction,
 9047        cx: &mut Context<Self>,
 9048    ) {
 9049        let Some(breakpoint_store) = &self.breakpoint_store else {
 9050            return;
 9051        };
 9052
 9053        let Some(buffer_id) = breakpoint_position.buffer_id.or_else(|| {
 9054            if breakpoint_position == Anchor::min() {
 9055                self.buffer()
 9056                    .read(cx)
 9057                    .excerpt_buffer_ids()
 9058                    .into_iter()
 9059                    .next()
 9060            } else {
 9061                None
 9062            }
 9063        }) else {
 9064            return;
 9065        };
 9066
 9067        let Some(buffer) = self.buffer().read(cx).buffer(buffer_id) else {
 9068            return;
 9069        };
 9070
 9071        breakpoint_store.update(cx, |breakpoint_store, cx| {
 9072            breakpoint_store.toggle_breakpoint(
 9073                buffer,
 9074                (breakpoint_position.text_anchor, breakpoint),
 9075                edit_action,
 9076                cx,
 9077            );
 9078        });
 9079
 9080        cx.notify();
 9081    }
 9082
 9083    #[cfg(any(test, feature = "test-support"))]
 9084    pub fn breakpoint_store(&self) -> Option<Entity<BreakpointStore>> {
 9085        self.breakpoint_store.clone()
 9086    }
 9087
 9088    pub fn prepare_restore_change(
 9089        &self,
 9090        revert_changes: &mut HashMap<BufferId, Vec<(Range<text::Anchor>, Rope)>>,
 9091        hunk: &MultiBufferDiffHunk,
 9092        cx: &mut App,
 9093    ) -> Option<()> {
 9094        if hunk.is_created_file() {
 9095            return None;
 9096        }
 9097        let buffer = self.buffer.read(cx);
 9098        let diff = buffer.diff_for(hunk.buffer_id)?;
 9099        let buffer = buffer.buffer(hunk.buffer_id)?;
 9100        let buffer = buffer.read(cx);
 9101        let original_text = diff
 9102            .read(cx)
 9103            .base_text()
 9104            .as_rope()
 9105            .slice(hunk.diff_base_byte_range.clone());
 9106        let buffer_snapshot = buffer.snapshot();
 9107        let buffer_revert_changes = revert_changes.entry(buffer.remote_id()).or_default();
 9108        if let Err(i) = buffer_revert_changes.binary_search_by(|probe| {
 9109            probe
 9110                .0
 9111                .start
 9112                .cmp(&hunk.buffer_range.start, &buffer_snapshot)
 9113                .then(probe.0.end.cmp(&hunk.buffer_range.end, &buffer_snapshot))
 9114        }) {
 9115            buffer_revert_changes.insert(i, (hunk.buffer_range.clone(), original_text));
 9116            Some(())
 9117        } else {
 9118            None
 9119        }
 9120    }
 9121
 9122    pub fn reverse_lines(&mut self, _: &ReverseLines, window: &mut Window, cx: &mut Context<Self>) {
 9123        self.manipulate_lines(window, cx, |lines| lines.reverse())
 9124    }
 9125
 9126    pub fn shuffle_lines(&mut self, _: &ShuffleLines, window: &mut Window, cx: &mut Context<Self>) {
 9127        self.manipulate_lines(window, cx, |lines| lines.shuffle(&mut thread_rng()))
 9128    }
 9129
 9130    fn manipulate_lines<Fn>(
 9131        &mut self,
 9132        window: &mut Window,
 9133        cx: &mut Context<Self>,
 9134        mut callback: Fn,
 9135    ) where
 9136        Fn: FnMut(&mut Vec<&str>),
 9137    {
 9138        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
 9139
 9140        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 9141        let buffer = self.buffer.read(cx).snapshot(cx);
 9142
 9143        let mut edits = Vec::new();
 9144
 9145        let selections = self.selections.all::<Point>(cx);
 9146        let mut selections = selections.iter().peekable();
 9147        let mut contiguous_row_selections = Vec::new();
 9148        let mut new_selections = Vec::new();
 9149        let mut added_lines = 0;
 9150        let mut removed_lines = 0;
 9151
 9152        while let Some(selection) = selections.next() {
 9153            let (start_row, end_row) = consume_contiguous_rows(
 9154                &mut contiguous_row_selections,
 9155                selection,
 9156                &display_map,
 9157                &mut selections,
 9158            );
 9159
 9160            let start_point = Point::new(start_row.0, 0);
 9161            let end_point = Point::new(
 9162                end_row.previous_row().0,
 9163                buffer.line_len(end_row.previous_row()),
 9164            );
 9165            let text = buffer
 9166                .text_for_range(start_point..end_point)
 9167                .collect::<String>();
 9168
 9169            let mut lines = text.split('\n').collect_vec();
 9170
 9171            let lines_before = lines.len();
 9172            callback(&mut lines);
 9173            let lines_after = lines.len();
 9174
 9175            edits.push((start_point..end_point, lines.join("\n")));
 9176
 9177            // Selections must change based on added and removed line count
 9178            let start_row =
 9179                MultiBufferRow(start_point.row + added_lines as u32 - removed_lines as u32);
 9180            let end_row = MultiBufferRow(start_row.0 + lines_after.saturating_sub(1) as u32);
 9181            new_selections.push(Selection {
 9182                id: selection.id,
 9183                start: start_row,
 9184                end: end_row,
 9185                goal: SelectionGoal::None,
 9186                reversed: selection.reversed,
 9187            });
 9188
 9189            if lines_after > lines_before {
 9190                added_lines += lines_after - lines_before;
 9191            } else if lines_before > lines_after {
 9192                removed_lines += lines_before - lines_after;
 9193            }
 9194        }
 9195
 9196        self.transact(window, cx, |this, window, cx| {
 9197            let buffer = this.buffer.update(cx, |buffer, cx| {
 9198                buffer.edit(edits, None, cx);
 9199                buffer.snapshot(cx)
 9200            });
 9201
 9202            // Recalculate offsets on newly edited buffer
 9203            let new_selections = new_selections
 9204                .iter()
 9205                .map(|s| {
 9206                    let start_point = Point::new(s.start.0, 0);
 9207                    let end_point = Point::new(s.end.0, buffer.line_len(s.end));
 9208                    Selection {
 9209                        id: s.id,
 9210                        start: buffer.point_to_offset(start_point),
 9211                        end: buffer.point_to_offset(end_point),
 9212                        goal: s.goal,
 9213                        reversed: s.reversed,
 9214                    }
 9215                })
 9216                .collect();
 9217
 9218            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9219                s.select(new_selections);
 9220            });
 9221
 9222            this.request_autoscroll(Autoscroll::fit(), cx);
 9223        });
 9224    }
 9225
 9226    pub fn toggle_case(&mut self, _: &ToggleCase, window: &mut Window, cx: &mut Context<Self>) {
 9227        self.manipulate_text(window, cx, |text| {
 9228            let has_upper_case_characters = text.chars().any(|c| c.is_uppercase());
 9229            if has_upper_case_characters {
 9230                text.to_lowercase()
 9231            } else {
 9232                text.to_uppercase()
 9233            }
 9234        })
 9235    }
 9236
 9237    pub fn convert_to_upper_case(
 9238        &mut self,
 9239        _: &ConvertToUpperCase,
 9240        window: &mut Window,
 9241        cx: &mut Context<Self>,
 9242    ) {
 9243        self.manipulate_text(window, cx, |text| text.to_uppercase())
 9244    }
 9245
 9246    pub fn convert_to_lower_case(
 9247        &mut self,
 9248        _: &ConvertToLowerCase,
 9249        window: &mut Window,
 9250        cx: &mut Context<Self>,
 9251    ) {
 9252        self.manipulate_text(window, cx, |text| text.to_lowercase())
 9253    }
 9254
 9255    pub fn convert_to_title_case(
 9256        &mut self,
 9257        _: &ConvertToTitleCase,
 9258        window: &mut Window,
 9259        cx: &mut Context<Self>,
 9260    ) {
 9261        self.manipulate_text(window, cx, |text| {
 9262            text.split('\n')
 9263                .map(|line| line.to_case(Case::Title))
 9264                .join("\n")
 9265        })
 9266    }
 9267
 9268    pub fn convert_to_snake_case(
 9269        &mut self,
 9270        _: &ConvertToSnakeCase,
 9271        window: &mut Window,
 9272        cx: &mut Context<Self>,
 9273    ) {
 9274        self.manipulate_text(window, cx, |text| text.to_case(Case::Snake))
 9275    }
 9276
 9277    pub fn convert_to_kebab_case(
 9278        &mut self,
 9279        _: &ConvertToKebabCase,
 9280        window: &mut Window,
 9281        cx: &mut Context<Self>,
 9282    ) {
 9283        self.manipulate_text(window, cx, |text| text.to_case(Case::Kebab))
 9284    }
 9285
 9286    pub fn convert_to_upper_camel_case(
 9287        &mut self,
 9288        _: &ConvertToUpperCamelCase,
 9289        window: &mut Window,
 9290        cx: &mut Context<Self>,
 9291    ) {
 9292        self.manipulate_text(window, cx, |text| {
 9293            text.split('\n')
 9294                .map(|line| line.to_case(Case::UpperCamel))
 9295                .join("\n")
 9296        })
 9297    }
 9298
 9299    pub fn convert_to_lower_camel_case(
 9300        &mut self,
 9301        _: &ConvertToLowerCamelCase,
 9302        window: &mut Window,
 9303        cx: &mut Context<Self>,
 9304    ) {
 9305        self.manipulate_text(window, cx, |text| text.to_case(Case::Camel))
 9306    }
 9307
 9308    pub fn convert_to_opposite_case(
 9309        &mut self,
 9310        _: &ConvertToOppositeCase,
 9311        window: &mut Window,
 9312        cx: &mut Context<Self>,
 9313    ) {
 9314        self.manipulate_text(window, cx, |text| {
 9315            text.chars()
 9316                .fold(String::with_capacity(text.len()), |mut t, c| {
 9317                    if c.is_uppercase() {
 9318                        t.extend(c.to_lowercase());
 9319                    } else {
 9320                        t.extend(c.to_uppercase());
 9321                    }
 9322                    t
 9323                })
 9324        })
 9325    }
 9326
 9327    pub fn convert_to_rot13(
 9328        &mut self,
 9329        _: &ConvertToRot13,
 9330        window: &mut Window,
 9331        cx: &mut Context<Self>,
 9332    ) {
 9333        self.manipulate_text(window, cx, |text| {
 9334            text.chars()
 9335                .map(|c| match c {
 9336                    'A'..='M' | 'a'..='m' => ((c as u8) + 13) as char,
 9337                    'N'..='Z' | 'n'..='z' => ((c as u8) - 13) as char,
 9338                    _ => c,
 9339                })
 9340                .collect()
 9341        })
 9342    }
 9343
 9344    pub fn convert_to_rot47(
 9345        &mut self,
 9346        _: &ConvertToRot47,
 9347        window: &mut Window,
 9348        cx: &mut Context<Self>,
 9349    ) {
 9350        self.manipulate_text(window, cx, |text| {
 9351            text.chars()
 9352                .map(|c| {
 9353                    let code_point = c as u32;
 9354                    if code_point >= 33 && code_point <= 126 {
 9355                        return char::from_u32(33 + ((code_point + 14) % 94)).unwrap();
 9356                    }
 9357                    c
 9358                })
 9359                .collect()
 9360        })
 9361    }
 9362
 9363    fn manipulate_text<Fn>(&mut self, window: &mut Window, cx: &mut Context<Self>, mut callback: Fn)
 9364    where
 9365        Fn: FnMut(&str) -> String,
 9366    {
 9367        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 9368        let buffer = self.buffer.read(cx).snapshot(cx);
 9369
 9370        let mut new_selections = Vec::new();
 9371        let mut edits = Vec::new();
 9372        let mut selection_adjustment = 0i32;
 9373
 9374        for selection in self.selections.all::<usize>(cx) {
 9375            let selection_is_empty = selection.is_empty();
 9376
 9377            let (start, end) = if selection_is_empty {
 9378                let word_range = movement::surrounding_word(
 9379                    &display_map,
 9380                    selection.start.to_display_point(&display_map),
 9381                );
 9382                let start = word_range.start.to_offset(&display_map, Bias::Left);
 9383                let end = word_range.end.to_offset(&display_map, Bias::Left);
 9384                (start, end)
 9385            } else {
 9386                (selection.start, selection.end)
 9387            };
 9388
 9389            let text = buffer.text_for_range(start..end).collect::<String>();
 9390            let old_length = text.len() as i32;
 9391            let text = callback(&text);
 9392
 9393            new_selections.push(Selection {
 9394                start: (start as i32 - selection_adjustment) as usize,
 9395                end: ((start + text.len()) as i32 - selection_adjustment) as usize,
 9396                goal: SelectionGoal::None,
 9397                ..selection
 9398            });
 9399
 9400            selection_adjustment += old_length - text.len() as i32;
 9401
 9402            edits.push((start..end, text));
 9403        }
 9404
 9405        self.transact(window, cx, |this, window, cx| {
 9406            this.buffer.update(cx, |buffer, cx| {
 9407                buffer.edit(edits, None, cx);
 9408            });
 9409
 9410            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9411                s.select(new_selections);
 9412            });
 9413
 9414            this.request_autoscroll(Autoscroll::fit(), cx);
 9415        });
 9416    }
 9417
 9418    pub fn duplicate(
 9419        &mut self,
 9420        upwards: bool,
 9421        whole_lines: bool,
 9422        window: &mut Window,
 9423        cx: &mut Context<Self>,
 9424    ) {
 9425        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
 9426
 9427        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 9428        let buffer = &display_map.buffer_snapshot;
 9429        let selections = self.selections.all::<Point>(cx);
 9430
 9431        let mut edits = Vec::new();
 9432        let mut selections_iter = selections.iter().peekable();
 9433        while let Some(selection) = selections_iter.next() {
 9434            let mut rows = selection.spanned_rows(false, &display_map);
 9435            // duplicate line-wise
 9436            if whole_lines || selection.start == selection.end {
 9437                // Avoid duplicating the same lines twice.
 9438                while let Some(next_selection) = selections_iter.peek() {
 9439                    let next_rows = next_selection.spanned_rows(false, &display_map);
 9440                    if next_rows.start < rows.end {
 9441                        rows.end = next_rows.end;
 9442                        selections_iter.next().unwrap();
 9443                    } else {
 9444                        break;
 9445                    }
 9446                }
 9447
 9448                // Copy the text from the selected row region and splice it either at the start
 9449                // or end of the region.
 9450                let start = Point::new(rows.start.0, 0);
 9451                let end = Point::new(
 9452                    rows.end.previous_row().0,
 9453                    buffer.line_len(rows.end.previous_row()),
 9454                );
 9455                let text = buffer
 9456                    .text_for_range(start..end)
 9457                    .chain(Some("\n"))
 9458                    .collect::<String>();
 9459                let insert_location = if upwards {
 9460                    Point::new(rows.end.0, 0)
 9461                } else {
 9462                    start
 9463                };
 9464                edits.push((insert_location..insert_location, text));
 9465            } else {
 9466                // duplicate character-wise
 9467                let start = selection.start;
 9468                let end = selection.end;
 9469                let text = buffer.text_for_range(start..end).collect::<String>();
 9470                edits.push((selection.end..selection.end, text));
 9471            }
 9472        }
 9473
 9474        self.transact(window, cx, |this, _, cx| {
 9475            this.buffer.update(cx, |buffer, cx| {
 9476                buffer.edit(edits, None, cx);
 9477            });
 9478
 9479            this.request_autoscroll(Autoscroll::fit(), cx);
 9480        });
 9481    }
 9482
 9483    pub fn duplicate_line_up(
 9484        &mut self,
 9485        _: &DuplicateLineUp,
 9486        window: &mut Window,
 9487        cx: &mut Context<Self>,
 9488    ) {
 9489        self.duplicate(true, true, window, cx);
 9490    }
 9491
 9492    pub fn duplicate_line_down(
 9493        &mut self,
 9494        _: &DuplicateLineDown,
 9495        window: &mut Window,
 9496        cx: &mut Context<Self>,
 9497    ) {
 9498        self.duplicate(false, true, window, cx);
 9499    }
 9500
 9501    pub fn duplicate_selection(
 9502        &mut self,
 9503        _: &DuplicateSelection,
 9504        window: &mut Window,
 9505        cx: &mut Context<Self>,
 9506    ) {
 9507        self.duplicate(false, false, window, cx);
 9508    }
 9509
 9510    pub fn move_line_up(&mut self, _: &MoveLineUp, window: &mut Window, cx: &mut Context<Self>) {
 9511        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
 9512
 9513        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 9514        let buffer = self.buffer.read(cx).snapshot(cx);
 9515
 9516        let mut edits = Vec::new();
 9517        let mut unfold_ranges = Vec::new();
 9518        let mut refold_creases = Vec::new();
 9519
 9520        let selections = self.selections.all::<Point>(cx);
 9521        let mut selections = selections.iter().peekable();
 9522        let mut contiguous_row_selections = Vec::new();
 9523        let mut new_selections = Vec::new();
 9524
 9525        while let Some(selection) = selections.next() {
 9526            // Find all the selections that span a contiguous row range
 9527            let (start_row, end_row) = consume_contiguous_rows(
 9528                &mut contiguous_row_selections,
 9529                selection,
 9530                &display_map,
 9531                &mut selections,
 9532            );
 9533
 9534            // Move the text spanned by the row range to be before the line preceding the row range
 9535            if start_row.0 > 0 {
 9536                let range_to_move = Point::new(
 9537                    start_row.previous_row().0,
 9538                    buffer.line_len(start_row.previous_row()),
 9539                )
 9540                    ..Point::new(
 9541                        end_row.previous_row().0,
 9542                        buffer.line_len(end_row.previous_row()),
 9543                    );
 9544                let insertion_point = display_map
 9545                    .prev_line_boundary(Point::new(start_row.previous_row().0, 0))
 9546                    .0;
 9547
 9548                // Don't move lines across excerpts
 9549                if buffer
 9550                    .excerpt_containing(insertion_point..range_to_move.end)
 9551                    .is_some()
 9552                {
 9553                    let text = buffer
 9554                        .text_for_range(range_to_move.clone())
 9555                        .flat_map(|s| s.chars())
 9556                        .skip(1)
 9557                        .chain(['\n'])
 9558                        .collect::<String>();
 9559
 9560                    edits.push((
 9561                        buffer.anchor_after(range_to_move.start)
 9562                            ..buffer.anchor_before(range_to_move.end),
 9563                        String::new(),
 9564                    ));
 9565                    let insertion_anchor = buffer.anchor_after(insertion_point);
 9566                    edits.push((insertion_anchor..insertion_anchor, text));
 9567
 9568                    let row_delta = range_to_move.start.row - insertion_point.row + 1;
 9569
 9570                    // Move selections up
 9571                    new_selections.extend(contiguous_row_selections.drain(..).map(
 9572                        |mut selection| {
 9573                            selection.start.row -= row_delta;
 9574                            selection.end.row -= row_delta;
 9575                            selection
 9576                        },
 9577                    ));
 9578
 9579                    // Move folds up
 9580                    unfold_ranges.push(range_to_move.clone());
 9581                    for fold in display_map.folds_in_range(
 9582                        buffer.anchor_before(range_to_move.start)
 9583                            ..buffer.anchor_after(range_to_move.end),
 9584                    ) {
 9585                        let mut start = fold.range.start.to_point(&buffer);
 9586                        let mut end = fold.range.end.to_point(&buffer);
 9587                        start.row -= row_delta;
 9588                        end.row -= row_delta;
 9589                        refold_creases.push(Crease::simple(start..end, fold.placeholder.clone()));
 9590                    }
 9591                }
 9592            }
 9593
 9594            // If we didn't move line(s), preserve the existing selections
 9595            new_selections.append(&mut contiguous_row_selections);
 9596        }
 9597
 9598        self.transact(window, cx, |this, window, cx| {
 9599            this.unfold_ranges(&unfold_ranges, true, true, cx);
 9600            this.buffer.update(cx, |buffer, cx| {
 9601                for (range, text) in edits {
 9602                    buffer.edit([(range, text)], None, cx);
 9603                }
 9604            });
 9605            this.fold_creases(refold_creases, true, window, cx);
 9606            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9607                s.select(new_selections);
 9608            })
 9609        });
 9610    }
 9611
 9612    pub fn move_line_down(
 9613        &mut self,
 9614        _: &MoveLineDown,
 9615        window: &mut Window,
 9616        cx: &mut Context<Self>,
 9617    ) {
 9618        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
 9619
 9620        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 9621        let buffer = self.buffer.read(cx).snapshot(cx);
 9622
 9623        let mut edits = Vec::new();
 9624        let mut unfold_ranges = Vec::new();
 9625        let mut refold_creases = Vec::new();
 9626
 9627        let selections = self.selections.all::<Point>(cx);
 9628        let mut selections = selections.iter().peekable();
 9629        let mut contiguous_row_selections = Vec::new();
 9630        let mut new_selections = Vec::new();
 9631
 9632        while let Some(selection) = selections.next() {
 9633            // Find all the selections that span a contiguous row range
 9634            let (start_row, end_row) = consume_contiguous_rows(
 9635                &mut contiguous_row_selections,
 9636                selection,
 9637                &display_map,
 9638                &mut selections,
 9639            );
 9640
 9641            // Move the text spanned by the row range to be after the last line of the row range
 9642            if end_row.0 <= buffer.max_point().row {
 9643                let range_to_move =
 9644                    MultiBufferPoint::new(start_row.0, 0)..MultiBufferPoint::new(end_row.0, 0);
 9645                let insertion_point = display_map
 9646                    .next_line_boundary(MultiBufferPoint::new(end_row.0, 0))
 9647                    .0;
 9648
 9649                // Don't move lines across excerpt boundaries
 9650                if buffer
 9651                    .excerpt_containing(range_to_move.start..insertion_point)
 9652                    .is_some()
 9653                {
 9654                    let mut text = String::from("\n");
 9655                    text.extend(buffer.text_for_range(range_to_move.clone()));
 9656                    text.pop(); // Drop trailing newline
 9657                    edits.push((
 9658                        buffer.anchor_after(range_to_move.start)
 9659                            ..buffer.anchor_before(range_to_move.end),
 9660                        String::new(),
 9661                    ));
 9662                    let insertion_anchor = buffer.anchor_after(insertion_point);
 9663                    edits.push((insertion_anchor..insertion_anchor, text));
 9664
 9665                    let row_delta = insertion_point.row - range_to_move.end.row + 1;
 9666
 9667                    // Move selections down
 9668                    new_selections.extend(contiguous_row_selections.drain(..).map(
 9669                        |mut selection| {
 9670                            selection.start.row += row_delta;
 9671                            selection.end.row += row_delta;
 9672                            selection
 9673                        },
 9674                    ));
 9675
 9676                    // Move folds down
 9677                    unfold_ranges.push(range_to_move.clone());
 9678                    for fold in display_map.folds_in_range(
 9679                        buffer.anchor_before(range_to_move.start)
 9680                            ..buffer.anchor_after(range_to_move.end),
 9681                    ) {
 9682                        let mut start = fold.range.start.to_point(&buffer);
 9683                        let mut end = fold.range.end.to_point(&buffer);
 9684                        start.row += row_delta;
 9685                        end.row += row_delta;
 9686                        refold_creases.push(Crease::simple(start..end, fold.placeholder.clone()));
 9687                    }
 9688                }
 9689            }
 9690
 9691            // If we didn't move line(s), preserve the existing selections
 9692            new_selections.append(&mut contiguous_row_selections);
 9693        }
 9694
 9695        self.transact(window, cx, |this, window, cx| {
 9696            this.unfold_ranges(&unfold_ranges, true, true, cx);
 9697            this.buffer.update(cx, |buffer, cx| {
 9698                for (range, text) in edits {
 9699                    buffer.edit([(range, text)], None, cx);
 9700                }
 9701            });
 9702            this.fold_creases(refold_creases, true, window, cx);
 9703            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9704                s.select(new_selections)
 9705            });
 9706        });
 9707    }
 9708
 9709    pub fn transpose(&mut self, _: &Transpose, window: &mut Window, cx: &mut Context<Self>) {
 9710        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
 9711        let text_layout_details = &self.text_layout_details(window);
 9712        self.transact(window, cx, |this, window, cx| {
 9713            let edits = this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9714                let mut edits: Vec<(Range<usize>, String)> = Default::default();
 9715                s.move_with(|display_map, selection| {
 9716                    if !selection.is_empty() {
 9717                        return;
 9718                    }
 9719
 9720                    let mut head = selection.head();
 9721                    let mut transpose_offset = head.to_offset(display_map, Bias::Right);
 9722                    if head.column() == display_map.line_len(head.row()) {
 9723                        transpose_offset = display_map
 9724                            .buffer_snapshot
 9725                            .clip_offset(transpose_offset.saturating_sub(1), Bias::Left);
 9726                    }
 9727
 9728                    if transpose_offset == 0 {
 9729                        return;
 9730                    }
 9731
 9732                    *head.column_mut() += 1;
 9733                    head = display_map.clip_point(head, Bias::Right);
 9734                    let goal = SelectionGoal::HorizontalPosition(
 9735                        display_map
 9736                            .x_for_display_point(head, text_layout_details)
 9737                            .into(),
 9738                    );
 9739                    selection.collapse_to(head, goal);
 9740
 9741                    let transpose_start = display_map
 9742                        .buffer_snapshot
 9743                        .clip_offset(transpose_offset.saturating_sub(1), Bias::Left);
 9744                    if edits.last().map_or(true, |e| e.0.end <= transpose_start) {
 9745                        let transpose_end = display_map
 9746                            .buffer_snapshot
 9747                            .clip_offset(transpose_offset + 1, Bias::Right);
 9748                        if let Some(ch) =
 9749                            display_map.buffer_snapshot.chars_at(transpose_start).next()
 9750                        {
 9751                            edits.push((transpose_start..transpose_offset, String::new()));
 9752                            edits.push((transpose_end..transpose_end, ch.to_string()));
 9753                        }
 9754                    }
 9755                });
 9756                edits
 9757            });
 9758            this.buffer
 9759                .update(cx, |buffer, cx| buffer.edit(edits, None, cx));
 9760            let selections = this.selections.all::<usize>(cx);
 9761            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9762                s.select(selections);
 9763            });
 9764        });
 9765    }
 9766
 9767    pub fn rewrap(&mut self, _: &Rewrap, _: &mut Window, cx: &mut Context<Self>) {
 9768        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
 9769        self.rewrap_impl(RewrapOptions::default(), cx)
 9770    }
 9771
 9772    pub fn rewrap_impl(&mut self, options: RewrapOptions, cx: &mut Context<Self>) {
 9773        let buffer = self.buffer.read(cx).snapshot(cx);
 9774        let selections = self.selections.all::<Point>(cx);
 9775        let mut selections = selections.iter().peekable();
 9776
 9777        let mut edits = Vec::new();
 9778        let mut rewrapped_row_ranges = Vec::<RangeInclusive<u32>>::new();
 9779
 9780        while let Some(selection) = selections.next() {
 9781            let mut start_row = selection.start.row;
 9782            let mut end_row = selection.end.row;
 9783
 9784            // Skip selections that overlap with a range that has already been rewrapped.
 9785            let selection_range = start_row..end_row;
 9786            if rewrapped_row_ranges
 9787                .iter()
 9788                .any(|range| range.overlaps(&selection_range))
 9789            {
 9790                continue;
 9791            }
 9792
 9793            let tab_size = buffer.language_settings_at(selection.head(), cx).tab_size;
 9794
 9795            // Since not all lines in the selection may be at the same indent
 9796            // level, choose the indent size that is the most common between all
 9797            // of the lines.
 9798            //
 9799            // If there is a tie, we use the deepest indent.
 9800            let (indent_size, indent_end) = {
 9801                let mut indent_size_occurrences = HashMap::default();
 9802                let mut rows_by_indent_size = HashMap::<IndentSize, Vec<u32>>::default();
 9803
 9804                for row in start_row..=end_row {
 9805                    let indent = buffer.indent_size_for_line(MultiBufferRow(row));
 9806                    rows_by_indent_size.entry(indent).or_default().push(row);
 9807                    *indent_size_occurrences.entry(indent).or_insert(0) += 1;
 9808                }
 9809
 9810                let indent_size = indent_size_occurrences
 9811                    .into_iter()
 9812                    .max_by_key(|(indent, count)| (*count, indent.len_with_expanded_tabs(tab_size)))
 9813                    .map(|(indent, _)| indent)
 9814                    .unwrap_or_default();
 9815                let row = rows_by_indent_size[&indent_size][0];
 9816                let indent_end = Point::new(row, indent_size.len);
 9817
 9818                (indent_size, indent_end)
 9819            };
 9820
 9821            let mut line_prefix = indent_size.chars().collect::<String>();
 9822
 9823            let mut inside_comment = false;
 9824            if let Some(comment_prefix) =
 9825                buffer
 9826                    .language_scope_at(selection.head())
 9827                    .and_then(|language| {
 9828                        language
 9829                            .line_comment_prefixes()
 9830                            .iter()
 9831                            .find(|prefix| buffer.contains_str_at(indent_end, prefix))
 9832                            .cloned()
 9833                    })
 9834            {
 9835                line_prefix.push_str(&comment_prefix);
 9836                inside_comment = true;
 9837            }
 9838
 9839            let language_settings = buffer.language_settings_at(selection.head(), cx);
 9840            let allow_rewrap_based_on_language = match language_settings.allow_rewrap {
 9841                RewrapBehavior::InComments => inside_comment,
 9842                RewrapBehavior::InSelections => !selection.is_empty(),
 9843                RewrapBehavior::Anywhere => true,
 9844            };
 9845
 9846            let should_rewrap = options.override_language_settings
 9847                || allow_rewrap_based_on_language
 9848                || self.hard_wrap.is_some();
 9849            if !should_rewrap {
 9850                continue;
 9851            }
 9852
 9853            if selection.is_empty() {
 9854                'expand_upwards: while start_row > 0 {
 9855                    let prev_row = start_row - 1;
 9856                    if buffer.contains_str_at(Point::new(prev_row, 0), &line_prefix)
 9857                        && buffer.line_len(MultiBufferRow(prev_row)) as usize > line_prefix.len()
 9858                    {
 9859                        start_row = prev_row;
 9860                    } else {
 9861                        break 'expand_upwards;
 9862                    }
 9863                }
 9864
 9865                'expand_downwards: while end_row < buffer.max_point().row {
 9866                    let next_row = end_row + 1;
 9867                    if buffer.contains_str_at(Point::new(next_row, 0), &line_prefix)
 9868                        && buffer.line_len(MultiBufferRow(next_row)) as usize > line_prefix.len()
 9869                    {
 9870                        end_row = next_row;
 9871                    } else {
 9872                        break 'expand_downwards;
 9873                    }
 9874                }
 9875            }
 9876
 9877            let start = Point::new(start_row, 0);
 9878            let start_offset = start.to_offset(&buffer);
 9879            let end = Point::new(end_row, buffer.line_len(MultiBufferRow(end_row)));
 9880            let selection_text = buffer.text_for_range(start..end).collect::<String>();
 9881            let Some(lines_without_prefixes) = selection_text
 9882                .lines()
 9883                .map(|line| {
 9884                    line.strip_prefix(&line_prefix)
 9885                        .or_else(|| line.trim_start().strip_prefix(&line_prefix.trim_start()))
 9886                        .ok_or_else(|| {
 9887                            anyhow!("line did not start with prefix {line_prefix:?}: {line:?}")
 9888                        })
 9889                })
 9890                .collect::<Result<Vec<_>, _>>()
 9891                .log_err()
 9892            else {
 9893                continue;
 9894            };
 9895
 9896            let wrap_column = self.hard_wrap.unwrap_or_else(|| {
 9897                buffer
 9898                    .language_settings_at(Point::new(start_row, 0), cx)
 9899                    .preferred_line_length as usize
 9900            });
 9901            let wrapped_text = wrap_with_prefix(
 9902                line_prefix,
 9903                lines_without_prefixes.join("\n"),
 9904                wrap_column,
 9905                tab_size,
 9906                options.preserve_existing_whitespace,
 9907            );
 9908
 9909            // TODO: should always use char-based diff while still supporting cursor behavior that
 9910            // matches vim.
 9911            let mut diff_options = DiffOptions::default();
 9912            if options.override_language_settings {
 9913                diff_options.max_word_diff_len = 0;
 9914                diff_options.max_word_diff_line_count = 0;
 9915            } else {
 9916                diff_options.max_word_diff_len = usize::MAX;
 9917                diff_options.max_word_diff_line_count = usize::MAX;
 9918            }
 9919
 9920            for (old_range, new_text) in
 9921                text_diff_with_options(&selection_text, &wrapped_text, diff_options)
 9922            {
 9923                let edit_start = buffer.anchor_after(start_offset + old_range.start);
 9924                let edit_end = buffer.anchor_after(start_offset + old_range.end);
 9925                edits.push((edit_start..edit_end, new_text));
 9926            }
 9927
 9928            rewrapped_row_ranges.push(start_row..=end_row);
 9929        }
 9930
 9931        self.buffer
 9932            .update(cx, |buffer, cx| buffer.edit(edits, None, cx));
 9933    }
 9934
 9935    pub fn cut_common(&mut self, window: &mut Window, cx: &mut Context<Self>) -> ClipboardItem {
 9936        let mut text = String::new();
 9937        let buffer = self.buffer.read(cx).snapshot(cx);
 9938        let mut selections = self.selections.all::<Point>(cx);
 9939        let mut clipboard_selections = Vec::with_capacity(selections.len());
 9940        {
 9941            let max_point = buffer.max_point();
 9942            let mut is_first = true;
 9943            for selection in &mut selections {
 9944                let is_entire_line = selection.is_empty() || self.selections.line_mode;
 9945                if is_entire_line {
 9946                    selection.start = Point::new(selection.start.row, 0);
 9947                    if !selection.is_empty() && selection.end.column == 0 {
 9948                        selection.end = cmp::min(max_point, selection.end);
 9949                    } else {
 9950                        selection.end = cmp::min(max_point, Point::new(selection.end.row + 1, 0));
 9951                    }
 9952                    selection.goal = SelectionGoal::None;
 9953                }
 9954                if is_first {
 9955                    is_first = false;
 9956                } else {
 9957                    text += "\n";
 9958                }
 9959                let mut len = 0;
 9960                for chunk in buffer.text_for_range(selection.start..selection.end) {
 9961                    text.push_str(chunk);
 9962                    len += chunk.len();
 9963                }
 9964                clipboard_selections.push(ClipboardSelection {
 9965                    len,
 9966                    is_entire_line,
 9967                    first_line_indent: buffer
 9968                        .indent_size_for_line(MultiBufferRow(selection.start.row))
 9969                        .len,
 9970                });
 9971            }
 9972        }
 9973
 9974        self.transact(window, cx, |this, window, cx| {
 9975            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9976                s.select(selections);
 9977            });
 9978            this.insert("", window, cx);
 9979        });
 9980        ClipboardItem::new_string_with_json_metadata(text, clipboard_selections)
 9981    }
 9982
 9983    pub fn cut(&mut self, _: &Cut, window: &mut Window, cx: &mut Context<Self>) {
 9984        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
 9985        let item = self.cut_common(window, cx);
 9986        cx.write_to_clipboard(item);
 9987    }
 9988
 9989    pub fn kill_ring_cut(&mut self, _: &KillRingCut, window: &mut Window, cx: &mut Context<Self>) {
 9990        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
 9991        self.change_selections(None, window, cx, |s| {
 9992            s.move_with(|snapshot, sel| {
 9993                if sel.is_empty() {
 9994                    sel.end = DisplayPoint::new(sel.end.row(), snapshot.line_len(sel.end.row()))
 9995                }
 9996            });
 9997        });
 9998        let item = self.cut_common(window, cx);
 9999        cx.set_global(KillRing(item))
10000    }
10001
10002    pub fn kill_ring_yank(
10003        &mut self,
10004        _: &KillRingYank,
10005        window: &mut Window,
10006        cx: &mut Context<Self>,
10007    ) {
10008        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
10009        let (text, metadata) = if let Some(KillRing(item)) = cx.try_global() {
10010            if let Some(ClipboardEntry::String(kill_ring)) = item.entries().first() {
10011                (kill_ring.text().to_string(), kill_ring.metadata_json())
10012            } else {
10013                return;
10014            }
10015        } else {
10016            return;
10017        };
10018        self.do_paste(&text, metadata, false, window, cx);
10019    }
10020
10021    pub fn copy_and_trim(&mut self, _: &CopyAndTrim, _: &mut Window, cx: &mut Context<Self>) {
10022        self.do_copy(true, cx);
10023    }
10024
10025    pub fn copy(&mut self, _: &Copy, _: &mut Window, cx: &mut Context<Self>) {
10026        self.do_copy(false, cx);
10027    }
10028
10029    fn do_copy(&self, strip_leading_indents: bool, cx: &mut Context<Self>) {
10030        let selections = self.selections.all::<Point>(cx);
10031        let buffer = self.buffer.read(cx).read(cx);
10032        let mut text = String::new();
10033
10034        let mut clipboard_selections = Vec::with_capacity(selections.len());
10035        {
10036            let max_point = buffer.max_point();
10037            let mut is_first = true;
10038            for selection in &selections {
10039                let mut start = selection.start;
10040                let mut end = selection.end;
10041                let is_entire_line = selection.is_empty() || self.selections.line_mode;
10042                if is_entire_line {
10043                    start = Point::new(start.row, 0);
10044                    end = cmp::min(max_point, Point::new(end.row + 1, 0));
10045                }
10046
10047                let mut trimmed_selections = Vec::new();
10048                if strip_leading_indents && end.row.saturating_sub(start.row) > 0 {
10049                    let row = MultiBufferRow(start.row);
10050                    let first_indent = buffer.indent_size_for_line(row);
10051                    if first_indent.len == 0 || start.column > first_indent.len {
10052                        trimmed_selections.push(start..end);
10053                    } else {
10054                        trimmed_selections.push(
10055                            Point::new(row.0, first_indent.len)
10056                                ..Point::new(row.0, buffer.line_len(row)),
10057                        );
10058                        for row in start.row + 1..=end.row {
10059                            let row_indent_size = buffer.indent_size_for_line(MultiBufferRow(row));
10060                            if row_indent_size.len >= first_indent.len {
10061                                trimmed_selections.push(
10062                                    Point::new(row, first_indent.len)
10063                                        ..Point::new(row, buffer.line_len(MultiBufferRow(row))),
10064                                );
10065                            } else {
10066                                trimmed_selections.clear();
10067                                trimmed_selections.push(start..end);
10068                                break;
10069                            }
10070                        }
10071                    }
10072                } else {
10073                    trimmed_selections.push(start..end);
10074                }
10075
10076                for trimmed_range in trimmed_selections {
10077                    if is_first {
10078                        is_first = false;
10079                    } else {
10080                        text += "\n";
10081                    }
10082                    let mut len = 0;
10083                    for chunk in buffer.text_for_range(trimmed_range.start..trimmed_range.end) {
10084                        text.push_str(chunk);
10085                        len += chunk.len();
10086                    }
10087                    clipboard_selections.push(ClipboardSelection {
10088                        len,
10089                        is_entire_line,
10090                        first_line_indent: buffer
10091                            .indent_size_for_line(MultiBufferRow(trimmed_range.start.row))
10092                            .len,
10093                    });
10094                }
10095            }
10096        }
10097
10098        cx.write_to_clipboard(ClipboardItem::new_string_with_json_metadata(
10099            text,
10100            clipboard_selections,
10101        ));
10102    }
10103
10104    pub fn do_paste(
10105        &mut self,
10106        text: &String,
10107        clipboard_selections: Option<Vec<ClipboardSelection>>,
10108        handle_entire_lines: bool,
10109        window: &mut Window,
10110        cx: &mut Context<Self>,
10111    ) {
10112        if self.read_only(cx) {
10113            return;
10114        }
10115
10116        let clipboard_text = Cow::Borrowed(text);
10117
10118        self.transact(window, cx, |this, window, cx| {
10119            if let Some(mut clipboard_selections) = clipboard_selections {
10120                let old_selections = this.selections.all::<usize>(cx);
10121                let all_selections_were_entire_line =
10122                    clipboard_selections.iter().all(|s| s.is_entire_line);
10123                let first_selection_indent_column =
10124                    clipboard_selections.first().map(|s| s.first_line_indent);
10125                if clipboard_selections.len() != old_selections.len() {
10126                    clipboard_selections.drain(..);
10127                }
10128                let cursor_offset = this.selections.last::<usize>(cx).head();
10129                let mut auto_indent_on_paste = true;
10130
10131                this.buffer.update(cx, |buffer, cx| {
10132                    let snapshot = buffer.read(cx);
10133                    auto_indent_on_paste = snapshot
10134                        .language_settings_at(cursor_offset, cx)
10135                        .auto_indent_on_paste;
10136
10137                    let mut start_offset = 0;
10138                    let mut edits = Vec::new();
10139                    let mut original_indent_columns = Vec::new();
10140                    for (ix, selection) in old_selections.iter().enumerate() {
10141                        let to_insert;
10142                        let entire_line;
10143                        let original_indent_column;
10144                        if let Some(clipboard_selection) = clipboard_selections.get(ix) {
10145                            let end_offset = start_offset + clipboard_selection.len;
10146                            to_insert = &clipboard_text[start_offset..end_offset];
10147                            entire_line = clipboard_selection.is_entire_line;
10148                            start_offset = end_offset + 1;
10149                            original_indent_column = Some(clipboard_selection.first_line_indent);
10150                        } else {
10151                            to_insert = clipboard_text.as_str();
10152                            entire_line = all_selections_were_entire_line;
10153                            original_indent_column = first_selection_indent_column
10154                        }
10155
10156                        // If the corresponding selection was empty when this slice of the
10157                        // clipboard text was written, then the entire line containing the
10158                        // selection was copied. If this selection is also currently empty,
10159                        // then paste the line before the current line of the buffer.
10160                        let range = if selection.is_empty() && handle_entire_lines && entire_line {
10161                            let column = selection.start.to_point(&snapshot).column as usize;
10162                            let line_start = selection.start - column;
10163                            line_start..line_start
10164                        } else {
10165                            selection.range()
10166                        };
10167
10168                        edits.push((range, to_insert));
10169                        original_indent_columns.push(original_indent_column);
10170                    }
10171                    drop(snapshot);
10172
10173                    buffer.edit(
10174                        edits,
10175                        if auto_indent_on_paste {
10176                            Some(AutoindentMode::Block {
10177                                original_indent_columns,
10178                            })
10179                        } else {
10180                            None
10181                        },
10182                        cx,
10183                    );
10184                });
10185
10186                let selections = this.selections.all::<usize>(cx);
10187                this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10188                    s.select(selections)
10189                });
10190            } else {
10191                this.insert(&clipboard_text, window, cx);
10192            }
10193        });
10194    }
10195
10196    pub fn paste(&mut self, _: &Paste, window: &mut Window, cx: &mut Context<Self>) {
10197        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
10198        if let Some(item) = cx.read_from_clipboard() {
10199            let entries = item.entries();
10200
10201            match entries.first() {
10202                // For now, we only support applying metadata if there's one string. In the future, we can incorporate all the selections
10203                // of all the pasted entries.
10204                Some(ClipboardEntry::String(clipboard_string)) if entries.len() == 1 => self
10205                    .do_paste(
10206                        clipboard_string.text(),
10207                        clipboard_string.metadata_json::<Vec<ClipboardSelection>>(),
10208                        true,
10209                        window,
10210                        cx,
10211                    ),
10212                _ => self.do_paste(&item.text().unwrap_or_default(), None, true, window, cx),
10213            }
10214        }
10215    }
10216
10217    pub fn undo(&mut self, _: &Undo, window: &mut Window, cx: &mut Context<Self>) {
10218        if self.read_only(cx) {
10219            return;
10220        }
10221
10222        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
10223
10224        if let Some(transaction_id) = self.buffer.update(cx, |buffer, cx| buffer.undo(cx)) {
10225            if let Some((selections, _)) =
10226                self.selection_history.transaction(transaction_id).cloned()
10227            {
10228                self.change_selections(None, window, cx, |s| {
10229                    s.select_anchors(selections.to_vec());
10230                });
10231            } else {
10232                log::error!(
10233                    "No entry in selection_history found for undo. \
10234                     This may correspond to a bug where undo does not update the selection. \
10235                     If this is occurring, please add details to \
10236                     https://github.com/zed-industries/zed/issues/22692"
10237                );
10238            }
10239            self.request_autoscroll(Autoscroll::fit(), cx);
10240            self.unmark_text(window, cx);
10241            self.refresh_inline_completion(true, false, window, cx);
10242            cx.emit(EditorEvent::Edited { transaction_id });
10243            cx.emit(EditorEvent::TransactionUndone { transaction_id });
10244        }
10245    }
10246
10247    pub fn redo(&mut self, _: &Redo, window: &mut Window, cx: &mut Context<Self>) {
10248        if self.read_only(cx) {
10249            return;
10250        }
10251
10252        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
10253
10254        if let Some(transaction_id) = self.buffer.update(cx, |buffer, cx| buffer.redo(cx)) {
10255            if let Some((_, Some(selections))) =
10256                self.selection_history.transaction(transaction_id).cloned()
10257            {
10258                self.change_selections(None, window, cx, |s| {
10259                    s.select_anchors(selections.to_vec());
10260                });
10261            } else {
10262                log::error!(
10263                    "No entry in selection_history found for redo. \
10264                     This may correspond to a bug where undo does not update the selection. \
10265                     If this is occurring, please add details to \
10266                     https://github.com/zed-industries/zed/issues/22692"
10267                );
10268            }
10269            self.request_autoscroll(Autoscroll::fit(), cx);
10270            self.unmark_text(window, cx);
10271            self.refresh_inline_completion(true, false, window, cx);
10272            cx.emit(EditorEvent::Edited { transaction_id });
10273        }
10274    }
10275
10276    pub fn finalize_last_transaction(&mut self, cx: &mut Context<Self>) {
10277        self.buffer
10278            .update(cx, |buffer, cx| buffer.finalize_last_transaction(cx));
10279    }
10280
10281    pub fn group_until_transaction(&mut self, tx_id: TransactionId, cx: &mut Context<Self>) {
10282        self.buffer
10283            .update(cx, |buffer, cx| buffer.group_until_transaction(tx_id, cx));
10284    }
10285
10286    pub fn move_left(&mut self, _: &MoveLeft, window: &mut Window, cx: &mut Context<Self>) {
10287        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
10288        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10289            s.move_with(|map, selection| {
10290                let cursor = if selection.is_empty() {
10291                    movement::left(map, selection.start)
10292                } else {
10293                    selection.start
10294                };
10295                selection.collapse_to(cursor, SelectionGoal::None);
10296            });
10297        })
10298    }
10299
10300    pub fn select_left(&mut self, _: &SelectLeft, window: &mut Window, cx: &mut Context<Self>) {
10301        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
10302        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10303            s.move_heads_with(|map, head, _| (movement::left(map, head), SelectionGoal::None));
10304        })
10305    }
10306
10307    pub fn move_right(&mut self, _: &MoveRight, window: &mut Window, cx: &mut Context<Self>) {
10308        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
10309        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10310            s.move_with(|map, selection| {
10311                let cursor = if selection.is_empty() {
10312                    movement::right(map, selection.end)
10313                } else {
10314                    selection.end
10315                };
10316                selection.collapse_to(cursor, SelectionGoal::None)
10317            });
10318        })
10319    }
10320
10321    pub fn select_right(&mut self, _: &SelectRight, window: &mut Window, cx: &mut Context<Self>) {
10322        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
10323        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10324            s.move_heads_with(|map, head, _| (movement::right(map, head), SelectionGoal::None));
10325        })
10326    }
10327
10328    pub fn move_up(&mut self, _: &MoveUp, window: &mut Window, cx: &mut Context<Self>) {
10329        if self.take_rename(true, window, cx).is_some() {
10330            return;
10331        }
10332
10333        if matches!(self.mode, EditorMode::SingleLine { .. }) {
10334            cx.propagate();
10335            return;
10336        }
10337
10338        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
10339
10340        let text_layout_details = &self.text_layout_details(window);
10341        let selection_count = self.selections.count();
10342        let first_selection = self.selections.first_anchor();
10343
10344        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10345            s.move_with(|map, selection| {
10346                if !selection.is_empty() {
10347                    selection.goal = SelectionGoal::None;
10348                }
10349                let (cursor, goal) = movement::up(
10350                    map,
10351                    selection.start,
10352                    selection.goal,
10353                    false,
10354                    text_layout_details,
10355                );
10356                selection.collapse_to(cursor, goal);
10357            });
10358        });
10359
10360        if selection_count == 1 && first_selection.range() == self.selections.first_anchor().range()
10361        {
10362            cx.propagate();
10363        }
10364    }
10365
10366    pub fn move_up_by_lines(
10367        &mut self,
10368        action: &MoveUpByLines,
10369        window: &mut Window,
10370        cx: &mut Context<Self>,
10371    ) {
10372        if self.take_rename(true, window, cx).is_some() {
10373            return;
10374        }
10375
10376        if matches!(self.mode, EditorMode::SingleLine { .. }) {
10377            cx.propagate();
10378            return;
10379        }
10380
10381        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
10382
10383        let text_layout_details = &self.text_layout_details(window);
10384
10385        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10386            s.move_with(|map, selection| {
10387                if !selection.is_empty() {
10388                    selection.goal = SelectionGoal::None;
10389                }
10390                let (cursor, goal) = movement::up_by_rows(
10391                    map,
10392                    selection.start,
10393                    action.lines,
10394                    selection.goal,
10395                    false,
10396                    text_layout_details,
10397                );
10398                selection.collapse_to(cursor, goal);
10399            });
10400        })
10401    }
10402
10403    pub fn move_down_by_lines(
10404        &mut self,
10405        action: &MoveDownByLines,
10406        window: &mut Window,
10407        cx: &mut Context<Self>,
10408    ) {
10409        if self.take_rename(true, window, cx).is_some() {
10410            return;
10411        }
10412
10413        if matches!(self.mode, EditorMode::SingleLine { .. }) {
10414            cx.propagate();
10415            return;
10416        }
10417
10418        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
10419
10420        let text_layout_details = &self.text_layout_details(window);
10421
10422        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10423            s.move_with(|map, selection| {
10424                if !selection.is_empty() {
10425                    selection.goal = SelectionGoal::None;
10426                }
10427                let (cursor, goal) = movement::down_by_rows(
10428                    map,
10429                    selection.start,
10430                    action.lines,
10431                    selection.goal,
10432                    false,
10433                    text_layout_details,
10434                );
10435                selection.collapse_to(cursor, goal);
10436            });
10437        })
10438    }
10439
10440    pub fn select_down_by_lines(
10441        &mut self,
10442        action: &SelectDownByLines,
10443        window: &mut Window,
10444        cx: &mut Context<Self>,
10445    ) {
10446        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
10447        let text_layout_details = &self.text_layout_details(window);
10448        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10449            s.move_heads_with(|map, head, goal| {
10450                movement::down_by_rows(map, head, action.lines, goal, false, text_layout_details)
10451            })
10452        })
10453    }
10454
10455    pub fn select_up_by_lines(
10456        &mut self,
10457        action: &SelectUpByLines,
10458        window: &mut Window,
10459        cx: &mut Context<Self>,
10460    ) {
10461        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
10462        let text_layout_details = &self.text_layout_details(window);
10463        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10464            s.move_heads_with(|map, head, goal| {
10465                movement::up_by_rows(map, head, action.lines, goal, false, text_layout_details)
10466            })
10467        })
10468    }
10469
10470    pub fn select_page_up(
10471        &mut self,
10472        _: &SelectPageUp,
10473        window: &mut Window,
10474        cx: &mut Context<Self>,
10475    ) {
10476        let Some(row_count) = self.visible_row_count() else {
10477            return;
10478        };
10479
10480        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
10481
10482        let text_layout_details = &self.text_layout_details(window);
10483
10484        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10485            s.move_heads_with(|map, head, goal| {
10486                movement::up_by_rows(map, head, row_count, goal, false, text_layout_details)
10487            })
10488        })
10489    }
10490
10491    pub fn move_page_up(
10492        &mut self,
10493        action: &MovePageUp,
10494        window: &mut Window,
10495        cx: &mut Context<Self>,
10496    ) {
10497        if self.take_rename(true, window, cx).is_some() {
10498            return;
10499        }
10500
10501        if self
10502            .context_menu
10503            .borrow_mut()
10504            .as_mut()
10505            .map(|menu| menu.select_first(self.completion_provider.as_deref(), cx))
10506            .unwrap_or(false)
10507        {
10508            return;
10509        }
10510
10511        if matches!(self.mode, EditorMode::SingleLine { .. }) {
10512            cx.propagate();
10513            return;
10514        }
10515
10516        let Some(row_count) = self.visible_row_count() else {
10517            return;
10518        };
10519
10520        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
10521
10522        let autoscroll = if action.center_cursor {
10523            Autoscroll::center()
10524        } else {
10525            Autoscroll::fit()
10526        };
10527
10528        let text_layout_details = &self.text_layout_details(window);
10529
10530        self.change_selections(Some(autoscroll), window, cx, |s| {
10531            s.move_with(|map, selection| {
10532                if !selection.is_empty() {
10533                    selection.goal = SelectionGoal::None;
10534                }
10535                let (cursor, goal) = movement::up_by_rows(
10536                    map,
10537                    selection.end,
10538                    row_count,
10539                    selection.goal,
10540                    false,
10541                    text_layout_details,
10542                );
10543                selection.collapse_to(cursor, goal);
10544            });
10545        });
10546    }
10547
10548    pub fn select_up(&mut self, _: &SelectUp, window: &mut Window, cx: &mut Context<Self>) {
10549        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
10550        let text_layout_details = &self.text_layout_details(window);
10551        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10552            s.move_heads_with(|map, head, goal| {
10553                movement::up(map, head, goal, false, text_layout_details)
10554            })
10555        })
10556    }
10557
10558    pub fn move_down(&mut self, _: &MoveDown, window: &mut Window, cx: &mut Context<Self>) {
10559        self.take_rename(true, window, cx);
10560
10561        if matches!(self.mode, EditorMode::SingleLine { .. }) {
10562            cx.propagate();
10563            return;
10564        }
10565
10566        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
10567
10568        let text_layout_details = &self.text_layout_details(window);
10569        let selection_count = self.selections.count();
10570        let first_selection = self.selections.first_anchor();
10571
10572        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10573            s.move_with(|map, selection| {
10574                if !selection.is_empty() {
10575                    selection.goal = SelectionGoal::None;
10576                }
10577                let (cursor, goal) = movement::down(
10578                    map,
10579                    selection.end,
10580                    selection.goal,
10581                    false,
10582                    text_layout_details,
10583                );
10584                selection.collapse_to(cursor, goal);
10585            });
10586        });
10587
10588        if selection_count == 1 && first_selection.range() == self.selections.first_anchor().range()
10589        {
10590            cx.propagate();
10591        }
10592    }
10593
10594    pub fn select_page_down(
10595        &mut self,
10596        _: &SelectPageDown,
10597        window: &mut Window,
10598        cx: &mut Context<Self>,
10599    ) {
10600        let Some(row_count) = self.visible_row_count() else {
10601            return;
10602        };
10603
10604        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
10605
10606        let text_layout_details = &self.text_layout_details(window);
10607
10608        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10609            s.move_heads_with(|map, head, goal| {
10610                movement::down_by_rows(map, head, row_count, goal, false, text_layout_details)
10611            })
10612        })
10613    }
10614
10615    pub fn move_page_down(
10616        &mut self,
10617        action: &MovePageDown,
10618        window: &mut Window,
10619        cx: &mut Context<Self>,
10620    ) {
10621        if self.take_rename(true, window, cx).is_some() {
10622            return;
10623        }
10624
10625        if self
10626            .context_menu
10627            .borrow_mut()
10628            .as_mut()
10629            .map(|menu| menu.select_last(self.completion_provider.as_deref(), cx))
10630            .unwrap_or(false)
10631        {
10632            return;
10633        }
10634
10635        if matches!(self.mode, EditorMode::SingleLine { .. }) {
10636            cx.propagate();
10637            return;
10638        }
10639
10640        let Some(row_count) = self.visible_row_count() else {
10641            return;
10642        };
10643
10644        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
10645
10646        let autoscroll = if action.center_cursor {
10647            Autoscroll::center()
10648        } else {
10649            Autoscroll::fit()
10650        };
10651
10652        let text_layout_details = &self.text_layout_details(window);
10653        self.change_selections(Some(autoscroll), window, cx, |s| {
10654            s.move_with(|map, selection| {
10655                if !selection.is_empty() {
10656                    selection.goal = SelectionGoal::None;
10657                }
10658                let (cursor, goal) = movement::down_by_rows(
10659                    map,
10660                    selection.end,
10661                    row_count,
10662                    selection.goal,
10663                    false,
10664                    text_layout_details,
10665                );
10666                selection.collapse_to(cursor, goal);
10667            });
10668        });
10669    }
10670
10671    pub fn select_down(&mut self, _: &SelectDown, window: &mut Window, cx: &mut Context<Self>) {
10672        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
10673        let text_layout_details = &self.text_layout_details(window);
10674        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10675            s.move_heads_with(|map, head, goal| {
10676                movement::down(map, head, goal, false, text_layout_details)
10677            })
10678        });
10679    }
10680
10681    pub fn context_menu_first(
10682        &mut self,
10683        _: &ContextMenuFirst,
10684        _window: &mut Window,
10685        cx: &mut Context<Self>,
10686    ) {
10687        if let Some(context_menu) = self.context_menu.borrow_mut().as_mut() {
10688            context_menu.select_first(self.completion_provider.as_deref(), cx);
10689        }
10690    }
10691
10692    pub fn context_menu_prev(
10693        &mut self,
10694        _: &ContextMenuPrevious,
10695        _window: &mut Window,
10696        cx: &mut Context<Self>,
10697    ) {
10698        if let Some(context_menu) = self.context_menu.borrow_mut().as_mut() {
10699            context_menu.select_prev(self.completion_provider.as_deref(), cx);
10700        }
10701    }
10702
10703    pub fn context_menu_next(
10704        &mut self,
10705        _: &ContextMenuNext,
10706        _window: &mut Window,
10707        cx: &mut Context<Self>,
10708    ) {
10709        if let Some(context_menu) = self.context_menu.borrow_mut().as_mut() {
10710            context_menu.select_next(self.completion_provider.as_deref(), cx);
10711        }
10712    }
10713
10714    pub fn context_menu_last(
10715        &mut self,
10716        _: &ContextMenuLast,
10717        _window: &mut Window,
10718        cx: &mut Context<Self>,
10719    ) {
10720        if let Some(context_menu) = self.context_menu.borrow_mut().as_mut() {
10721            context_menu.select_last(self.completion_provider.as_deref(), cx);
10722        }
10723    }
10724
10725    pub fn move_to_previous_word_start(
10726        &mut self,
10727        _: &MoveToPreviousWordStart,
10728        window: &mut Window,
10729        cx: &mut Context<Self>,
10730    ) {
10731        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
10732        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10733            s.move_cursors_with(|map, head, _| {
10734                (
10735                    movement::previous_word_start(map, head),
10736                    SelectionGoal::None,
10737                )
10738            });
10739        })
10740    }
10741
10742    pub fn move_to_previous_subword_start(
10743        &mut self,
10744        _: &MoveToPreviousSubwordStart,
10745        window: &mut Window,
10746        cx: &mut Context<Self>,
10747    ) {
10748        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
10749        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10750            s.move_cursors_with(|map, head, _| {
10751                (
10752                    movement::previous_subword_start(map, head),
10753                    SelectionGoal::None,
10754                )
10755            });
10756        })
10757    }
10758
10759    pub fn select_to_previous_word_start(
10760        &mut self,
10761        _: &SelectToPreviousWordStart,
10762        window: &mut Window,
10763        cx: &mut Context<Self>,
10764    ) {
10765        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
10766        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10767            s.move_heads_with(|map, head, _| {
10768                (
10769                    movement::previous_word_start(map, head),
10770                    SelectionGoal::None,
10771                )
10772            });
10773        })
10774    }
10775
10776    pub fn select_to_previous_subword_start(
10777        &mut self,
10778        _: &SelectToPreviousSubwordStart,
10779        window: &mut Window,
10780        cx: &mut Context<Self>,
10781    ) {
10782        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
10783        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10784            s.move_heads_with(|map, head, _| {
10785                (
10786                    movement::previous_subword_start(map, head),
10787                    SelectionGoal::None,
10788                )
10789            });
10790        })
10791    }
10792
10793    pub fn delete_to_previous_word_start(
10794        &mut self,
10795        action: &DeleteToPreviousWordStart,
10796        window: &mut Window,
10797        cx: &mut Context<Self>,
10798    ) {
10799        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
10800        self.transact(window, cx, |this, window, cx| {
10801            this.select_autoclose_pair(window, cx);
10802            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10803                s.move_with(|map, selection| {
10804                    if selection.is_empty() {
10805                        let cursor = if action.ignore_newlines {
10806                            movement::previous_word_start(map, selection.head())
10807                        } else {
10808                            movement::previous_word_start_or_newline(map, selection.head())
10809                        };
10810                        selection.set_head(cursor, SelectionGoal::None);
10811                    }
10812                });
10813            });
10814            this.insert("", window, cx);
10815        });
10816    }
10817
10818    pub fn delete_to_previous_subword_start(
10819        &mut self,
10820        _: &DeleteToPreviousSubwordStart,
10821        window: &mut Window,
10822        cx: &mut Context<Self>,
10823    ) {
10824        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
10825        self.transact(window, cx, |this, window, cx| {
10826            this.select_autoclose_pair(window, cx);
10827            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10828                s.move_with(|map, selection| {
10829                    if selection.is_empty() {
10830                        let cursor = movement::previous_subword_start(map, selection.head());
10831                        selection.set_head(cursor, SelectionGoal::None);
10832                    }
10833                });
10834            });
10835            this.insert("", window, cx);
10836        });
10837    }
10838
10839    pub fn move_to_next_word_end(
10840        &mut self,
10841        _: &MoveToNextWordEnd,
10842        window: &mut Window,
10843        cx: &mut Context<Self>,
10844    ) {
10845        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
10846        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10847            s.move_cursors_with(|map, head, _| {
10848                (movement::next_word_end(map, head), SelectionGoal::None)
10849            });
10850        })
10851    }
10852
10853    pub fn move_to_next_subword_end(
10854        &mut self,
10855        _: &MoveToNextSubwordEnd,
10856        window: &mut Window,
10857        cx: &mut Context<Self>,
10858    ) {
10859        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
10860        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10861            s.move_cursors_with(|map, head, _| {
10862                (movement::next_subword_end(map, head), SelectionGoal::None)
10863            });
10864        })
10865    }
10866
10867    pub fn select_to_next_word_end(
10868        &mut self,
10869        _: &SelectToNextWordEnd,
10870        window: &mut Window,
10871        cx: &mut Context<Self>,
10872    ) {
10873        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
10874        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10875            s.move_heads_with(|map, head, _| {
10876                (movement::next_word_end(map, head), SelectionGoal::None)
10877            });
10878        })
10879    }
10880
10881    pub fn select_to_next_subword_end(
10882        &mut self,
10883        _: &SelectToNextSubwordEnd,
10884        window: &mut Window,
10885        cx: &mut Context<Self>,
10886    ) {
10887        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
10888        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10889            s.move_heads_with(|map, head, _| {
10890                (movement::next_subword_end(map, head), SelectionGoal::None)
10891            });
10892        })
10893    }
10894
10895    pub fn delete_to_next_word_end(
10896        &mut self,
10897        action: &DeleteToNextWordEnd,
10898        window: &mut Window,
10899        cx: &mut Context<Self>,
10900    ) {
10901        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
10902        self.transact(window, cx, |this, window, cx| {
10903            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10904                s.move_with(|map, selection| {
10905                    if selection.is_empty() {
10906                        let cursor = if action.ignore_newlines {
10907                            movement::next_word_end(map, selection.head())
10908                        } else {
10909                            movement::next_word_end_or_newline(map, selection.head())
10910                        };
10911                        selection.set_head(cursor, SelectionGoal::None);
10912                    }
10913                });
10914            });
10915            this.insert("", window, cx);
10916        });
10917    }
10918
10919    pub fn delete_to_next_subword_end(
10920        &mut self,
10921        _: &DeleteToNextSubwordEnd,
10922        window: &mut Window,
10923        cx: &mut Context<Self>,
10924    ) {
10925        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
10926        self.transact(window, cx, |this, window, cx| {
10927            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10928                s.move_with(|map, selection| {
10929                    if selection.is_empty() {
10930                        let cursor = movement::next_subword_end(map, selection.head());
10931                        selection.set_head(cursor, SelectionGoal::None);
10932                    }
10933                });
10934            });
10935            this.insert("", window, cx);
10936        });
10937    }
10938
10939    pub fn move_to_beginning_of_line(
10940        &mut self,
10941        action: &MoveToBeginningOfLine,
10942        window: &mut Window,
10943        cx: &mut Context<Self>,
10944    ) {
10945        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
10946        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10947            s.move_cursors_with(|map, head, _| {
10948                (
10949                    movement::indented_line_beginning(
10950                        map,
10951                        head,
10952                        action.stop_at_soft_wraps,
10953                        action.stop_at_indent,
10954                    ),
10955                    SelectionGoal::None,
10956                )
10957            });
10958        })
10959    }
10960
10961    pub fn select_to_beginning_of_line(
10962        &mut self,
10963        action: &SelectToBeginningOfLine,
10964        window: &mut Window,
10965        cx: &mut Context<Self>,
10966    ) {
10967        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
10968        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10969            s.move_heads_with(|map, head, _| {
10970                (
10971                    movement::indented_line_beginning(
10972                        map,
10973                        head,
10974                        action.stop_at_soft_wraps,
10975                        action.stop_at_indent,
10976                    ),
10977                    SelectionGoal::None,
10978                )
10979            });
10980        });
10981    }
10982
10983    pub fn delete_to_beginning_of_line(
10984        &mut self,
10985        action: &DeleteToBeginningOfLine,
10986        window: &mut Window,
10987        cx: &mut Context<Self>,
10988    ) {
10989        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
10990        self.transact(window, cx, |this, window, cx| {
10991            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10992                s.move_with(|_, selection| {
10993                    selection.reversed = true;
10994                });
10995            });
10996
10997            this.select_to_beginning_of_line(
10998                &SelectToBeginningOfLine {
10999                    stop_at_soft_wraps: false,
11000                    stop_at_indent: action.stop_at_indent,
11001                },
11002                window,
11003                cx,
11004            );
11005            this.backspace(&Backspace, window, cx);
11006        });
11007    }
11008
11009    pub fn move_to_end_of_line(
11010        &mut self,
11011        action: &MoveToEndOfLine,
11012        window: &mut Window,
11013        cx: &mut Context<Self>,
11014    ) {
11015        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11016        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11017            s.move_cursors_with(|map, head, _| {
11018                (
11019                    movement::line_end(map, head, action.stop_at_soft_wraps),
11020                    SelectionGoal::None,
11021                )
11022            });
11023        })
11024    }
11025
11026    pub fn select_to_end_of_line(
11027        &mut self,
11028        action: &SelectToEndOfLine,
11029        window: &mut Window,
11030        cx: &mut Context<Self>,
11031    ) {
11032        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11033        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11034            s.move_heads_with(|map, head, _| {
11035                (
11036                    movement::line_end(map, head, action.stop_at_soft_wraps),
11037                    SelectionGoal::None,
11038                )
11039            });
11040        })
11041    }
11042
11043    pub fn delete_to_end_of_line(
11044        &mut self,
11045        _: &DeleteToEndOfLine,
11046        window: &mut Window,
11047        cx: &mut Context<Self>,
11048    ) {
11049        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
11050        self.transact(window, cx, |this, window, cx| {
11051            this.select_to_end_of_line(
11052                &SelectToEndOfLine {
11053                    stop_at_soft_wraps: false,
11054                },
11055                window,
11056                cx,
11057            );
11058            this.delete(&Delete, window, cx);
11059        });
11060    }
11061
11062    pub fn cut_to_end_of_line(
11063        &mut self,
11064        _: &CutToEndOfLine,
11065        window: &mut Window,
11066        cx: &mut Context<Self>,
11067    ) {
11068        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
11069        self.transact(window, cx, |this, window, cx| {
11070            this.select_to_end_of_line(
11071                &SelectToEndOfLine {
11072                    stop_at_soft_wraps: false,
11073                },
11074                window,
11075                cx,
11076            );
11077            this.cut(&Cut, window, cx);
11078        });
11079    }
11080
11081    pub fn move_to_start_of_paragraph(
11082        &mut self,
11083        _: &MoveToStartOfParagraph,
11084        window: &mut Window,
11085        cx: &mut Context<Self>,
11086    ) {
11087        if matches!(self.mode, EditorMode::SingleLine { .. }) {
11088            cx.propagate();
11089            return;
11090        }
11091        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11092        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11093            s.move_with(|map, selection| {
11094                selection.collapse_to(
11095                    movement::start_of_paragraph(map, selection.head(), 1),
11096                    SelectionGoal::None,
11097                )
11098            });
11099        })
11100    }
11101
11102    pub fn move_to_end_of_paragraph(
11103        &mut self,
11104        _: &MoveToEndOfParagraph,
11105        window: &mut Window,
11106        cx: &mut Context<Self>,
11107    ) {
11108        if matches!(self.mode, EditorMode::SingleLine { .. }) {
11109            cx.propagate();
11110            return;
11111        }
11112        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11113        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11114            s.move_with(|map, selection| {
11115                selection.collapse_to(
11116                    movement::end_of_paragraph(map, selection.head(), 1),
11117                    SelectionGoal::None,
11118                )
11119            });
11120        })
11121    }
11122
11123    pub fn select_to_start_of_paragraph(
11124        &mut self,
11125        _: &SelectToStartOfParagraph,
11126        window: &mut Window,
11127        cx: &mut Context<Self>,
11128    ) {
11129        if matches!(self.mode, EditorMode::SingleLine { .. }) {
11130            cx.propagate();
11131            return;
11132        }
11133        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11134        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11135            s.move_heads_with(|map, head, _| {
11136                (
11137                    movement::start_of_paragraph(map, head, 1),
11138                    SelectionGoal::None,
11139                )
11140            });
11141        })
11142    }
11143
11144    pub fn select_to_end_of_paragraph(
11145        &mut self,
11146        _: &SelectToEndOfParagraph,
11147        window: &mut Window,
11148        cx: &mut Context<Self>,
11149    ) {
11150        if matches!(self.mode, EditorMode::SingleLine { .. }) {
11151            cx.propagate();
11152            return;
11153        }
11154        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11155        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11156            s.move_heads_with(|map, head, _| {
11157                (
11158                    movement::end_of_paragraph(map, head, 1),
11159                    SelectionGoal::None,
11160                )
11161            });
11162        })
11163    }
11164
11165    pub fn move_to_start_of_excerpt(
11166        &mut self,
11167        _: &MoveToStartOfExcerpt,
11168        window: &mut Window,
11169        cx: &mut Context<Self>,
11170    ) {
11171        if matches!(self.mode, EditorMode::SingleLine { .. }) {
11172            cx.propagate();
11173            return;
11174        }
11175        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11176        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11177            s.move_with(|map, selection| {
11178                selection.collapse_to(
11179                    movement::start_of_excerpt(
11180                        map,
11181                        selection.head(),
11182                        workspace::searchable::Direction::Prev,
11183                    ),
11184                    SelectionGoal::None,
11185                )
11186            });
11187        })
11188    }
11189
11190    pub fn move_to_start_of_next_excerpt(
11191        &mut self,
11192        _: &MoveToStartOfNextExcerpt,
11193        window: &mut Window,
11194        cx: &mut Context<Self>,
11195    ) {
11196        if matches!(self.mode, EditorMode::SingleLine { .. }) {
11197            cx.propagate();
11198            return;
11199        }
11200
11201        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11202            s.move_with(|map, selection| {
11203                selection.collapse_to(
11204                    movement::start_of_excerpt(
11205                        map,
11206                        selection.head(),
11207                        workspace::searchable::Direction::Next,
11208                    ),
11209                    SelectionGoal::None,
11210                )
11211            });
11212        })
11213    }
11214
11215    pub fn move_to_end_of_excerpt(
11216        &mut self,
11217        _: &MoveToEndOfExcerpt,
11218        window: &mut Window,
11219        cx: &mut Context<Self>,
11220    ) {
11221        if matches!(self.mode, EditorMode::SingleLine { .. }) {
11222            cx.propagate();
11223            return;
11224        }
11225        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11226        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11227            s.move_with(|map, selection| {
11228                selection.collapse_to(
11229                    movement::end_of_excerpt(
11230                        map,
11231                        selection.head(),
11232                        workspace::searchable::Direction::Next,
11233                    ),
11234                    SelectionGoal::None,
11235                )
11236            });
11237        })
11238    }
11239
11240    pub fn move_to_end_of_previous_excerpt(
11241        &mut self,
11242        _: &MoveToEndOfPreviousExcerpt,
11243        window: &mut Window,
11244        cx: &mut Context<Self>,
11245    ) {
11246        if matches!(self.mode, EditorMode::SingleLine { .. }) {
11247            cx.propagate();
11248            return;
11249        }
11250        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11251        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11252            s.move_with(|map, selection| {
11253                selection.collapse_to(
11254                    movement::end_of_excerpt(
11255                        map,
11256                        selection.head(),
11257                        workspace::searchable::Direction::Prev,
11258                    ),
11259                    SelectionGoal::None,
11260                )
11261            });
11262        })
11263    }
11264
11265    pub fn select_to_start_of_excerpt(
11266        &mut self,
11267        _: &SelectToStartOfExcerpt,
11268        window: &mut Window,
11269        cx: &mut Context<Self>,
11270    ) {
11271        if matches!(self.mode, EditorMode::SingleLine { .. }) {
11272            cx.propagate();
11273            return;
11274        }
11275        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11276        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11277            s.move_heads_with(|map, head, _| {
11278                (
11279                    movement::start_of_excerpt(map, head, workspace::searchable::Direction::Prev),
11280                    SelectionGoal::None,
11281                )
11282            });
11283        })
11284    }
11285
11286    pub fn select_to_start_of_next_excerpt(
11287        &mut self,
11288        _: &SelectToStartOfNextExcerpt,
11289        window: &mut Window,
11290        cx: &mut Context<Self>,
11291    ) {
11292        if matches!(self.mode, EditorMode::SingleLine { .. }) {
11293            cx.propagate();
11294            return;
11295        }
11296        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11297        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11298            s.move_heads_with(|map, head, _| {
11299                (
11300                    movement::start_of_excerpt(map, head, workspace::searchable::Direction::Next),
11301                    SelectionGoal::None,
11302                )
11303            });
11304        })
11305    }
11306
11307    pub fn select_to_end_of_excerpt(
11308        &mut self,
11309        _: &SelectToEndOfExcerpt,
11310        window: &mut Window,
11311        cx: &mut Context<Self>,
11312    ) {
11313        if matches!(self.mode, EditorMode::SingleLine { .. }) {
11314            cx.propagate();
11315            return;
11316        }
11317        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11318        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11319            s.move_heads_with(|map, head, _| {
11320                (
11321                    movement::end_of_excerpt(map, head, workspace::searchable::Direction::Next),
11322                    SelectionGoal::None,
11323                )
11324            });
11325        })
11326    }
11327
11328    pub fn select_to_end_of_previous_excerpt(
11329        &mut self,
11330        _: &SelectToEndOfPreviousExcerpt,
11331        window: &mut Window,
11332        cx: &mut Context<Self>,
11333    ) {
11334        if matches!(self.mode, EditorMode::SingleLine { .. }) {
11335            cx.propagate();
11336            return;
11337        }
11338        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11339        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11340            s.move_heads_with(|map, head, _| {
11341                (
11342                    movement::end_of_excerpt(map, head, workspace::searchable::Direction::Prev),
11343                    SelectionGoal::None,
11344                )
11345            });
11346        })
11347    }
11348
11349    pub fn move_to_beginning(
11350        &mut self,
11351        _: &MoveToBeginning,
11352        window: &mut Window,
11353        cx: &mut Context<Self>,
11354    ) {
11355        if matches!(self.mode, EditorMode::SingleLine { .. }) {
11356            cx.propagate();
11357            return;
11358        }
11359        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11360        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11361            s.select_ranges(vec![0..0]);
11362        });
11363    }
11364
11365    pub fn select_to_beginning(
11366        &mut self,
11367        _: &SelectToBeginning,
11368        window: &mut Window,
11369        cx: &mut Context<Self>,
11370    ) {
11371        let mut selection = self.selections.last::<Point>(cx);
11372        selection.set_head(Point::zero(), SelectionGoal::None);
11373        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11374        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11375            s.select(vec![selection]);
11376        });
11377    }
11378
11379    pub fn move_to_end(&mut self, _: &MoveToEnd, window: &mut Window, cx: &mut Context<Self>) {
11380        if matches!(self.mode, EditorMode::SingleLine { .. }) {
11381            cx.propagate();
11382            return;
11383        }
11384        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11385        let cursor = self.buffer.read(cx).read(cx).len();
11386        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11387            s.select_ranges(vec![cursor..cursor])
11388        });
11389    }
11390
11391    pub fn set_nav_history(&mut self, nav_history: Option<ItemNavHistory>) {
11392        self.nav_history = nav_history;
11393    }
11394
11395    pub fn nav_history(&self) -> Option<&ItemNavHistory> {
11396        self.nav_history.as_ref()
11397    }
11398
11399    pub fn create_nav_history_entry(&mut self, cx: &mut Context<Self>) {
11400        self.push_to_nav_history(self.selections.newest_anchor().head(), None, false, cx);
11401    }
11402
11403    fn push_to_nav_history(
11404        &mut self,
11405        cursor_anchor: Anchor,
11406        new_position: Option<Point>,
11407        is_deactivate: bool,
11408        cx: &mut Context<Self>,
11409    ) {
11410        if let Some(nav_history) = self.nav_history.as_mut() {
11411            let buffer = self.buffer.read(cx).read(cx);
11412            let cursor_position = cursor_anchor.to_point(&buffer);
11413            let scroll_state = self.scroll_manager.anchor();
11414            let scroll_top_row = scroll_state.top_row(&buffer);
11415            drop(buffer);
11416
11417            if let Some(new_position) = new_position {
11418                let row_delta = (new_position.row as i64 - cursor_position.row as i64).abs();
11419                if row_delta < MIN_NAVIGATION_HISTORY_ROW_DELTA {
11420                    return;
11421                }
11422            }
11423
11424            nav_history.push(
11425                Some(NavigationData {
11426                    cursor_anchor,
11427                    cursor_position,
11428                    scroll_anchor: scroll_state,
11429                    scroll_top_row,
11430                }),
11431                cx,
11432            );
11433            cx.emit(EditorEvent::PushedToNavHistory {
11434                anchor: cursor_anchor,
11435                is_deactivate,
11436            })
11437        }
11438    }
11439
11440    pub fn select_to_end(&mut self, _: &SelectToEnd, window: &mut Window, cx: &mut Context<Self>) {
11441        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11442        let buffer = self.buffer.read(cx).snapshot(cx);
11443        let mut selection = self.selections.first::<usize>(cx);
11444        selection.set_head(buffer.len(), SelectionGoal::None);
11445        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11446            s.select(vec![selection]);
11447        });
11448    }
11449
11450    pub fn select_all(&mut self, _: &SelectAll, window: &mut Window, cx: &mut Context<Self>) {
11451        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11452        let end = self.buffer.read(cx).read(cx).len();
11453        self.change_selections(None, window, cx, |s| {
11454            s.select_ranges(vec![0..end]);
11455        });
11456    }
11457
11458    pub fn select_line(&mut self, _: &SelectLine, window: &mut Window, cx: &mut Context<Self>) {
11459        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11460        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
11461        let mut selections = self.selections.all::<Point>(cx);
11462        let max_point = display_map.buffer_snapshot.max_point();
11463        for selection in &mut selections {
11464            let rows = selection.spanned_rows(true, &display_map);
11465            selection.start = Point::new(rows.start.0, 0);
11466            selection.end = cmp::min(max_point, Point::new(rows.end.0, 0));
11467            selection.reversed = false;
11468        }
11469        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11470            s.select(selections);
11471        });
11472    }
11473
11474    pub fn split_selection_into_lines(
11475        &mut self,
11476        _: &SplitSelectionIntoLines,
11477        window: &mut Window,
11478        cx: &mut Context<Self>,
11479    ) {
11480        let selections = self
11481            .selections
11482            .all::<Point>(cx)
11483            .into_iter()
11484            .map(|selection| selection.start..selection.end)
11485            .collect::<Vec<_>>();
11486        self.unfold_ranges(&selections, true, true, cx);
11487
11488        let mut new_selection_ranges = Vec::new();
11489        {
11490            let buffer = self.buffer.read(cx).read(cx);
11491            for selection in selections {
11492                for row in selection.start.row..selection.end.row {
11493                    let cursor = Point::new(row, buffer.line_len(MultiBufferRow(row)));
11494                    new_selection_ranges.push(cursor..cursor);
11495                }
11496
11497                let is_multiline_selection = selection.start.row != selection.end.row;
11498                // Don't insert last one if it's a multi-line selection ending at the start of a line,
11499                // so this action feels more ergonomic when paired with other selection operations
11500                let should_skip_last = is_multiline_selection && selection.end.column == 0;
11501                if !should_skip_last {
11502                    new_selection_ranges.push(selection.end..selection.end);
11503                }
11504            }
11505        }
11506        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11507            s.select_ranges(new_selection_ranges);
11508        });
11509    }
11510
11511    pub fn add_selection_above(
11512        &mut self,
11513        _: &AddSelectionAbove,
11514        window: &mut Window,
11515        cx: &mut Context<Self>,
11516    ) {
11517        self.add_selection(true, window, cx);
11518    }
11519
11520    pub fn add_selection_below(
11521        &mut self,
11522        _: &AddSelectionBelow,
11523        window: &mut Window,
11524        cx: &mut Context<Self>,
11525    ) {
11526        self.add_selection(false, window, cx);
11527    }
11528
11529    fn add_selection(&mut self, above: bool, window: &mut Window, cx: &mut Context<Self>) {
11530        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11531
11532        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
11533        let mut selections = self.selections.all::<Point>(cx);
11534        let text_layout_details = self.text_layout_details(window);
11535        let mut state = self.add_selections_state.take().unwrap_or_else(|| {
11536            let oldest_selection = selections.iter().min_by_key(|s| s.id).unwrap().clone();
11537            let range = oldest_selection.display_range(&display_map).sorted();
11538
11539            let start_x = display_map.x_for_display_point(range.start, &text_layout_details);
11540            let end_x = display_map.x_for_display_point(range.end, &text_layout_details);
11541            let positions = start_x.min(end_x)..start_x.max(end_x);
11542
11543            selections.clear();
11544            let mut stack = Vec::new();
11545            for row in range.start.row().0..=range.end.row().0 {
11546                if let Some(selection) = self.selections.build_columnar_selection(
11547                    &display_map,
11548                    DisplayRow(row),
11549                    &positions,
11550                    oldest_selection.reversed,
11551                    &text_layout_details,
11552                ) {
11553                    stack.push(selection.id);
11554                    selections.push(selection);
11555                }
11556            }
11557
11558            if above {
11559                stack.reverse();
11560            }
11561
11562            AddSelectionsState { above, stack }
11563        });
11564
11565        let last_added_selection = *state.stack.last().unwrap();
11566        let mut new_selections = Vec::new();
11567        if above == state.above {
11568            let end_row = if above {
11569                DisplayRow(0)
11570            } else {
11571                display_map.max_point().row()
11572            };
11573
11574            'outer: for selection in selections {
11575                if selection.id == last_added_selection {
11576                    let range = selection.display_range(&display_map).sorted();
11577                    debug_assert_eq!(range.start.row(), range.end.row());
11578                    let mut row = range.start.row();
11579                    let positions =
11580                        if let SelectionGoal::HorizontalRange { start, end } = selection.goal {
11581                            px(start)..px(end)
11582                        } else {
11583                            let start_x =
11584                                display_map.x_for_display_point(range.start, &text_layout_details);
11585                            let end_x =
11586                                display_map.x_for_display_point(range.end, &text_layout_details);
11587                            start_x.min(end_x)..start_x.max(end_x)
11588                        };
11589
11590                    while row != end_row {
11591                        if above {
11592                            row.0 -= 1;
11593                        } else {
11594                            row.0 += 1;
11595                        }
11596
11597                        if let Some(new_selection) = self.selections.build_columnar_selection(
11598                            &display_map,
11599                            row,
11600                            &positions,
11601                            selection.reversed,
11602                            &text_layout_details,
11603                        ) {
11604                            state.stack.push(new_selection.id);
11605                            if above {
11606                                new_selections.push(new_selection);
11607                                new_selections.push(selection);
11608                            } else {
11609                                new_selections.push(selection);
11610                                new_selections.push(new_selection);
11611                            }
11612
11613                            continue 'outer;
11614                        }
11615                    }
11616                }
11617
11618                new_selections.push(selection);
11619            }
11620        } else {
11621            new_selections = selections;
11622            new_selections.retain(|s| s.id != last_added_selection);
11623            state.stack.pop();
11624        }
11625
11626        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11627            s.select(new_selections);
11628        });
11629        if state.stack.len() > 1 {
11630            self.add_selections_state = Some(state);
11631        }
11632    }
11633
11634    pub fn select_next_match_internal(
11635        &mut self,
11636        display_map: &DisplaySnapshot,
11637        replace_newest: bool,
11638        autoscroll: Option<Autoscroll>,
11639        window: &mut Window,
11640        cx: &mut Context<Self>,
11641    ) -> Result<()> {
11642        fn select_next_match_ranges(
11643            this: &mut Editor,
11644            range: Range<usize>,
11645            replace_newest: bool,
11646            auto_scroll: Option<Autoscroll>,
11647            window: &mut Window,
11648            cx: &mut Context<Editor>,
11649        ) {
11650            this.unfold_ranges(&[range.clone()], false, auto_scroll.is_some(), cx);
11651            this.change_selections(auto_scroll, window, cx, |s| {
11652                if replace_newest {
11653                    s.delete(s.newest_anchor().id);
11654                }
11655                s.insert_range(range.clone());
11656            });
11657        }
11658
11659        let buffer = &display_map.buffer_snapshot;
11660        let mut selections = self.selections.all::<usize>(cx);
11661        if let Some(mut select_next_state) = self.select_next_state.take() {
11662            let query = &select_next_state.query;
11663            if !select_next_state.done {
11664                let first_selection = selections.iter().min_by_key(|s| s.id).unwrap();
11665                let last_selection = selections.iter().max_by_key(|s| s.id).unwrap();
11666                let mut next_selected_range = None;
11667
11668                let bytes_after_last_selection =
11669                    buffer.bytes_in_range(last_selection.end..buffer.len());
11670                let bytes_before_first_selection = buffer.bytes_in_range(0..first_selection.start);
11671                let query_matches = query
11672                    .stream_find_iter(bytes_after_last_selection)
11673                    .map(|result| (last_selection.end, result))
11674                    .chain(
11675                        query
11676                            .stream_find_iter(bytes_before_first_selection)
11677                            .map(|result| (0, result)),
11678                    );
11679
11680                for (start_offset, query_match) in query_matches {
11681                    let query_match = query_match.unwrap(); // can only fail due to I/O
11682                    let offset_range =
11683                        start_offset + query_match.start()..start_offset + query_match.end();
11684                    let display_range = offset_range.start.to_display_point(display_map)
11685                        ..offset_range.end.to_display_point(display_map);
11686
11687                    if !select_next_state.wordwise
11688                        || (!movement::is_inside_word(display_map, display_range.start)
11689                            && !movement::is_inside_word(display_map, display_range.end))
11690                    {
11691                        // TODO: This is n^2, because we might check all the selections
11692                        if !selections
11693                            .iter()
11694                            .any(|selection| selection.range().overlaps(&offset_range))
11695                        {
11696                            next_selected_range = Some(offset_range);
11697                            break;
11698                        }
11699                    }
11700                }
11701
11702                if let Some(next_selected_range) = next_selected_range {
11703                    select_next_match_ranges(
11704                        self,
11705                        next_selected_range,
11706                        replace_newest,
11707                        autoscroll,
11708                        window,
11709                        cx,
11710                    );
11711                } else {
11712                    select_next_state.done = true;
11713                }
11714            }
11715
11716            self.select_next_state = Some(select_next_state);
11717        } else {
11718            let mut only_carets = true;
11719            let mut same_text_selected = true;
11720            let mut selected_text = None;
11721
11722            let mut selections_iter = selections.iter().peekable();
11723            while let Some(selection) = selections_iter.next() {
11724                if selection.start != selection.end {
11725                    only_carets = false;
11726                }
11727
11728                if same_text_selected {
11729                    if selected_text.is_none() {
11730                        selected_text =
11731                            Some(buffer.text_for_range(selection.range()).collect::<String>());
11732                    }
11733
11734                    if let Some(next_selection) = selections_iter.peek() {
11735                        if next_selection.range().len() == selection.range().len() {
11736                            let next_selected_text = buffer
11737                                .text_for_range(next_selection.range())
11738                                .collect::<String>();
11739                            if Some(next_selected_text) != selected_text {
11740                                same_text_selected = false;
11741                                selected_text = None;
11742                            }
11743                        } else {
11744                            same_text_selected = false;
11745                            selected_text = None;
11746                        }
11747                    }
11748                }
11749            }
11750
11751            if only_carets {
11752                for selection in &mut selections {
11753                    let word_range = movement::surrounding_word(
11754                        display_map,
11755                        selection.start.to_display_point(display_map),
11756                    );
11757                    selection.start = word_range.start.to_offset(display_map, Bias::Left);
11758                    selection.end = word_range.end.to_offset(display_map, Bias::Left);
11759                    selection.goal = SelectionGoal::None;
11760                    selection.reversed = false;
11761                    select_next_match_ranges(
11762                        self,
11763                        selection.start..selection.end,
11764                        replace_newest,
11765                        autoscroll,
11766                        window,
11767                        cx,
11768                    );
11769                }
11770
11771                if selections.len() == 1 {
11772                    let selection = selections
11773                        .last()
11774                        .expect("ensured that there's only one selection");
11775                    let query = buffer
11776                        .text_for_range(selection.start..selection.end)
11777                        .collect::<String>();
11778                    let is_empty = query.is_empty();
11779                    let select_state = SelectNextState {
11780                        query: AhoCorasick::new(&[query])?,
11781                        wordwise: true,
11782                        done: is_empty,
11783                    };
11784                    self.select_next_state = Some(select_state);
11785                } else {
11786                    self.select_next_state = None;
11787                }
11788            } else if let Some(selected_text) = selected_text {
11789                self.select_next_state = Some(SelectNextState {
11790                    query: AhoCorasick::new(&[selected_text])?,
11791                    wordwise: false,
11792                    done: false,
11793                });
11794                self.select_next_match_internal(
11795                    display_map,
11796                    replace_newest,
11797                    autoscroll,
11798                    window,
11799                    cx,
11800                )?;
11801            }
11802        }
11803        Ok(())
11804    }
11805
11806    pub fn select_all_matches(
11807        &mut self,
11808        _action: &SelectAllMatches,
11809        window: &mut Window,
11810        cx: &mut Context<Self>,
11811    ) -> Result<()> {
11812        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11813
11814        self.push_to_selection_history();
11815        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
11816
11817        self.select_next_match_internal(&display_map, false, None, window, cx)?;
11818        let Some(select_next_state) = self.select_next_state.as_mut() else {
11819            return Ok(());
11820        };
11821        if select_next_state.done {
11822            return Ok(());
11823        }
11824
11825        let mut new_selections = Vec::new();
11826
11827        let reversed = self.selections.oldest::<usize>(cx).reversed;
11828        let buffer = &display_map.buffer_snapshot;
11829        let query_matches = select_next_state
11830            .query
11831            .stream_find_iter(buffer.bytes_in_range(0..buffer.len()));
11832
11833        for query_match in query_matches.into_iter() {
11834            let query_match = query_match.context("query match for select all action")?; // can only fail due to I/O
11835            let offset_range = if reversed {
11836                query_match.end()..query_match.start()
11837            } else {
11838                query_match.start()..query_match.end()
11839            };
11840            let display_range = offset_range.start.to_display_point(&display_map)
11841                ..offset_range.end.to_display_point(&display_map);
11842
11843            if !select_next_state.wordwise
11844                || (!movement::is_inside_word(&display_map, display_range.start)
11845                    && !movement::is_inside_word(&display_map, display_range.end))
11846            {
11847                new_selections.push(offset_range.start..offset_range.end);
11848            }
11849        }
11850
11851        select_next_state.done = true;
11852        self.unfold_ranges(&new_selections.clone(), false, false, cx);
11853        self.change_selections(None, window, cx, |selections| {
11854            selections.select_ranges(new_selections)
11855        });
11856
11857        Ok(())
11858    }
11859
11860    pub fn select_next(
11861        &mut self,
11862        action: &SelectNext,
11863        window: &mut Window,
11864        cx: &mut Context<Self>,
11865    ) -> Result<()> {
11866        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11867        self.push_to_selection_history();
11868        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
11869        self.select_next_match_internal(
11870            &display_map,
11871            action.replace_newest,
11872            Some(Autoscroll::newest()),
11873            window,
11874            cx,
11875        )?;
11876        Ok(())
11877    }
11878
11879    pub fn select_previous(
11880        &mut self,
11881        action: &SelectPrevious,
11882        window: &mut Window,
11883        cx: &mut Context<Self>,
11884    ) -> Result<()> {
11885        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11886        self.push_to_selection_history();
11887        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
11888        let buffer = &display_map.buffer_snapshot;
11889        let mut selections = self.selections.all::<usize>(cx);
11890        if let Some(mut select_prev_state) = self.select_prev_state.take() {
11891            let query = &select_prev_state.query;
11892            if !select_prev_state.done {
11893                let first_selection = selections.iter().min_by_key(|s| s.id).unwrap();
11894                let last_selection = selections.iter().max_by_key(|s| s.id).unwrap();
11895                let mut next_selected_range = None;
11896                // When we're iterating matches backwards, the oldest match will actually be the furthest one in the buffer.
11897                let bytes_before_last_selection =
11898                    buffer.reversed_bytes_in_range(0..last_selection.start);
11899                let bytes_after_first_selection =
11900                    buffer.reversed_bytes_in_range(first_selection.end..buffer.len());
11901                let query_matches = query
11902                    .stream_find_iter(bytes_before_last_selection)
11903                    .map(|result| (last_selection.start, result))
11904                    .chain(
11905                        query
11906                            .stream_find_iter(bytes_after_first_selection)
11907                            .map(|result| (buffer.len(), result)),
11908                    );
11909                for (end_offset, query_match) in query_matches {
11910                    let query_match = query_match.unwrap(); // can only fail due to I/O
11911                    let offset_range =
11912                        end_offset - query_match.end()..end_offset - query_match.start();
11913                    let display_range = offset_range.start.to_display_point(&display_map)
11914                        ..offset_range.end.to_display_point(&display_map);
11915
11916                    if !select_prev_state.wordwise
11917                        || (!movement::is_inside_word(&display_map, display_range.start)
11918                            && !movement::is_inside_word(&display_map, display_range.end))
11919                    {
11920                        next_selected_range = Some(offset_range);
11921                        break;
11922                    }
11923                }
11924
11925                if let Some(next_selected_range) = next_selected_range {
11926                    self.unfold_ranges(&[next_selected_range.clone()], false, true, cx);
11927                    self.change_selections(Some(Autoscroll::newest()), window, cx, |s| {
11928                        if action.replace_newest {
11929                            s.delete(s.newest_anchor().id);
11930                        }
11931                        s.insert_range(next_selected_range);
11932                    });
11933                } else {
11934                    select_prev_state.done = true;
11935                }
11936            }
11937
11938            self.select_prev_state = Some(select_prev_state);
11939        } else {
11940            let mut only_carets = true;
11941            let mut same_text_selected = true;
11942            let mut selected_text = None;
11943
11944            let mut selections_iter = selections.iter().peekable();
11945            while let Some(selection) = selections_iter.next() {
11946                if selection.start != selection.end {
11947                    only_carets = false;
11948                }
11949
11950                if same_text_selected {
11951                    if selected_text.is_none() {
11952                        selected_text =
11953                            Some(buffer.text_for_range(selection.range()).collect::<String>());
11954                    }
11955
11956                    if let Some(next_selection) = selections_iter.peek() {
11957                        if next_selection.range().len() == selection.range().len() {
11958                            let next_selected_text = buffer
11959                                .text_for_range(next_selection.range())
11960                                .collect::<String>();
11961                            if Some(next_selected_text) != selected_text {
11962                                same_text_selected = false;
11963                                selected_text = None;
11964                            }
11965                        } else {
11966                            same_text_selected = false;
11967                            selected_text = None;
11968                        }
11969                    }
11970                }
11971            }
11972
11973            if only_carets {
11974                for selection in &mut selections {
11975                    let word_range = movement::surrounding_word(
11976                        &display_map,
11977                        selection.start.to_display_point(&display_map),
11978                    );
11979                    selection.start = word_range.start.to_offset(&display_map, Bias::Left);
11980                    selection.end = word_range.end.to_offset(&display_map, Bias::Left);
11981                    selection.goal = SelectionGoal::None;
11982                    selection.reversed = false;
11983                }
11984                if selections.len() == 1 {
11985                    let selection = selections
11986                        .last()
11987                        .expect("ensured that there's only one selection");
11988                    let query = buffer
11989                        .text_for_range(selection.start..selection.end)
11990                        .collect::<String>();
11991                    let is_empty = query.is_empty();
11992                    let select_state = SelectNextState {
11993                        query: AhoCorasick::new(&[query.chars().rev().collect::<String>()])?,
11994                        wordwise: true,
11995                        done: is_empty,
11996                    };
11997                    self.select_prev_state = Some(select_state);
11998                } else {
11999                    self.select_prev_state = None;
12000                }
12001
12002                self.unfold_ranges(
12003                    &selections.iter().map(|s| s.range()).collect::<Vec<_>>(),
12004                    false,
12005                    true,
12006                    cx,
12007                );
12008                self.change_selections(Some(Autoscroll::newest()), window, cx, |s| {
12009                    s.select(selections);
12010                });
12011            } else if let Some(selected_text) = selected_text {
12012                self.select_prev_state = Some(SelectNextState {
12013                    query: AhoCorasick::new(&[selected_text.chars().rev().collect::<String>()])?,
12014                    wordwise: false,
12015                    done: false,
12016                });
12017                self.select_previous(action, window, cx)?;
12018            }
12019        }
12020        Ok(())
12021    }
12022
12023    pub fn find_next_match(
12024        &mut self,
12025        _: &FindNextMatch,
12026        window: &mut Window,
12027        cx: &mut Context<Self>,
12028    ) -> Result<()> {
12029        let selections = self.selections.disjoint_anchors();
12030        match selections.first() {
12031            Some(first) if selections.len() >= 2 => {
12032                self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
12033                    s.select_ranges([first.range()]);
12034                });
12035            }
12036            _ => self.select_next(
12037                &SelectNext {
12038                    replace_newest: true,
12039                },
12040                window,
12041                cx,
12042            )?,
12043        }
12044        Ok(())
12045    }
12046
12047    pub fn find_previous_match(
12048        &mut self,
12049        _: &FindPreviousMatch,
12050        window: &mut Window,
12051        cx: &mut Context<Self>,
12052    ) -> Result<()> {
12053        let selections = self.selections.disjoint_anchors();
12054        match selections.last() {
12055            Some(last) if selections.len() >= 2 => {
12056                self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
12057                    s.select_ranges([last.range()]);
12058                });
12059            }
12060            _ => self.select_previous(
12061                &SelectPrevious {
12062                    replace_newest: true,
12063                },
12064                window,
12065                cx,
12066            )?,
12067        }
12068        Ok(())
12069    }
12070
12071    pub fn toggle_comments(
12072        &mut self,
12073        action: &ToggleComments,
12074        window: &mut Window,
12075        cx: &mut Context<Self>,
12076    ) {
12077        if self.read_only(cx) {
12078            return;
12079        }
12080        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
12081        let text_layout_details = &self.text_layout_details(window);
12082        self.transact(window, cx, |this, window, cx| {
12083            let mut selections = this.selections.all::<MultiBufferPoint>(cx);
12084            let mut edits = Vec::new();
12085            let mut selection_edit_ranges = Vec::new();
12086            let mut last_toggled_row = None;
12087            let snapshot = this.buffer.read(cx).read(cx);
12088            let empty_str: Arc<str> = Arc::default();
12089            let mut suffixes_inserted = Vec::new();
12090            let ignore_indent = action.ignore_indent;
12091
12092            fn comment_prefix_range(
12093                snapshot: &MultiBufferSnapshot,
12094                row: MultiBufferRow,
12095                comment_prefix: &str,
12096                comment_prefix_whitespace: &str,
12097                ignore_indent: bool,
12098            ) -> Range<Point> {
12099                let indent_size = if ignore_indent {
12100                    0
12101                } else {
12102                    snapshot.indent_size_for_line(row).len
12103                };
12104
12105                let start = Point::new(row.0, indent_size);
12106
12107                let mut line_bytes = snapshot
12108                    .bytes_in_range(start..snapshot.max_point())
12109                    .flatten()
12110                    .copied();
12111
12112                // If this line currently begins with the line comment prefix, then record
12113                // the range containing the prefix.
12114                if line_bytes
12115                    .by_ref()
12116                    .take(comment_prefix.len())
12117                    .eq(comment_prefix.bytes())
12118                {
12119                    // Include any whitespace that matches the comment prefix.
12120                    let matching_whitespace_len = line_bytes
12121                        .zip(comment_prefix_whitespace.bytes())
12122                        .take_while(|(a, b)| a == b)
12123                        .count() as u32;
12124                    let end = Point::new(
12125                        start.row,
12126                        start.column + comment_prefix.len() as u32 + matching_whitespace_len,
12127                    );
12128                    start..end
12129                } else {
12130                    start..start
12131                }
12132            }
12133
12134            fn comment_suffix_range(
12135                snapshot: &MultiBufferSnapshot,
12136                row: MultiBufferRow,
12137                comment_suffix: &str,
12138                comment_suffix_has_leading_space: bool,
12139            ) -> Range<Point> {
12140                let end = Point::new(row.0, snapshot.line_len(row));
12141                let suffix_start_column = end.column.saturating_sub(comment_suffix.len() as u32);
12142
12143                let mut line_end_bytes = snapshot
12144                    .bytes_in_range(Point::new(end.row, suffix_start_column.saturating_sub(1))..end)
12145                    .flatten()
12146                    .copied();
12147
12148                let leading_space_len = if suffix_start_column > 0
12149                    && line_end_bytes.next() == Some(b' ')
12150                    && comment_suffix_has_leading_space
12151                {
12152                    1
12153                } else {
12154                    0
12155                };
12156
12157                // If this line currently begins with the line comment prefix, then record
12158                // the range containing the prefix.
12159                if line_end_bytes.by_ref().eq(comment_suffix.bytes()) {
12160                    let start = Point::new(end.row, suffix_start_column - leading_space_len);
12161                    start..end
12162                } else {
12163                    end..end
12164                }
12165            }
12166
12167            // TODO: Handle selections that cross excerpts
12168            for selection in &mut selections {
12169                let start_column = snapshot
12170                    .indent_size_for_line(MultiBufferRow(selection.start.row))
12171                    .len;
12172                let language = if let Some(language) =
12173                    snapshot.language_scope_at(Point::new(selection.start.row, start_column))
12174                {
12175                    language
12176                } else {
12177                    continue;
12178                };
12179
12180                selection_edit_ranges.clear();
12181
12182                // If multiple selections contain a given row, avoid processing that
12183                // row more than once.
12184                let mut start_row = MultiBufferRow(selection.start.row);
12185                if last_toggled_row == Some(start_row) {
12186                    start_row = start_row.next_row();
12187                }
12188                let end_row =
12189                    if selection.end.row > selection.start.row && selection.end.column == 0 {
12190                        MultiBufferRow(selection.end.row - 1)
12191                    } else {
12192                        MultiBufferRow(selection.end.row)
12193                    };
12194                last_toggled_row = Some(end_row);
12195
12196                if start_row > end_row {
12197                    continue;
12198                }
12199
12200                // If the language has line comments, toggle those.
12201                let mut full_comment_prefixes = language.line_comment_prefixes().to_vec();
12202
12203                // If ignore_indent is set, trim spaces from the right side of all full_comment_prefixes
12204                if ignore_indent {
12205                    full_comment_prefixes = full_comment_prefixes
12206                        .into_iter()
12207                        .map(|s| Arc::from(s.trim_end()))
12208                        .collect();
12209                }
12210
12211                if !full_comment_prefixes.is_empty() {
12212                    let first_prefix = full_comment_prefixes
12213                        .first()
12214                        .expect("prefixes is non-empty");
12215                    let prefix_trimmed_lengths = full_comment_prefixes
12216                        .iter()
12217                        .map(|p| p.trim_end_matches(' ').len())
12218                        .collect::<SmallVec<[usize; 4]>>();
12219
12220                    let mut all_selection_lines_are_comments = true;
12221
12222                    for row in start_row.0..=end_row.0 {
12223                        let row = MultiBufferRow(row);
12224                        if start_row < end_row && snapshot.is_line_blank(row) {
12225                            continue;
12226                        }
12227
12228                        let prefix_range = full_comment_prefixes
12229                            .iter()
12230                            .zip(prefix_trimmed_lengths.iter().copied())
12231                            .map(|(prefix, trimmed_prefix_len)| {
12232                                comment_prefix_range(
12233                                    snapshot.deref(),
12234                                    row,
12235                                    &prefix[..trimmed_prefix_len],
12236                                    &prefix[trimmed_prefix_len..],
12237                                    ignore_indent,
12238                                )
12239                            })
12240                            .max_by_key(|range| range.end.column - range.start.column)
12241                            .expect("prefixes is non-empty");
12242
12243                        if prefix_range.is_empty() {
12244                            all_selection_lines_are_comments = false;
12245                        }
12246
12247                        selection_edit_ranges.push(prefix_range);
12248                    }
12249
12250                    if all_selection_lines_are_comments {
12251                        edits.extend(
12252                            selection_edit_ranges
12253                                .iter()
12254                                .cloned()
12255                                .map(|range| (range, empty_str.clone())),
12256                        );
12257                    } else {
12258                        let min_column = selection_edit_ranges
12259                            .iter()
12260                            .map(|range| range.start.column)
12261                            .min()
12262                            .unwrap_or(0);
12263                        edits.extend(selection_edit_ranges.iter().map(|range| {
12264                            let position = Point::new(range.start.row, min_column);
12265                            (position..position, first_prefix.clone())
12266                        }));
12267                    }
12268                } else if let Some((full_comment_prefix, comment_suffix)) =
12269                    language.block_comment_delimiters()
12270                {
12271                    let comment_prefix = full_comment_prefix.trim_end_matches(' ');
12272                    let comment_prefix_whitespace = &full_comment_prefix[comment_prefix.len()..];
12273                    let prefix_range = comment_prefix_range(
12274                        snapshot.deref(),
12275                        start_row,
12276                        comment_prefix,
12277                        comment_prefix_whitespace,
12278                        ignore_indent,
12279                    );
12280                    let suffix_range = comment_suffix_range(
12281                        snapshot.deref(),
12282                        end_row,
12283                        comment_suffix.trim_start_matches(' '),
12284                        comment_suffix.starts_with(' '),
12285                    );
12286
12287                    if prefix_range.is_empty() || suffix_range.is_empty() {
12288                        edits.push((
12289                            prefix_range.start..prefix_range.start,
12290                            full_comment_prefix.clone(),
12291                        ));
12292                        edits.push((suffix_range.end..suffix_range.end, comment_suffix.clone()));
12293                        suffixes_inserted.push((end_row, comment_suffix.len()));
12294                    } else {
12295                        edits.push((prefix_range, empty_str.clone()));
12296                        edits.push((suffix_range, empty_str.clone()));
12297                    }
12298                } else {
12299                    continue;
12300                }
12301            }
12302
12303            drop(snapshot);
12304            this.buffer.update(cx, |buffer, cx| {
12305                buffer.edit(edits, None, cx);
12306            });
12307
12308            // Adjust selections so that they end before any comment suffixes that
12309            // were inserted.
12310            let mut suffixes_inserted = suffixes_inserted.into_iter().peekable();
12311            let mut selections = this.selections.all::<Point>(cx);
12312            let snapshot = this.buffer.read(cx).read(cx);
12313            for selection in &mut selections {
12314                while let Some((row, suffix_len)) = suffixes_inserted.peek().copied() {
12315                    match row.cmp(&MultiBufferRow(selection.end.row)) {
12316                        Ordering::Less => {
12317                            suffixes_inserted.next();
12318                            continue;
12319                        }
12320                        Ordering::Greater => break,
12321                        Ordering::Equal => {
12322                            if selection.end.column == snapshot.line_len(row) {
12323                                if selection.is_empty() {
12324                                    selection.start.column -= suffix_len as u32;
12325                                }
12326                                selection.end.column -= suffix_len as u32;
12327                            }
12328                            break;
12329                        }
12330                    }
12331                }
12332            }
12333
12334            drop(snapshot);
12335            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
12336                s.select(selections)
12337            });
12338
12339            let selections = this.selections.all::<Point>(cx);
12340            let selections_on_single_row = selections.windows(2).all(|selections| {
12341                selections[0].start.row == selections[1].start.row
12342                    && selections[0].end.row == selections[1].end.row
12343                    && selections[0].start.row == selections[0].end.row
12344            });
12345            let selections_selecting = selections
12346                .iter()
12347                .any(|selection| selection.start != selection.end);
12348            let advance_downwards = action.advance_downwards
12349                && selections_on_single_row
12350                && !selections_selecting
12351                && !matches!(this.mode, EditorMode::SingleLine { .. });
12352
12353            if advance_downwards {
12354                let snapshot = this.buffer.read(cx).snapshot(cx);
12355
12356                this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
12357                    s.move_cursors_with(|display_snapshot, display_point, _| {
12358                        let mut point = display_point.to_point(display_snapshot);
12359                        point.row += 1;
12360                        point = snapshot.clip_point(point, Bias::Left);
12361                        let display_point = point.to_display_point(display_snapshot);
12362                        let goal = SelectionGoal::HorizontalPosition(
12363                            display_snapshot
12364                                .x_for_display_point(display_point, text_layout_details)
12365                                .into(),
12366                        );
12367                        (display_point, goal)
12368                    })
12369                });
12370            }
12371        });
12372    }
12373
12374    pub fn select_enclosing_symbol(
12375        &mut self,
12376        _: &SelectEnclosingSymbol,
12377        window: &mut Window,
12378        cx: &mut Context<Self>,
12379    ) {
12380        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
12381
12382        let buffer = self.buffer.read(cx).snapshot(cx);
12383        let old_selections = self.selections.all::<usize>(cx).into_boxed_slice();
12384
12385        fn update_selection(
12386            selection: &Selection<usize>,
12387            buffer_snap: &MultiBufferSnapshot,
12388        ) -> Option<Selection<usize>> {
12389            let cursor = selection.head();
12390            let (_buffer_id, symbols) = buffer_snap.symbols_containing(cursor, None)?;
12391            for symbol in symbols.iter().rev() {
12392                let start = symbol.range.start.to_offset(buffer_snap);
12393                let end = symbol.range.end.to_offset(buffer_snap);
12394                let new_range = start..end;
12395                if start < selection.start || end > selection.end {
12396                    return Some(Selection {
12397                        id: selection.id,
12398                        start: new_range.start,
12399                        end: new_range.end,
12400                        goal: SelectionGoal::None,
12401                        reversed: selection.reversed,
12402                    });
12403                }
12404            }
12405            None
12406        }
12407
12408        let mut selected_larger_symbol = false;
12409        let new_selections = old_selections
12410            .iter()
12411            .map(|selection| match update_selection(selection, &buffer) {
12412                Some(new_selection) => {
12413                    if new_selection.range() != selection.range() {
12414                        selected_larger_symbol = true;
12415                    }
12416                    new_selection
12417                }
12418                None => selection.clone(),
12419            })
12420            .collect::<Vec<_>>();
12421
12422        if selected_larger_symbol {
12423            self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
12424                s.select(new_selections);
12425            });
12426        }
12427    }
12428
12429    pub fn select_larger_syntax_node(
12430        &mut self,
12431        _: &SelectLargerSyntaxNode,
12432        window: &mut Window,
12433        cx: &mut Context<Self>,
12434    ) {
12435        let Some(visible_row_count) = self.visible_row_count() else {
12436            return;
12437        };
12438        let old_selections: Box<[_]> = self.selections.all::<usize>(cx).into();
12439        if old_selections.is_empty() {
12440            return;
12441        }
12442
12443        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
12444
12445        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
12446        let buffer = self.buffer.read(cx).snapshot(cx);
12447
12448        let mut selected_larger_node = false;
12449        let mut new_selections = old_selections
12450            .iter()
12451            .map(|selection| {
12452                let old_range = selection.start..selection.end;
12453                let mut new_range = old_range.clone();
12454                let mut new_node = None;
12455                while let Some((node, containing_range)) = buffer.syntax_ancestor(new_range.clone())
12456                {
12457                    new_node = Some(node);
12458                    new_range = match containing_range {
12459                        MultiOrSingleBufferOffsetRange::Single(_) => break,
12460                        MultiOrSingleBufferOffsetRange::Multi(range) => range,
12461                    };
12462                    if !display_map.intersects_fold(new_range.start)
12463                        && !display_map.intersects_fold(new_range.end)
12464                    {
12465                        break;
12466                    }
12467                }
12468
12469                if let Some(node) = new_node {
12470                    // Log the ancestor, to support using this action as a way to explore TreeSitter
12471                    // nodes. Parent and grandparent are also logged because this operation will not
12472                    // visit nodes that have the same range as their parent.
12473                    log::info!("Node: {node:?}");
12474                    let parent = node.parent();
12475                    log::info!("Parent: {parent:?}");
12476                    let grandparent = parent.and_then(|x| x.parent());
12477                    log::info!("Grandparent: {grandparent:?}");
12478                }
12479
12480                selected_larger_node |= new_range != old_range;
12481                Selection {
12482                    id: selection.id,
12483                    start: new_range.start,
12484                    end: new_range.end,
12485                    goal: SelectionGoal::None,
12486                    reversed: selection.reversed,
12487                }
12488            })
12489            .collect::<Vec<_>>();
12490
12491        if !selected_larger_node {
12492            return; // don't put this call in the history
12493        }
12494
12495        // scroll based on transformation done to the last selection created by the user
12496        let (last_old, last_new) = old_selections
12497            .last()
12498            .zip(new_selections.last().cloned())
12499            .expect("old_selections isn't empty");
12500
12501        // revert selection
12502        let is_selection_reversed = {
12503            let should_newest_selection_be_reversed = last_old.start != last_new.start;
12504            new_selections.last_mut().expect("checked above").reversed =
12505                should_newest_selection_be_reversed;
12506            should_newest_selection_be_reversed
12507        };
12508
12509        if selected_larger_node {
12510            self.select_syntax_node_history.disable_clearing = true;
12511            self.change_selections(None, window, cx, |s| {
12512                s.select(new_selections.clone());
12513            });
12514            self.select_syntax_node_history.disable_clearing = false;
12515        }
12516
12517        let start_row = last_new.start.to_display_point(&display_map).row().0;
12518        let end_row = last_new.end.to_display_point(&display_map).row().0;
12519        let selection_height = end_row - start_row + 1;
12520        let scroll_margin_rows = self.vertical_scroll_margin() as u32;
12521
12522        let fits_on_the_screen = visible_row_count >= selection_height + scroll_margin_rows * 2;
12523        let scroll_behavior = if fits_on_the_screen {
12524            self.request_autoscroll(Autoscroll::fit(), cx);
12525            SelectSyntaxNodeScrollBehavior::FitSelection
12526        } else if is_selection_reversed {
12527            self.scroll_cursor_top(&ScrollCursorTop, window, cx);
12528            SelectSyntaxNodeScrollBehavior::CursorTop
12529        } else {
12530            self.scroll_cursor_bottom(&ScrollCursorBottom, window, cx);
12531            SelectSyntaxNodeScrollBehavior::CursorBottom
12532        };
12533
12534        self.select_syntax_node_history.push((
12535            old_selections,
12536            scroll_behavior,
12537            is_selection_reversed,
12538        ));
12539    }
12540
12541    pub fn select_smaller_syntax_node(
12542        &mut self,
12543        _: &SelectSmallerSyntaxNode,
12544        window: &mut Window,
12545        cx: &mut Context<Self>,
12546    ) {
12547        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
12548
12549        if let Some((mut selections, scroll_behavior, is_selection_reversed)) =
12550            self.select_syntax_node_history.pop()
12551        {
12552            if let Some(selection) = selections.last_mut() {
12553                selection.reversed = is_selection_reversed;
12554            }
12555
12556            self.select_syntax_node_history.disable_clearing = true;
12557            self.change_selections(None, window, cx, |s| {
12558                s.select(selections.to_vec());
12559            });
12560            self.select_syntax_node_history.disable_clearing = false;
12561
12562            match scroll_behavior {
12563                SelectSyntaxNodeScrollBehavior::CursorTop => {
12564                    self.scroll_cursor_top(&ScrollCursorTop, window, cx);
12565                }
12566                SelectSyntaxNodeScrollBehavior::FitSelection => {
12567                    self.request_autoscroll(Autoscroll::fit(), cx);
12568                }
12569                SelectSyntaxNodeScrollBehavior::CursorBottom => {
12570                    self.scroll_cursor_bottom(&ScrollCursorBottom, window, cx);
12571                }
12572            }
12573        }
12574    }
12575
12576    fn refresh_runnables(&mut self, window: &mut Window, cx: &mut Context<Self>) -> Task<()> {
12577        if !EditorSettings::get_global(cx).gutter.runnables {
12578            self.clear_tasks();
12579            return Task::ready(());
12580        }
12581        let project = self.project.as_ref().map(Entity::downgrade);
12582        let task_sources = self.lsp_task_sources(cx);
12583        cx.spawn_in(window, async move |editor, cx| {
12584            cx.background_executor().timer(UPDATE_DEBOUNCE).await;
12585            let Some(project) = project.and_then(|p| p.upgrade()) else {
12586                return;
12587            };
12588            let Ok(display_snapshot) = editor.update(cx, |this, cx| {
12589                this.display_map.update(cx, |map, cx| map.snapshot(cx))
12590            }) else {
12591                return;
12592            };
12593
12594            let hide_runnables = project
12595                .update(cx, |project, cx| {
12596                    // Do not display any test indicators in non-dev server remote projects.
12597                    project.is_via_collab() && project.ssh_connection_string(cx).is_none()
12598                })
12599                .unwrap_or(true);
12600            if hide_runnables {
12601                return;
12602            }
12603            let new_rows =
12604                cx.background_spawn({
12605                    let snapshot = display_snapshot.clone();
12606                    async move {
12607                        Self::fetch_runnable_ranges(&snapshot, Anchor::min()..Anchor::max())
12608                    }
12609                })
12610                    .await;
12611            let Ok(lsp_tasks) =
12612                cx.update(|_, cx| crate::lsp_tasks(project.clone(), &task_sources, None, cx))
12613            else {
12614                return;
12615            };
12616            let lsp_tasks = lsp_tasks.await;
12617
12618            let Ok(mut lsp_tasks_by_rows) = cx.update(|_, cx| {
12619                lsp_tasks
12620                    .into_iter()
12621                    .flat_map(|(kind, tasks)| {
12622                        tasks.into_iter().filter_map(move |(location, task)| {
12623                            Some((kind.clone(), location?, task))
12624                        })
12625                    })
12626                    .fold(HashMap::default(), |mut acc, (kind, location, task)| {
12627                        let buffer = location.target.buffer;
12628                        let buffer_snapshot = buffer.read(cx).snapshot();
12629                        let offset = display_snapshot.buffer_snapshot.excerpts().find_map(
12630                            |(excerpt_id, snapshot, _)| {
12631                                if snapshot.remote_id() == buffer_snapshot.remote_id() {
12632                                    display_snapshot
12633                                        .buffer_snapshot
12634                                        .anchor_in_excerpt(excerpt_id, location.target.range.start)
12635                                } else {
12636                                    None
12637                                }
12638                            },
12639                        );
12640                        if let Some(offset) = offset {
12641                            let task_buffer_range =
12642                                location.target.range.to_point(&buffer_snapshot);
12643                            let context_buffer_range =
12644                                task_buffer_range.to_offset(&buffer_snapshot);
12645                            let context_range = BufferOffset(context_buffer_range.start)
12646                                ..BufferOffset(context_buffer_range.end);
12647
12648                            acc.entry((buffer_snapshot.remote_id(), task_buffer_range.start.row))
12649                                .or_insert_with(|| RunnableTasks {
12650                                    templates: Vec::new(),
12651                                    offset,
12652                                    column: task_buffer_range.start.column,
12653                                    extra_variables: HashMap::default(),
12654                                    context_range,
12655                                })
12656                                .templates
12657                                .push((kind, task.original_task().clone()));
12658                        }
12659
12660                        acc
12661                    })
12662            }) else {
12663                return;
12664            };
12665
12666            let rows = Self::runnable_rows(project, display_snapshot, new_rows, cx.clone());
12667            editor
12668                .update(cx, |editor, _| {
12669                    editor.clear_tasks();
12670                    for (key, mut value) in rows {
12671                        if let Some(lsp_tasks) = lsp_tasks_by_rows.remove(&key) {
12672                            value.templates.extend(lsp_tasks.templates);
12673                        }
12674
12675                        editor.insert_tasks(key, value);
12676                    }
12677                    for (key, value) in lsp_tasks_by_rows {
12678                        editor.insert_tasks(key, value);
12679                    }
12680                })
12681                .ok();
12682        })
12683    }
12684    fn fetch_runnable_ranges(
12685        snapshot: &DisplaySnapshot,
12686        range: Range<Anchor>,
12687    ) -> Vec<language::RunnableRange> {
12688        snapshot.buffer_snapshot.runnable_ranges(range).collect()
12689    }
12690
12691    fn runnable_rows(
12692        project: Entity<Project>,
12693        snapshot: DisplaySnapshot,
12694        runnable_ranges: Vec<RunnableRange>,
12695        mut cx: AsyncWindowContext,
12696    ) -> Vec<((BufferId, BufferRow), RunnableTasks)> {
12697        runnable_ranges
12698            .into_iter()
12699            .filter_map(|mut runnable| {
12700                let tasks = cx
12701                    .update(|_, cx| Self::templates_with_tags(&project, &mut runnable.runnable, cx))
12702                    .ok()?;
12703                if tasks.is_empty() {
12704                    return None;
12705                }
12706
12707                let point = runnable.run_range.start.to_point(&snapshot.buffer_snapshot);
12708
12709                let row = snapshot
12710                    .buffer_snapshot
12711                    .buffer_line_for_row(MultiBufferRow(point.row))?
12712                    .1
12713                    .start
12714                    .row;
12715
12716                let context_range =
12717                    BufferOffset(runnable.full_range.start)..BufferOffset(runnable.full_range.end);
12718                Some((
12719                    (runnable.buffer_id, row),
12720                    RunnableTasks {
12721                        templates: tasks,
12722                        offset: snapshot
12723                            .buffer_snapshot
12724                            .anchor_before(runnable.run_range.start),
12725                        context_range,
12726                        column: point.column,
12727                        extra_variables: runnable.extra_captures,
12728                    },
12729                ))
12730            })
12731            .collect()
12732    }
12733
12734    fn templates_with_tags(
12735        project: &Entity<Project>,
12736        runnable: &mut Runnable,
12737        cx: &mut App,
12738    ) -> Vec<(TaskSourceKind, TaskTemplate)> {
12739        let (inventory, worktree_id, file) = project.read_with(cx, |project, cx| {
12740            let (worktree_id, file) = project
12741                .buffer_for_id(runnable.buffer, cx)
12742                .and_then(|buffer| buffer.read(cx).file())
12743                .map(|file| (file.worktree_id(cx), file.clone()))
12744                .unzip();
12745
12746            (
12747                project.task_store().read(cx).task_inventory().cloned(),
12748                worktree_id,
12749                file,
12750            )
12751        });
12752
12753        let mut templates_with_tags = mem::take(&mut runnable.tags)
12754            .into_iter()
12755            .flat_map(|RunnableTag(tag)| {
12756                inventory
12757                    .as_ref()
12758                    .into_iter()
12759                    .flat_map(|inventory| {
12760                        inventory.read(cx).list_tasks(
12761                            file.clone(),
12762                            Some(runnable.language.clone()),
12763                            worktree_id,
12764                            cx,
12765                        )
12766                    })
12767                    .filter(move |(_, template)| {
12768                        template.tags.iter().any(|source_tag| source_tag == &tag)
12769                    })
12770            })
12771            .sorted_by_key(|(kind, _)| kind.to_owned())
12772            .collect::<Vec<_>>();
12773        if let Some((leading_tag_source, _)) = templates_with_tags.first() {
12774            // Strongest source wins; if we have worktree tag binding, prefer that to
12775            // global and language bindings;
12776            // if we have a global binding, prefer that to language binding.
12777            let first_mismatch = templates_with_tags
12778                .iter()
12779                .position(|(tag_source, _)| tag_source != leading_tag_source);
12780            if let Some(index) = first_mismatch {
12781                templates_with_tags.truncate(index);
12782            }
12783        }
12784
12785        templates_with_tags
12786    }
12787
12788    pub fn move_to_enclosing_bracket(
12789        &mut self,
12790        _: &MoveToEnclosingBracket,
12791        window: &mut Window,
12792        cx: &mut Context<Self>,
12793    ) {
12794        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
12795        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
12796            s.move_offsets_with(|snapshot, selection| {
12797                let Some(enclosing_bracket_ranges) =
12798                    snapshot.enclosing_bracket_ranges(selection.start..selection.end)
12799                else {
12800                    return;
12801                };
12802
12803                let mut best_length = usize::MAX;
12804                let mut best_inside = false;
12805                let mut best_in_bracket_range = false;
12806                let mut best_destination = None;
12807                for (open, close) in enclosing_bracket_ranges {
12808                    let close = close.to_inclusive();
12809                    let length = close.end() - open.start;
12810                    let inside = selection.start >= open.end && selection.end <= *close.start();
12811                    let in_bracket_range = open.to_inclusive().contains(&selection.head())
12812                        || close.contains(&selection.head());
12813
12814                    // If best is next to a bracket and current isn't, skip
12815                    if !in_bracket_range && best_in_bracket_range {
12816                        continue;
12817                    }
12818
12819                    // Prefer smaller lengths unless best is inside and current isn't
12820                    if length > best_length && (best_inside || !inside) {
12821                        continue;
12822                    }
12823
12824                    best_length = length;
12825                    best_inside = inside;
12826                    best_in_bracket_range = in_bracket_range;
12827                    best_destination = Some(
12828                        if close.contains(&selection.start) && close.contains(&selection.end) {
12829                            if inside { open.end } else { open.start }
12830                        } else if inside {
12831                            *close.start()
12832                        } else {
12833                            *close.end()
12834                        },
12835                    );
12836                }
12837
12838                if let Some(destination) = best_destination {
12839                    selection.collapse_to(destination, SelectionGoal::None);
12840                }
12841            })
12842        });
12843    }
12844
12845    pub fn undo_selection(
12846        &mut self,
12847        _: &UndoSelection,
12848        window: &mut Window,
12849        cx: &mut Context<Self>,
12850    ) {
12851        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
12852        self.end_selection(window, cx);
12853        self.selection_history.mode = SelectionHistoryMode::Undoing;
12854        if let Some(entry) = self.selection_history.undo_stack.pop_back() {
12855            self.change_selections(None, window, cx, |s| {
12856                s.select_anchors(entry.selections.to_vec())
12857            });
12858            self.select_next_state = entry.select_next_state;
12859            self.select_prev_state = entry.select_prev_state;
12860            self.add_selections_state = entry.add_selections_state;
12861            self.request_autoscroll(Autoscroll::newest(), cx);
12862        }
12863        self.selection_history.mode = SelectionHistoryMode::Normal;
12864    }
12865
12866    pub fn redo_selection(
12867        &mut self,
12868        _: &RedoSelection,
12869        window: &mut Window,
12870        cx: &mut Context<Self>,
12871    ) {
12872        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
12873        self.end_selection(window, cx);
12874        self.selection_history.mode = SelectionHistoryMode::Redoing;
12875        if let Some(entry) = self.selection_history.redo_stack.pop_back() {
12876            self.change_selections(None, window, cx, |s| {
12877                s.select_anchors(entry.selections.to_vec())
12878            });
12879            self.select_next_state = entry.select_next_state;
12880            self.select_prev_state = entry.select_prev_state;
12881            self.add_selections_state = entry.add_selections_state;
12882            self.request_autoscroll(Autoscroll::newest(), cx);
12883        }
12884        self.selection_history.mode = SelectionHistoryMode::Normal;
12885    }
12886
12887    pub fn expand_excerpts(
12888        &mut self,
12889        action: &ExpandExcerpts,
12890        _: &mut Window,
12891        cx: &mut Context<Self>,
12892    ) {
12893        self.expand_excerpts_for_direction(action.lines, ExpandExcerptDirection::UpAndDown, cx)
12894    }
12895
12896    pub fn expand_excerpts_down(
12897        &mut self,
12898        action: &ExpandExcerptsDown,
12899        _: &mut Window,
12900        cx: &mut Context<Self>,
12901    ) {
12902        self.expand_excerpts_for_direction(action.lines, ExpandExcerptDirection::Down, cx)
12903    }
12904
12905    pub fn expand_excerpts_up(
12906        &mut self,
12907        action: &ExpandExcerptsUp,
12908        _: &mut Window,
12909        cx: &mut Context<Self>,
12910    ) {
12911        self.expand_excerpts_for_direction(action.lines, ExpandExcerptDirection::Up, cx)
12912    }
12913
12914    pub fn expand_excerpts_for_direction(
12915        &mut self,
12916        lines: u32,
12917        direction: ExpandExcerptDirection,
12918
12919        cx: &mut Context<Self>,
12920    ) {
12921        let selections = self.selections.disjoint_anchors();
12922
12923        let lines = if lines == 0 {
12924            EditorSettings::get_global(cx).expand_excerpt_lines
12925        } else {
12926            lines
12927        };
12928
12929        self.buffer.update(cx, |buffer, cx| {
12930            let snapshot = buffer.snapshot(cx);
12931            let mut excerpt_ids = selections
12932                .iter()
12933                .flat_map(|selection| snapshot.excerpt_ids_for_range(selection.range()))
12934                .collect::<Vec<_>>();
12935            excerpt_ids.sort();
12936            excerpt_ids.dedup();
12937            buffer.expand_excerpts(excerpt_ids, lines, direction, cx)
12938        })
12939    }
12940
12941    pub fn expand_excerpt(
12942        &mut self,
12943        excerpt: ExcerptId,
12944        direction: ExpandExcerptDirection,
12945        window: &mut Window,
12946        cx: &mut Context<Self>,
12947    ) {
12948        let current_scroll_position = self.scroll_position(cx);
12949        let lines_to_expand = EditorSettings::get_global(cx).expand_excerpt_lines;
12950        let mut should_scroll_up = false;
12951
12952        if direction == ExpandExcerptDirection::Down {
12953            let multi_buffer = self.buffer.read(cx);
12954            let snapshot = multi_buffer.snapshot(cx);
12955            if let Some(buffer_id) = snapshot.buffer_id_for_excerpt(excerpt) {
12956                if let Some(buffer) = multi_buffer.buffer(buffer_id) {
12957                    if let Some(excerpt_range) = snapshot.buffer_range_for_excerpt(excerpt) {
12958                        let buffer_snapshot = buffer.read(cx).snapshot();
12959                        let excerpt_end_row =
12960                            Point::from_anchor(&excerpt_range.end, &buffer_snapshot).row;
12961                        let last_row = buffer_snapshot.max_point().row;
12962                        let lines_below = last_row.saturating_sub(excerpt_end_row);
12963                        should_scroll_up = lines_below >= lines_to_expand;
12964                    }
12965                }
12966            }
12967        }
12968
12969        self.buffer.update(cx, |buffer, cx| {
12970            buffer.expand_excerpts([excerpt], lines_to_expand, direction, cx)
12971        });
12972
12973        if should_scroll_up {
12974            let new_scroll_position =
12975                current_scroll_position + gpui::Point::new(0.0, lines_to_expand as f32);
12976            self.set_scroll_position(new_scroll_position, window, cx);
12977        }
12978    }
12979
12980    pub fn go_to_singleton_buffer_point(
12981        &mut self,
12982        point: Point,
12983        window: &mut Window,
12984        cx: &mut Context<Self>,
12985    ) {
12986        self.go_to_singleton_buffer_range(point..point, window, cx);
12987    }
12988
12989    pub fn go_to_singleton_buffer_range(
12990        &mut self,
12991        range: Range<Point>,
12992        window: &mut Window,
12993        cx: &mut Context<Self>,
12994    ) {
12995        let multibuffer = self.buffer().read(cx);
12996        let Some(buffer) = multibuffer.as_singleton() else {
12997            return;
12998        };
12999        let Some(start) = multibuffer.buffer_point_to_anchor(&buffer, range.start, cx) else {
13000            return;
13001        };
13002        let Some(end) = multibuffer.buffer_point_to_anchor(&buffer, range.end, cx) else {
13003            return;
13004        };
13005        self.change_selections(Some(Autoscroll::center()), window, cx, |s| {
13006            s.select_anchor_ranges([start..end])
13007        });
13008    }
13009
13010    fn go_to_diagnostic(
13011        &mut self,
13012        _: &GoToDiagnostic,
13013        window: &mut Window,
13014        cx: &mut Context<Self>,
13015    ) {
13016        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
13017        self.go_to_diagnostic_impl(Direction::Next, window, cx)
13018    }
13019
13020    fn go_to_prev_diagnostic(
13021        &mut self,
13022        _: &GoToPreviousDiagnostic,
13023        window: &mut Window,
13024        cx: &mut Context<Self>,
13025    ) {
13026        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
13027        self.go_to_diagnostic_impl(Direction::Prev, window, cx)
13028    }
13029
13030    pub fn go_to_diagnostic_impl(
13031        &mut self,
13032        direction: Direction,
13033        window: &mut Window,
13034        cx: &mut Context<Self>,
13035    ) {
13036        let buffer = self.buffer.read(cx).snapshot(cx);
13037        let selection = self.selections.newest::<usize>(cx);
13038        // If there is an active Diagnostic Popover jump to its diagnostic instead.
13039        if direction == Direction::Next {
13040            if let Some(popover) = self.hover_state.diagnostic_popover.as_ref() {
13041                let Some(buffer_id) = popover.local_diagnostic.range.start.buffer_id else {
13042                    return;
13043                };
13044                self.activate_diagnostics(
13045                    buffer_id,
13046                    popover.local_diagnostic.diagnostic.group_id,
13047                    window,
13048                    cx,
13049                );
13050                if let Some(active_diagnostics) = self.active_diagnostics.as_ref() {
13051                    let primary_range_start = active_diagnostics.primary_range.start;
13052                    self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
13053                        let mut new_selection = s.newest_anchor().clone();
13054                        new_selection.collapse_to(primary_range_start, SelectionGoal::None);
13055                        s.select_anchors(vec![new_selection.clone()]);
13056                    });
13057                    self.refresh_inline_completion(false, true, window, cx);
13058                }
13059                return;
13060            }
13061        }
13062
13063        let active_group_id = self
13064            .active_diagnostics
13065            .as_ref()
13066            .map(|active_group| active_group.group_id);
13067        let active_primary_range = self.active_diagnostics.as_ref().map(|active_diagnostics| {
13068            active_diagnostics
13069                .primary_range
13070                .to_offset(&buffer)
13071                .to_inclusive()
13072        });
13073        let search_start = if let Some(active_primary_range) = active_primary_range.as_ref() {
13074            if active_primary_range.contains(&selection.head()) {
13075                *active_primary_range.start()
13076            } else {
13077                selection.head()
13078            }
13079        } else {
13080            selection.head()
13081        };
13082
13083        let snapshot = self.snapshot(window, cx);
13084        let primary_diagnostics_before = buffer
13085            .diagnostics_in_range::<usize>(0..search_start)
13086            .filter(|entry| entry.diagnostic.is_primary)
13087            .filter(|entry| entry.range.start != entry.range.end)
13088            .filter(|entry| entry.diagnostic.severity <= DiagnosticSeverity::WARNING)
13089            .filter(|entry| !snapshot.intersects_fold(entry.range.start))
13090            .collect::<Vec<_>>();
13091        let last_same_group_diagnostic_before = active_group_id.and_then(|active_group_id| {
13092            primary_diagnostics_before
13093                .iter()
13094                .position(|entry| entry.diagnostic.group_id == active_group_id)
13095        });
13096
13097        let primary_diagnostics_after = buffer
13098            .diagnostics_in_range::<usize>(search_start..buffer.len())
13099            .filter(|entry| entry.diagnostic.is_primary)
13100            .filter(|entry| entry.range.start != entry.range.end)
13101            .filter(|entry| entry.diagnostic.severity <= DiagnosticSeverity::WARNING)
13102            .filter(|diagnostic| !snapshot.intersects_fold(diagnostic.range.start))
13103            .collect::<Vec<_>>();
13104        let last_same_group_diagnostic_after = active_group_id.and_then(|active_group_id| {
13105            primary_diagnostics_after
13106                .iter()
13107                .enumerate()
13108                .rev()
13109                .find_map(|(i, entry)| {
13110                    if entry.diagnostic.group_id == active_group_id {
13111                        Some(i)
13112                    } else {
13113                        None
13114                    }
13115                })
13116        });
13117
13118        let next_primary_diagnostic = match direction {
13119            Direction::Prev => primary_diagnostics_before
13120                .iter()
13121                .take(last_same_group_diagnostic_before.unwrap_or(usize::MAX))
13122                .rev()
13123                .next(),
13124            Direction::Next => primary_diagnostics_after
13125                .iter()
13126                .skip(
13127                    last_same_group_diagnostic_after
13128                        .map(|index| index + 1)
13129                        .unwrap_or(0),
13130                )
13131                .next(),
13132        };
13133
13134        // Cycle around to the start of the buffer, potentially moving back to the start of
13135        // the currently active diagnostic.
13136        let cycle_around = || match direction {
13137            Direction::Prev => primary_diagnostics_after
13138                .iter()
13139                .rev()
13140                .chain(primary_diagnostics_before.iter().rev())
13141                .next(),
13142            Direction::Next => primary_diagnostics_before
13143                .iter()
13144                .chain(primary_diagnostics_after.iter())
13145                .next(),
13146        };
13147
13148        if let Some((primary_range, group_id)) = next_primary_diagnostic
13149            .or_else(cycle_around)
13150            .map(|entry| (&entry.range, entry.diagnostic.group_id))
13151        {
13152            let Some(buffer_id) = buffer.anchor_after(primary_range.start).buffer_id else {
13153                return;
13154            };
13155            self.activate_diagnostics(buffer_id, group_id, window, cx);
13156            if self.active_diagnostics.is_some() {
13157                self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
13158                    s.select(vec![Selection {
13159                        id: selection.id,
13160                        start: primary_range.start,
13161                        end: primary_range.start,
13162                        reversed: false,
13163                        goal: SelectionGoal::None,
13164                    }]);
13165                });
13166                self.refresh_inline_completion(false, true, window, cx);
13167            }
13168        }
13169    }
13170
13171    fn go_to_next_hunk(&mut self, _: &GoToHunk, window: &mut Window, cx: &mut Context<Self>) {
13172        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
13173        let snapshot = self.snapshot(window, cx);
13174        let selection = self.selections.newest::<Point>(cx);
13175        self.go_to_hunk_before_or_after_position(
13176            &snapshot,
13177            selection.head(),
13178            Direction::Next,
13179            window,
13180            cx,
13181        );
13182    }
13183
13184    pub fn go_to_hunk_before_or_after_position(
13185        &mut self,
13186        snapshot: &EditorSnapshot,
13187        position: Point,
13188        direction: Direction,
13189        window: &mut Window,
13190        cx: &mut Context<Editor>,
13191    ) {
13192        let row = if direction == Direction::Next {
13193            self.hunk_after_position(snapshot, position)
13194                .map(|hunk| hunk.row_range.start)
13195        } else {
13196            self.hunk_before_position(snapshot, position)
13197        };
13198
13199        if let Some(row) = row {
13200            let destination = Point::new(row.0, 0);
13201            let autoscroll = Autoscroll::center();
13202
13203            self.unfold_ranges(&[destination..destination], false, false, cx);
13204            self.change_selections(Some(autoscroll), window, cx, |s| {
13205                s.select_ranges([destination..destination]);
13206            });
13207        }
13208    }
13209
13210    fn hunk_after_position(
13211        &mut self,
13212        snapshot: &EditorSnapshot,
13213        position: Point,
13214    ) -> Option<MultiBufferDiffHunk> {
13215        snapshot
13216            .buffer_snapshot
13217            .diff_hunks_in_range(position..snapshot.buffer_snapshot.max_point())
13218            .find(|hunk| hunk.row_range.start.0 > position.row)
13219            .or_else(|| {
13220                snapshot
13221                    .buffer_snapshot
13222                    .diff_hunks_in_range(Point::zero()..position)
13223                    .find(|hunk| hunk.row_range.end.0 < position.row)
13224            })
13225    }
13226
13227    fn go_to_prev_hunk(
13228        &mut self,
13229        _: &GoToPreviousHunk,
13230        window: &mut Window,
13231        cx: &mut Context<Self>,
13232    ) {
13233        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
13234        let snapshot = self.snapshot(window, cx);
13235        let selection = self.selections.newest::<Point>(cx);
13236        self.go_to_hunk_before_or_after_position(
13237            &snapshot,
13238            selection.head(),
13239            Direction::Prev,
13240            window,
13241            cx,
13242        );
13243    }
13244
13245    fn hunk_before_position(
13246        &mut self,
13247        snapshot: &EditorSnapshot,
13248        position: Point,
13249    ) -> Option<MultiBufferRow> {
13250        snapshot
13251            .buffer_snapshot
13252            .diff_hunk_before(position)
13253            .or_else(|| snapshot.buffer_snapshot.diff_hunk_before(Point::MAX))
13254    }
13255
13256    fn go_to_line<T: 'static>(
13257        &mut self,
13258        position: Anchor,
13259        highlight_color: Option<Hsla>,
13260        window: &mut Window,
13261        cx: &mut Context<Self>,
13262    ) {
13263        let snapshot = self.snapshot(window, cx).display_snapshot;
13264        let position = position.to_point(&snapshot.buffer_snapshot);
13265        let start = snapshot
13266            .buffer_snapshot
13267            .clip_point(Point::new(position.row, 0), Bias::Left);
13268        let end = start + Point::new(1, 0);
13269        let start = snapshot.buffer_snapshot.anchor_before(start);
13270        let end = snapshot.buffer_snapshot.anchor_before(end);
13271
13272        self.highlight_rows::<T>(
13273            start..end,
13274            highlight_color
13275                .unwrap_or_else(|| cx.theme().colors().editor_highlighted_line_background),
13276            false,
13277            cx,
13278        );
13279        self.request_autoscroll(Autoscroll::center().for_anchor(start), cx);
13280    }
13281
13282    pub fn go_to_definition(
13283        &mut self,
13284        _: &GoToDefinition,
13285        window: &mut Window,
13286        cx: &mut Context<Self>,
13287    ) -> Task<Result<Navigated>> {
13288        let definition =
13289            self.go_to_definition_of_kind(GotoDefinitionKind::Symbol, false, window, cx);
13290        let fallback_strategy = EditorSettings::get_global(cx).go_to_definition_fallback;
13291        cx.spawn_in(window, async move |editor, cx| {
13292            if definition.await? == Navigated::Yes {
13293                return Ok(Navigated::Yes);
13294            }
13295            match fallback_strategy {
13296                GoToDefinitionFallback::None => Ok(Navigated::No),
13297                GoToDefinitionFallback::FindAllReferences => {
13298                    match editor.update_in(cx, |editor, window, cx| {
13299                        editor.find_all_references(&FindAllReferences, window, cx)
13300                    })? {
13301                        Some(references) => references.await,
13302                        None => Ok(Navigated::No),
13303                    }
13304                }
13305            }
13306        })
13307    }
13308
13309    pub fn go_to_declaration(
13310        &mut self,
13311        _: &GoToDeclaration,
13312        window: &mut Window,
13313        cx: &mut Context<Self>,
13314    ) -> Task<Result<Navigated>> {
13315        self.go_to_definition_of_kind(GotoDefinitionKind::Declaration, false, window, cx)
13316    }
13317
13318    pub fn go_to_declaration_split(
13319        &mut self,
13320        _: &GoToDeclaration,
13321        window: &mut Window,
13322        cx: &mut Context<Self>,
13323    ) -> Task<Result<Navigated>> {
13324        self.go_to_definition_of_kind(GotoDefinitionKind::Declaration, true, window, cx)
13325    }
13326
13327    pub fn go_to_implementation(
13328        &mut self,
13329        _: &GoToImplementation,
13330        window: &mut Window,
13331        cx: &mut Context<Self>,
13332    ) -> Task<Result<Navigated>> {
13333        self.go_to_definition_of_kind(GotoDefinitionKind::Implementation, false, window, cx)
13334    }
13335
13336    pub fn go_to_implementation_split(
13337        &mut self,
13338        _: &GoToImplementationSplit,
13339        window: &mut Window,
13340        cx: &mut Context<Self>,
13341    ) -> Task<Result<Navigated>> {
13342        self.go_to_definition_of_kind(GotoDefinitionKind::Implementation, true, window, cx)
13343    }
13344
13345    pub fn go_to_type_definition(
13346        &mut self,
13347        _: &GoToTypeDefinition,
13348        window: &mut Window,
13349        cx: &mut Context<Self>,
13350    ) -> Task<Result<Navigated>> {
13351        self.go_to_definition_of_kind(GotoDefinitionKind::Type, false, window, cx)
13352    }
13353
13354    pub fn go_to_definition_split(
13355        &mut self,
13356        _: &GoToDefinitionSplit,
13357        window: &mut Window,
13358        cx: &mut Context<Self>,
13359    ) -> Task<Result<Navigated>> {
13360        self.go_to_definition_of_kind(GotoDefinitionKind::Symbol, true, window, cx)
13361    }
13362
13363    pub fn go_to_type_definition_split(
13364        &mut self,
13365        _: &GoToTypeDefinitionSplit,
13366        window: &mut Window,
13367        cx: &mut Context<Self>,
13368    ) -> Task<Result<Navigated>> {
13369        self.go_to_definition_of_kind(GotoDefinitionKind::Type, true, window, cx)
13370    }
13371
13372    fn go_to_definition_of_kind(
13373        &mut self,
13374        kind: GotoDefinitionKind,
13375        split: bool,
13376        window: &mut Window,
13377        cx: &mut Context<Self>,
13378    ) -> Task<Result<Navigated>> {
13379        let Some(provider) = self.semantics_provider.clone() else {
13380            return Task::ready(Ok(Navigated::No));
13381        };
13382        let head = self.selections.newest::<usize>(cx).head();
13383        let buffer = self.buffer.read(cx);
13384        let (buffer, head) = if let Some(text_anchor) = buffer.text_anchor_for_position(head, cx) {
13385            text_anchor
13386        } else {
13387            return Task::ready(Ok(Navigated::No));
13388        };
13389
13390        let Some(definitions) = provider.definitions(&buffer, head, kind, cx) else {
13391            return Task::ready(Ok(Navigated::No));
13392        };
13393
13394        cx.spawn_in(window, async move |editor, cx| {
13395            let definitions = definitions.await?;
13396            let navigated = editor
13397                .update_in(cx, |editor, window, cx| {
13398                    editor.navigate_to_hover_links(
13399                        Some(kind),
13400                        definitions
13401                            .into_iter()
13402                            .filter(|location| {
13403                                hover_links::exclude_link_to_position(&buffer, &head, location, cx)
13404                            })
13405                            .map(HoverLink::Text)
13406                            .collect::<Vec<_>>(),
13407                        split,
13408                        window,
13409                        cx,
13410                    )
13411                })?
13412                .await?;
13413            anyhow::Ok(navigated)
13414        })
13415    }
13416
13417    pub fn open_url(&mut self, _: &OpenUrl, window: &mut Window, cx: &mut Context<Self>) {
13418        let selection = self.selections.newest_anchor();
13419        let head = selection.head();
13420        let tail = selection.tail();
13421
13422        let Some((buffer, start_position)) =
13423            self.buffer.read(cx).text_anchor_for_position(head, cx)
13424        else {
13425            return;
13426        };
13427
13428        let end_position = if head != tail {
13429            let Some((_, pos)) = self.buffer.read(cx).text_anchor_for_position(tail, cx) else {
13430                return;
13431            };
13432            Some(pos)
13433        } else {
13434            None
13435        };
13436
13437        let url_finder = cx.spawn_in(window, async move |editor, cx| {
13438            let url = if let Some(end_pos) = end_position {
13439                find_url_from_range(&buffer, start_position..end_pos, cx.clone())
13440            } else {
13441                find_url(&buffer, start_position, cx.clone()).map(|(_, url)| url)
13442            };
13443
13444            if let Some(url) = url {
13445                editor.update(cx, |_, cx| {
13446                    cx.open_url(&url);
13447                })
13448            } else {
13449                Ok(())
13450            }
13451        });
13452
13453        url_finder.detach();
13454    }
13455
13456    pub fn open_selected_filename(
13457        &mut self,
13458        _: &OpenSelectedFilename,
13459        window: &mut Window,
13460        cx: &mut Context<Self>,
13461    ) {
13462        let Some(workspace) = self.workspace() else {
13463            return;
13464        };
13465
13466        let position = self.selections.newest_anchor().head();
13467
13468        let Some((buffer, buffer_position)) =
13469            self.buffer.read(cx).text_anchor_for_position(position, cx)
13470        else {
13471            return;
13472        };
13473
13474        let project = self.project.clone();
13475
13476        cx.spawn_in(window, async move |_, cx| {
13477            let result = find_file(&buffer, project, buffer_position, cx).await;
13478
13479            if let Some((_, path)) = result {
13480                workspace
13481                    .update_in(cx, |workspace, window, cx| {
13482                        workspace.open_resolved_path(path, window, cx)
13483                    })?
13484                    .await?;
13485            }
13486            anyhow::Ok(())
13487        })
13488        .detach();
13489    }
13490
13491    pub(crate) fn navigate_to_hover_links(
13492        &mut self,
13493        kind: Option<GotoDefinitionKind>,
13494        mut definitions: Vec<HoverLink>,
13495        split: bool,
13496        window: &mut Window,
13497        cx: &mut Context<Editor>,
13498    ) -> Task<Result<Navigated>> {
13499        // If there is one definition, just open it directly
13500        if definitions.len() == 1 {
13501            let definition = definitions.pop().unwrap();
13502
13503            enum TargetTaskResult {
13504                Location(Option<Location>),
13505                AlreadyNavigated,
13506            }
13507
13508            let target_task = match definition {
13509                HoverLink::Text(link) => {
13510                    Task::ready(anyhow::Ok(TargetTaskResult::Location(Some(link.target))))
13511                }
13512                HoverLink::InlayHint(lsp_location, server_id) => {
13513                    let computation =
13514                        self.compute_target_location(lsp_location, server_id, window, cx);
13515                    cx.background_spawn(async move {
13516                        let location = computation.await?;
13517                        Ok(TargetTaskResult::Location(location))
13518                    })
13519                }
13520                HoverLink::Url(url) => {
13521                    cx.open_url(&url);
13522                    Task::ready(Ok(TargetTaskResult::AlreadyNavigated))
13523                }
13524                HoverLink::File(path) => {
13525                    if let Some(workspace) = self.workspace() {
13526                        cx.spawn_in(window, async move |_, cx| {
13527                            workspace
13528                                .update_in(cx, |workspace, window, cx| {
13529                                    workspace.open_resolved_path(path, window, cx)
13530                                })?
13531                                .await
13532                                .map(|_| TargetTaskResult::AlreadyNavigated)
13533                        })
13534                    } else {
13535                        Task::ready(Ok(TargetTaskResult::Location(None)))
13536                    }
13537                }
13538            };
13539            cx.spawn_in(window, async move |editor, cx| {
13540                let target = match target_task.await.context("target resolution task")? {
13541                    TargetTaskResult::AlreadyNavigated => return Ok(Navigated::Yes),
13542                    TargetTaskResult::Location(None) => return Ok(Navigated::No),
13543                    TargetTaskResult::Location(Some(target)) => target,
13544                };
13545
13546                editor.update_in(cx, |editor, window, cx| {
13547                    let Some(workspace) = editor.workspace() else {
13548                        return Navigated::No;
13549                    };
13550                    let pane = workspace.read(cx).active_pane().clone();
13551
13552                    let range = target.range.to_point(target.buffer.read(cx));
13553                    let range = editor.range_for_match(&range);
13554                    let range = collapse_multiline_range(range);
13555
13556                    if !split
13557                        && Some(&target.buffer) == editor.buffer.read(cx).as_singleton().as_ref()
13558                    {
13559                        editor.go_to_singleton_buffer_range(range.clone(), window, cx);
13560                    } else {
13561                        window.defer(cx, move |window, cx| {
13562                            let target_editor: Entity<Self> =
13563                                workspace.update(cx, |workspace, cx| {
13564                                    let pane = if split {
13565                                        workspace.adjacent_pane(window, cx)
13566                                    } else {
13567                                        workspace.active_pane().clone()
13568                                    };
13569
13570                                    workspace.open_project_item(
13571                                        pane,
13572                                        target.buffer.clone(),
13573                                        true,
13574                                        true,
13575                                        window,
13576                                        cx,
13577                                    )
13578                                });
13579                            target_editor.update(cx, |target_editor, cx| {
13580                                // When selecting a definition in a different buffer, disable the nav history
13581                                // to avoid creating a history entry at the previous cursor location.
13582                                pane.update(cx, |pane, _| pane.disable_history());
13583                                target_editor.go_to_singleton_buffer_range(range, window, cx);
13584                                pane.update(cx, |pane, _| pane.enable_history());
13585                            });
13586                        });
13587                    }
13588                    Navigated::Yes
13589                })
13590            })
13591        } else if !definitions.is_empty() {
13592            cx.spawn_in(window, async move |editor, cx| {
13593                let (title, location_tasks, workspace) = editor
13594                    .update_in(cx, |editor, window, cx| {
13595                        let tab_kind = match kind {
13596                            Some(GotoDefinitionKind::Implementation) => "Implementations",
13597                            _ => "Definitions",
13598                        };
13599                        let title = definitions
13600                            .iter()
13601                            .find_map(|definition| match definition {
13602                                HoverLink::Text(link) => link.origin.as_ref().map(|origin| {
13603                                    let buffer = origin.buffer.read(cx);
13604                                    format!(
13605                                        "{} for {}",
13606                                        tab_kind,
13607                                        buffer
13608                                            .text_for_range(origin.range.clone())
13609                                            .collect::<String>()
13610                                    )
13611                                }),
13612                                HoverLink::InlayHint(_, _) => None,
13613                                HoverLink::Url(_) => None,
13614                                HoverLink::File(_) => None,
13615                            })
13616                            .unwrap_or(tab_kind.to_string());
13617                        let location_tasks = definitions
13618                            .into_iter()
13619                            .map(|definition| match definition {
13620                                HoverLink::Text(link) => Task::ready(Ok(Some(link.target))),
13621                                HoverLink::InlayHint(lsp_location, server_id) => editor
13622                                    .compute_target_location(lsp_location, server_id, window, cx),
13623                                HoverLink::Url(_) => Task::ready(Ok(None)),
13624                                HoverLink::File(_) => Task::ready(Ok(None)),
13625                            })
13626                            .collect::<Vec<_>>();
13627                        (title, location_tasks, editor.workspace().clone())
13628                    })
13629                    .context("location tasks preparation")?;
13630
13631                let locations = future::join_all(location_tasks)
13632                    .await
13633                    .into_iter()
13634                    .filter_map(|location| location.transpose())
13635                    .collect::<Result<_>>()
13636                    .context("location tasks")?;
13637
13638                let Some(workspace) = workspace else {
13639                    return Ok(Navigated::No);
13640                };
13641                let opened = workspace
13642                    .update_in(cx, |workspace, window, cx| {
13643                        Self::open_locations_in_multibuffer(
13644                            workspace,
13645                            locations,
13646                            title,
13647                            split,
13648                            MultibufferSelectionMode::First,
13649                            window,
13650                            cx,
13651                        )
13652                    })
13653                    .ok();
13654
13655                anyhow::Ok(Navigated::from_bool(opened.is_some()))
13656            })
13657        } else {
13658            Task::ready(Ok(Navigated::No))
13659        }
13660    }
13661
13662    fn compute_target_location(
13663        &self,
13664        lsp_location: lsp::Location,
13665        server_id: LanguageServerId,
13666        window: &mut Window,
13667        cx: &mut Context<Self>,
13668    ) -> Task<anyhow::Result<Option<Location>>> {
13669        let Some(project) = self.project.clone() else {
13670            return Task::ready(Ok(None));
13671        };
13672
13673        cx.spawn_in(window, async move |editor, cx| {
13674            let location_task = editor.update(cx, |_, cx| {
13675                project.update(cx, |project, cx| {
13676                    let language_server_name = project
13677                        .language_server_statuses(cx)
13678                        .find(|(id, _)| server_id == *id)
13679                        .map(|(_, status)| LanguageServerName::from(status.name.as_str()));
13680                    language_server_name.map(|language_server_name| {
13681                        project.open_local_buffer_via_lsp(
13682                            lsp_location.uri.clone(),
13683                            server_id,
13684                            language_server_name,
13685                            cx,
13686                        )
13687                    })
13688                })
13689            })?;
13690            let location = match location_task {
13691                Some(task) => Some({
13692                    let target_buffer_handle = task.await.context("open local buffer")?;
13693                    let range = target_buffer_handle.update(cx, |target_buffer, _| {
13694                        let target_start = target_buffer
13695                            .clip_point_utf16(point_from_lsp(lsp_location.range.start), Bias::Left);
13696                        let target_end = target_buffer
13697                            .clip_point_utf16(point_from_lsp(lsp_location.range.end), Bias::Left);
13698                        target_buffer.anchor_after(target_start)
13699                            ..target_buffer.anchor_before(target_end)
13700                    })?;
13701                    Location {
13702                        buffer: target_buffer_handle,
13703                        range,
13704                    }
13705                }),
13706                None => None,
13707            };
13708            Ok(location)
13709        })
13710    }
13711
13712    pub fn find_all_references(
13713        &mut self,
13714        _: &FindAllReferences,
13715        window: &mut Window,
13716        cx: &mut Context<Self>,
13717    ) -> Option<Task<Result<Navigated>>> {
13718        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
13719
13720        let selection = self.selections.newest::<usize>(cx);
13721        let multi_buffer = self.buffer.read(cx);
13722        let head = selection.head();
13723
13724        let multi_buffer_snapshot = multi_buffer.snapshot(cx);
13725        let head_anchor = multi_buffer_snapshot.anchor_at(
13726            head,
13727            if head < selection.tail() {
13728                Bias::Right
13729            } else {
13730                Bias::Left
13731            },
13732        );
13733
13734        match self
13735            .find_all_references_task_sources
13736            .binary_search_by(|anchor| anchor.cmp(&head_anchor, &multi_buffer_snapshot))
13737        {
13738            Ok(_) => {
13739                log::info!(
13740                    "Ignoring repeated FindAllReferences invocation with the position of already running task"
13741                );
13742                return None;
13743            }
13744            Err(i) => {
13745                self.find_all_references_task_sources.insert(i, head_anchor);
13746            }
13747        }
13748
13749        let (buffer, head) = multi_buffer.text_anchor_for_position(head, cx)?;
13750        let workspace = self.workspace()?;
13751        let project = workspace.read(cx).project().clone();
13752        let references = project.update(cx, |project, cx| project.references(&buffer, head, cx));
13753        Some(cx.spawn_in(window, async move |editor, cx| {
13754            let _cleanup = cx.on_drop(&editor, move |editor, _| {
13755                if let Ok(i) = editor
13756                    .find_all_references_task_sources
13757                    .binary_search_by(|anchor| anchor.cmp(&head_anchor, &multi_buffer_snapshot))
13758                {
13759                    editor.find_all_references_task_sources.remove(i);
13760                }
13761            });
13762
13763            let locations = references.await?;
13764            if locations.is_empty() {
13765                return anyhow::Ok(Navigated::No);
13766            }
13767
13768            workspace.update_in(cx, |workspace, window, cx| {
13769                let title = locations
13770                    .first()
13771                    .as_ref()
13772                    .map(|location| {
13773                        let buffer = location.buffer.read(cx);
13774                        format!(
13775                            "References to `{}`",
13776                            buffer
13777                                .text_for_range(location.range.clone())
13778                                .collect::<String>()
13779                        )
13780                    })
13781                    .unwrap();
13782                Self::open_locations_in_multibuffer(
13783                    workspace,
13784                    locations,
13785                    title,
13786                    false,
13787                    MultibufferSelectionMode::First,
13788                    window,
13789                    cx,
13790                );
13791                Navigated::Yes
13792            })
13793        }))
13794    }
13795
13796    /// Opens a multibuffer with the given project locations in it
13797    pub fn open_locations_in_multibuffer(
13798        workspace: &mut Workspace,
13799        mut locations: Vec<Location>,
13800        title: String,
13801        split: bool,
13802        multibuffer_selection_mode: MultibufferSelectionMode,
13803        window: &mut Window,
13804        cx: &mut Context<Workspace>,
13805    ) {
13806        // If there are multiple definitions, open them in a multibuffer
13807        locations.sort_by_key(|location| location.buffer.read(cx).remote_id());
13808        let mut locations = locations.into_iter().peekable();
13809        let mut ranges: Vec<Range<Anchor>> = Vec::new();
13810        let capability = workspace.project().read(cx).capability();
13811
13812        let excerpt_buffer = cx.new(|cx| {
13813            let mut multibuffer = MultiBuffer::new(capability);
13814            while let Some(location) = locations.next() {
13815                let buffer = location.buffer.read(cx);
13816                let mut ranges_for_buffer = Vec::new();
13817                let range = location.range.to_point(buffer);
13818                ranges_for_buffer.push(range.clone());
13819
13820                while let Some(next_location) = locations.peek() {
13821                    if next_location.buffer == location.buffer {
13822                        ranges_for_buffer.push(next_location.range.to_point(buffer));
13823                        locations.next();
13824                    } else {
13825                        break;
13826                    }
13827                }
13828
13829                ranges_for_buffer.sort_by_key(|range| (range.start, Reverse(range.end)));
13830                let (new_ranges, _) = multibuffer.set_excerpts_for_path(
13831                    PathKey::for_buffer(&location.buffer, cx),
13832                    location.buffer.clone(),
13833                    ranges_for_buffer,
13834                    DEFAULT_MULTIBUFFER_CONTEXT,
13835                    cx,
13836                );
13837                ranges.extend(new_ranges)
13838            }
13839
13840            multibuffer.with_title(title)
13841        });
13842
13843        let editor = cx.new(|cx| {
13844            Editor::for_multibuffer(
13845                excerpt_buffer,
13846                Some(workspace.project().clone()),
13847                window,
13848                cx,
13849            )
13850        });
13851        editor.update(cx, |editor, cx| {
13852            match multibuffer_selection_mode {
13853                MultibufferSelectionMode::First => {
13854                    if let Some(first_range) = ranges.first() {
13855                        editor.change_selections(None, window, cx, |selections| {
13856                            selections.clear_disjoint();
13857                            selections.select_anchor_ranges(std::iter::once(first_range.clone()));
13858                        });
13859                    }
13860                    editor.highlight_background::<Self>(
13861                        &ranges,
13862                        |theme| theme.editor_highlighted_line_background,
13863                        cx,
13864                    );
13865                }
13866                MultibufferSelectionMode::All => {
13867                    editor.change_selections(None, window, cx, |selections| {
13868                        selections.clear_disjoint();
13869                        selections.select_anchor_ranges(ranges);
13870                    });
13871                }
13872            }
13873            editor.register_buffers_with_language_servers(cx);
13874        });
13875
13876        let item = Box::new(editor);
13877        let item_id = item.item_id();
13878
13879        if split {
13880            workspace.split_item(SplitDirection::Right, item.clone(), window, cx);
13881        } else {
13882            if PreviewTabsSettings::get_global(cx).enable_preview_from_code_navigation {
13883                let (preview_item_id, preview_item_idx) =
13884                    workspace.active_pane().update(cx, |pane, _| {
13885                        (pane.preview_item_id(), pane.preview_item_idx())
13886                    });
13887
13888                workspace.add_item_to_active_pane(item.clone(), preview_item_idx, true, window, cx);
13889
13890                if let Some(preview_item_id) = preview_item_id {
13891                    workspace.active_pane().update(cx, |pane, cx| {
13892                        pane.remove_item(preview_item_id, false, false, window, cx);
13893                    });
13894                }
13895            } else {
13896                workspace.add_item_to_active_pane(item.clone(), None, true, window, cx);
13897            }
13898        }
13899        workspace.active_pane().update(cx, |pane, cx| {
13900            pane.set_preview_item_id(Some(item_id), cx);
13901        });
13902    }
13903
13904    pub fn rename(
13905        &mut self,
13906        _: &Rename,
13907        window: &mut Window,
13908        cx: &mut Context<Self>,
13909    ) -> Option<Task<Result<()>>> {
13910        use language::ToOffset as _;
13911
13912        let provider = self.semantics_provider.clone()?;
13913        let selection = self.selections.newest_anchor().clone();
13914        let (cursor_buffer, cursor_buffer_position) = self
13915            .buffer
13916            .read(cx)
13917            .text_anchor_for_position(selection.head(), cx)?;
13918        let (tail_buffer, cursor_buffer_position_end) = self
13919            .buffer
13920            .read(cx)
13921            .text_anchor_for_position(selection.tail(), cx)?;
13922        if tail_buffer != cursor_buffer {
13923            return None;
13924        }
13925
13926        let snapshot = cursor_buffer.read(cx).snapshot();
13927        let cursor_buffer_offset = cursor_buffer_position.to_offset(&snapshot);
13928        let cursor_buffer_offset_end = cursor_buffer_position_end.to_offset(&snapshot);
13929        let prepare_rename = provider
13930            .range_for_rename(&cursor_buffer, cursor_buffer_position, cx)
13931            .unwrap_or_else(|| Task::ready(Ok(None)));
13932        drop(snapshot);
13933
13934        Some(cx.spawn_in(window, async move |this, cx| {
13935            let rename_range = if let Some(range) = prepare_rename.await? {
13936                Some(range)
13937            } else {
13938                this.update(cx, |this, cx| {
13939                    let buffer = this.buffer.read(cx).snapshot(cx);
13940                    let mut buffer_highlights = this
13941                        .document_highlights_for_position(selection.head(), &buffer)
13942                        .filter(|highlight| {
13943                            highlight.start.excerpt_id == selection.head().excerpt_id
13944                                && highlight.end.excerpt_id == selection.head().excerpt_id
13945                        });
13946                    buffer_highlights
13947                        .next()
13948                        .map(|highlight| highlight.start.text_anchor..highlight.end.text_anchor)
13949                })?
13950            };
13951            if let Some(rename_range) = rename_range {
13952                this.update_in(cx, |this, window, cx| {
13953                    let snapshot = cursor_buffer.read(cx).snapshot();
13954                    let rename_buffer_range = rename_range.to_offset(&snapshot);
13955                    let cursor_offset_in_rename_range =
13956                        cursor_buffer_offset.saturating_sub(rename_buffer_range.start);
13957                    let cursor_offset_in_rename_range_end =
13958                        cursor_buffer_offset_end.saturating_sub(rename_buffer_range.start);
13959
13960                    this.take_rename(false, window, cx);
13961                    let buffer = this.buffer.read(cx).read(cx);
13962                    let cursor_offset = selection.head().to_offset(&buffer);
13963                    let rename_start = cursor_offset.saturating_sub(cursor_offset_in_rename_range);
13964                    let rename_end = rename_start + rename_buffer_range.len();
13965                    let range = buffer.anchor_before(rename_start)..buffer.anchor_after(rename_end);
13966                    let mut old_highlight_id = None;
13967                    let old_name: Arc<str> = buffer
13968                        .chunks(rename_start..rename_end, true)
13969                        .map(|chunk| {
13970                            if old_highlight_id.is_none() {
13971                                old_highlight_id = chunk.syntax_highlight_id;
13972                            }
13973                            chunk.text
13974                        })
13975                        .collect::<String>()
13976                        .into();
13977
13978                    drop(buffer);
13979
13980                    // Position the selection in the rename editor so that it matches the current selection.
13981                    this.show_local_selections = false;
13982                    let rename_editor = cx.new(|cx| {
13983                        let mut editor = Editor::single_line(window, cx);
13984                        editor.buffer.update(cx, |buffer, cx| {
13985                            buffer.edit([(0..0, old_name.clone())], None, cx)
13986                        });
13987                        let rename_selection_range = match cursor_offset_in_rename_range
13988                            .cmp(&cursor_offset_in_rename_range_end)
13989                        {
13990                            Ordering::Equal => {
13991                                editor.select_all(&SelectAll, window, cx);
13992                                return editor;
13993                            }
13994                            Ordering::Less => {
13995                                cursor_offset_in_rename_range..cursor_offset_in_rename_range_end
13996                            }
13997                            Ordering::Greater => {
13998                                cursor_offset_in_rename_range_end..cursor_offset_in_rename_range
13999                            }
14000                        };
14001                        if rename_selection_range.end > old_name.len() {
14002                            editor.select_all(&SelectAll, window, cx);
14003                        } else {
14004                            editor.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
14005                                s.select_ranges([rename_selection_range]);
14006                            });
14007                        }
14008                        editor
14009                    });
14010                    cx.subscribe(&rename_editor, |_, _, e: &EditorEvent, cx| {
14011                        if e == &EditorEvent::Focused {
14012                            cx.emit(EditorEvent::FocusedIn)
14013                        }
14014                    })
14015                    .detach();
14016
14017                    let write_highlights =
14018                        this.clear_background_highlights::<DocumentHighlightWrite>(cx);
14019                    let read_highlights =
14020                        this.clear_background_highlights::<DocumentHighlightRead>(cx);
14021                    let ranges = write_highlights
14022                        .iter()
14023                        .flat_map(|(_, ranges)| ranges.iter())
14024                        .chain(read_highlights.iter().flat_map(|(_, ranges)| ranges.iter()))
14025                        .cloned()
14026                        .collect();
14027
14028                    this.highlight_text::<Rename>(
14029                        ranges,
14030                        HighlightStyle {
14031                            fade_out: Some(0.6),
14032                            ..Default::default()
14033                        },
14034                        cx,
14035                    );
14036                    let rename_focus_handle = rename_editor.focus_handle(cx);
14037                    window.focus(&rename_focus_handle);
14038                    let block_id = this.insert_blocks(
14039                        [BlockProperties {
14040                            style: BlockStyle::Flex,
14041                            placement: BlockPlacement::Below(range.start),
14042                            height: Some(1),
14043                            render: Arc::new({
14044                                let rename_editor = rename_editor.clone();
14045                                move |cx: &mut BlockContext| {
14046                                    let mut text_style = cx.editor_style.text.clone();
14047                                    if let Some(highlight_style) = old_highlight_id
14048                                        .and_then(|h| h.style(&cx.editor_style.syntax))
14049                                    {
14050                                        text_style = text_style.highlight(highlight_style);
14051                                    }
14052                                    div()
14053                                        .block_mouse_down()
14054                                        .pl(cx.anchor_x)
14055                                        .child(EditorElement::new(
14056                                            &rename_editor,
14057                                            EditorStyle {
14058                                                background: cx.theme().system().transparent,
14059                                                local_player: cx.editor_style.local_player,
14060                                                text: text_style,
14061                                                scrollbar_width: cx.editor_style.scrollbar_width,
14062                                                syntax: cx.editor_style.syntax.clone(),
14063                                                status: cx.editor_style.status.clone(),
14064                                                inlay_hints_style: HighlightStyle {
14065                                                    font_weight: Some(FontWeight::BOLD),
14066                                                    ..make_inlay_hints_style(cx.app)
14067                                                },
14068                                                inline_completion_styles: make_suggestion_styles(
14069                                                    cx.app,
14070                                                ),
14071                                                ..EditorStyle::default()
14072                                            },
14073                                        ))
14074                                        .into_any_element()
14075                                }
14076                            }),
14077                            priority: 0,
14078                        }],
14079                        Some(Autoscroll::fit()),
14080                        cx,
14081                    )[0];
14082                    this.pending_rename = Some(RenameState {
14083                        range,
14084                        old_name,
14085                        editor: rename_editor,
14086                        block_id,
14087                    });
14088                })?;
14089            }
14090
14091            Ok(())
14092        }))
14093    }
14094
14095    pub fn confirm_rename(
14096        &mut self,
14097        _: &ConfirmRename,
14098        window: &mut Window,
14099        cx: &mut Context<Self>,
14100    ) -> Option<Task<Result<()>>> {
14101        let rename = self.take_rename(false, window, cx)?;
14102        let workspace = self.workspace()?.downgrade();
14103        let (buffer, start) = self
14104            .buffer
14105            .read(cx)
14106            .text_anchor_for_position(rename.range.start, cx)?;
14107        let (end_buffer, _) = self
14108            .buffer
14109            .read(cx)
14110            .text_anchor_for_position(rename.range.end, cx)?;
14111        if buffer != end_buffer {
14112            return None;
14113        }
14114
14115        let old_name = rename.old_name;
14116        let new_name = rename.editor.read(cx).text(cx);
14117
14118        let rename = self.semantics_provider.as_ref()?.perform_rename(
14119            &buffer,
14120            start,
14121            new_name.clone(),
14122            cx,
14123        )?;
14124
14125        Some(cx.spawn_in(window, async move |editor, cx| {
14126            let project_transaction = rename.await?;
14127            Self::open_project_transaction(
14128                &editor,
14129                workspace,
14130                project_transaction,
14131                format!("Rename: {}{}", old_name, new_name),
14132                cx,
14133            )
14134            .await?;
14135
14136            editor.update(cx, |editor, cx| {
14137                editor.refresh_document_highlights(cx);
14138            })?;
14139            Ok(())
14140        }))
14141    }
14142
14143    fn take_rename(
14144        &mut self,
14145        moving_cursor: bool,
14146        window: &mut Window,
14147        cx: &mut Context<Self>,
14148    ) -> Option<RenameState> {
14149        let rename = self.pending_rename.take()?;
14150        if rename.editor.focus_handle(cx).is_focused(window) {
14151            window.focus(&self.focus_handle);
14152        }
14153
14154        self.remove_blocks(
14155            [rename.block_id].into_iter().collect(),
14156            Some(Autoscroll::fit()),
14157            cx,
14158        );
14159        self.clear_highlights::<Rename>(cx);
14160        self.show_local_selections = true;
14161
14162        if moving_cursor {
14163            let cursor_in_rename_editor = rename.editor.update(cx, |editor, cx| {
14164                editor.selections.newest::<usize>(cx).head()
14165            });
14166
14167            // Update the selection to match the position of the selection inside
14168            // the rename editor.
14169            let snapshot = self.buffer.read(cx).read(cx);
14170            let rename_range = rename.range.to_offset(&snapshot);
14171            let cursor_in_editor = snapshot
14172                .clip_offset(rename_range.start + cursor_in_rename_editor, Bias::Left)
14173                .min(rename_range.end);
14174            drop(snapshot);
14175
14176            self.change_selections(None, window, cx, |s| {
14177                s.select_ranges(vec![cursor_in_editor..cursor_in_editor])
14178            });
14179        } else {
14180            self.refresh_document_highlights(cx);
14181        }
14182
14183        Some(rename)
14184    }
14185
14186    pub fn pending_rename(&self) -> Option<&RenameState> {
14187        self.pending_rename.as_ref()
14188    }
14189
14190    fn format(
14191        &mut self,
14192        _: &Format,
14193        window: &mut Window,
14194        cx: &mut Context<Self>,
14195    ) -> Option<Task<Result<()>>> {
14196        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
14197
14198        let project = match &self.project {
14199            Some(project) => project.clone(),
14200            None => return None,
14201        };
14202
14203        Some(self.perform_format(
14204            project,
14205            FormatTrigger::Manual,
14206            FormatTarget::Buffers,
14207            window,
14208            cx,
14209        ))
14210    }
14211
14212    fn format_selections(
14213        &mut self,
14214        _: &FormatSelections,
14215        window: &mut Window,
14216        cx: &mut Context<Self>,
14217    ) -> Option<Task<Result<()>>> {
14218        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
14219
14220        let project = match &self.project {
14221            Some(project) => project.clone(),
14222            None => return None,
14223        };
14224
14225        let ranges = self
14226            .selections
14227            .all_adjusted(cx)
14228            .into_iter()
14229            .map(|selection| selection.range())
14230            .collect_vec();
14231
14232        Some(self.perform_format(
14233            project,
14234            FormatTrigger::Manual,
14235            FormatTarget::Ranges(ranges),
14236            window,
14237            cx,
14238        ))
14239    }
14240
14241    fn perform_format(
14242        &mut self,
14243        project: Entity<Project>,
14244        trigger: FormatTrigger,
14245        target: FormatTarget,
14246        window: &mut Window,
14247        cx: &mut Context<Self>,
14248    ) -> Task<Result<()>> {
14249        let buffer = self.buffer.clone();
14250        let (buffers, target) = match target {
14251            FormatTarget::Buffers => {
14252                let mut buffers = buffer.read(cx).all_buffers();
14253                if trigger == FormatTrigger::Save {
14254                    buffers.retain(|buffer| buffer.read(cx).is_dirty());
14255                }
14256                (buffers, LspFormatTarget::Buffers)
14257            }
14258            FormatTarget::Ranges(selection_ranges) => {
14259                let multi_buffer = buffer.read(cx);
14260                let snapshot = multi_buffer.read(cx);
14261                let mut buffers = HashSet::default();
14262                let mut buffer_id_to_ranges: BTreeMap<BufferId, Vec<Range<text::Anchor>>> =
14263                    BTreeMap::new();
14264                for selection_range in selection_ranges {
14265                    for (buffer, buffer_range, _) in
14266                        snapshot.range_to_buffer_ranges(selection_range)
14267                    {
14268                        let buffer_id = buffer.remote_id();
14269                        let start = buffer.anchor_before(buffer_range.start);
14270                        let end = buffer.anchor_after(buffer_range.end);
14271                        buffers.insert(multi_buffer.buffer(buffer_id).unwrap());
14272                        buffer_id_to_ranges
14273                            .entry(buffer_id)
14274                            .and_modify(|buffer_ranges| buffer_ranges.push(start..end))
14275                            .or_insert_with(|| vec![start..end]);
14276                    }
14277                }
14278                (buffers, LspFormatTarget::Ranges(buffer_id_to_ranges))
14279            }
14280        };
14281
14282        let transaction_id_prev = buffer.read_with(cx, |b, cx| b.last_transaction_id(cx));
14283        let selections_prev = transaction_id_prev
14284            .and_then(|transaction_id_prev| {
14285                // default to selections as they were after the last edit, if we have them,
14286                // instead of how they are now.
14287                // This will make it so that editing, moving somewhere else, formatting, then undoing the format
14288                // will take you back to where you made the last edit, instead of staying where you scrolled
14289                self.selection_history
14290                    .transaction(transaction_id_prev)
14291                    .map(|t| t.0.clone())
14292            })
14293            .unwrap_or_else(|| {
14294                log::info!("Failed to determine selections from before format. Falling back to selections when format was initiated");
14295                self.selections.disjoint_anchors()
14296            });
14297
14298        let mut timeout = cx.background_executor().timer(FORMAT_TIMEOUT).fuse();
14299        let format = project.update(cx, |project, cx| {
14300            project.format(buffers, target, true, trigger, cx)
14301        });
14302
14303        cx.spawn_in(window, async move |editor, cx| {
14304            let transaction = futures::select_biased! {
14305                transaction = format.log_err().fuse() => transaction,
14306                () = timeout => {
14307                    log::warn!("timed out waiting for formatting");
14308                    None
14309                }
14310            };
14311
14312            buffer
14313                .update(cx, |buffer, cx| {
14314                    if let Some(transaction) = transaction {
14315                        if !buffer.is_singleton() {
14316                            buffer.push_transaction(&transaction.0, cx);
14317                        }
14318                    }
14319                    cx.notify();
14320                })
14321                .ok();
14322
14323            if let Some(transaction_id_now) =
14324                buffer.read_with(cx, |b, cx| b.last_transaction_id(cx))?
14325            {
14326                let has_new_transaction = transaction_id_prev != Some(transaction_id_now);
14327                if has_new_transaction {
14328                    _ = editor.update(cx, |editor, _| {
14329                        editor
14330                            .selection_history
14331                            .insert_transaction(transaction_id_now, selections_prev);
14332                    });
14333                }
14334            }
14335
14336            Ok(())
14337        })
14338    }
14339
14340    fn organize_imports(
14341        &mut self,
14342        _: &OrganizeImports,
14343        window: &mut Window,
14344        cx: &mut Context<Self>,
14345    ) -> Option<Task<Result<()>>> {
14346        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
14347        let project = match &self.project {
14348            Some(project) => project.clone(),
14349            None => return None,
14350        };
14351        Some(self.perform_code_action_kind(
14352            project,
14353            CodeActionKind::SOURCE_ORGANIZE_IMPORTS,
14354            window,
14355            cx,
14356        ))
14357    }
14358
14359    fn perform_code_action_kind(
14360        &mut self,
14361        project: Entity<Project>,
14362        kind: CodeActionKind,
14363        window: &mut Window,
14364        cx: &mut Context<Self>,
14365    ) -> Task<Result<()>> {
14366        let buffer = self.buffer.clone();
14367        let buffers = buffer.read(cx).all_buffers();
14368        let mut timeout = cx.background_executor().timer(CODE_ACTION_TIMEOUT).fuse();
14369        let apply_action = project.update(cx, |project, cx| {
14370            project.apply_code_action_kind(buffers, kind, true, cx)
14371        });
14372        cx.spawn_in(window, async move |_, cx| {
14373            let transaction = futures::select_biased! {
14374                () = timeout => {
14375                    log::warn!("timed out waiting for executing code action");
14376                    None
14377                }
14378                transaction = apply_action.log_err().fuse() => transaction,
14379            };
14380            buffer
14381                .update(cx, |buffer, cx| {
14382                    // check if we need this
14383                    if let Some(transaction) = transaction {
14384                        if !buffer.is_singleton() {
14385                            buffer.push_transaction(&transaction.0, cx);
14386                        }
14387                    }
14388                    cx.notify();
14389                })
14390                .ok();
14391            Ok(())
14392        })
14393    }
14394
14395    fn restart_language_server(
14396        &mut self,
14397        _: &RestartLanguageServer,
14398        _: &mut Window,
14399        cx: &mut Context<Self>,
14400    ) {
14401        if let Some(project) = self.project.clone() {
14402            self.buffer.update(cx, |multi_buffer, cx| {
14403                project.update(cx, |project, cx| {
14404                    project.restart_language_servers_for_buffers(
14405                        multi_buffer.all_buffers().into_iter().collect(),
14406                        cx,
14407                    );
14408                });
14409            })
14410        }
14411    }
14412
14413    fn stop_language_server(
14414        &mut self,
14415        _: &StopLanguageServer,
14416        _: &mut Window,
14417        cx: &mut Context<Self>,
14418    ) {
14419        if let Some(project) = self.project.clone() {
14420            self.buffer.update(cx, |multi_buffer, cx| {
14421                project.update(cx, |project, cx| {
14422                    project.stop_language_servers_for_buffers(
14423                        multi_buffer.all_buffers().into_iter().collect(),
14424                        cx,
14425                    );
14426                    cx.emit(project::Event::RefreshInlayHints);
14427                });
14428            });
14429        }
14430    }
14431
14432    fn cancel_language_server_work(
14433        workspace: &mut Workspace,
14434        _: &actions::CancelLanguageServerWork,
14435        _: &mut Window,
14436        cx: &mut Context<Workspace>,
14437    ) {
14438        let project = workspace.project();
14439        let buffers = workspace
14440            .active_item(cx)
14441            .and_then(|item| item.act_as::<Editor>(cx))
14442            .map_or(HashSet::default(), |editor| {
14443                editor.read(cx).buffer.read(cx).all_buffers()
14444            });
14445        project.update(cx, |project, cx| {
14446            project.cancel_language_server_work_for_buffers(buffers, cx);
14447        });
14448    }
14449
14450    fn show_character_palette(
14451        &mut self,
14452        _: &ShowCharacterPalette,
14453        window: &mut Window,
14454        _: &mut Context<Self>,
14455    ) {
14456        window.show_character_palette();
14457    }
14458
14459    fn refresh_active_diagnostics(&mut self, cx: &mut Context<Editor>) {
14460        if let Some(active_diagnostics) = self.active_diagnostics.as_mut() {
14461            let buffer = self.buffer.read(cx).snapshot(cx);
14462            let primary_range_start = active_diagnostics.primary_range.start.to_offset(&buffer);
14463            let primary_range_end = active_diagnostics.primary_range.end.to_offset(&buffer);
14464            let is_valid = buffer
14465                .diagnostics_in_range::<usize>(primary_range_start..primary_range_end)
14466                .any(|entry| {
14467                    entry.diagnostic.is_primary
14468                        && !entry.range.is_empty()
14469                        && entry.range.start == primary_range_start
14470                        && entry.diagnostic.message == active_diagnostics.primary_message
14471                });
14472
14473            if is_valid != active_diagnostics.is_valid {
14474                active_diagnostics.is_valid = is_valid;
14475                if is_valid {
14476                    let mut new_styles = HashMap::default();
14477                    for (block_id, diagnostic) in &active_diagnostics.blocks {
14478                        new_styles.insert(
14479                            *block_id,
14480                            diagnostic_block_renderer(diagnostic.clone(), None, true),
14481                        );
14482                    }
14483                    self.display_map.update(cx, |display_map, _cx| {
14484                        display_map.replace_blocks(new_styles);
14485                    });
14486                } else {
14487                    self.dismiss_diagnostics(cx);
14488                }
14489            }
14490        }
14491    }
14492
14493    fn activate_diagnostics(
14494        &mut self,
14495        buffer_id: BufferId,
14496        group_id: usize,
14497        window: &mut Window,
14498        cx: &mut Context<Self>,
14499    ) {
14500        self.dismiss_diagnostics(cx);
14501        let snapshot = self.snapshot(window, cx);
14502        self.active_diagnostics = self.display_map.update(cx, |display_map, cx| {
14503            let buffer = self.buffer.read(cx).snapshot(cx);
14504
14505            let mut primary_range = None;
14506            let mut primary_message = None;
14507            let diagnostic_group = buffer
14508                .diagnostic_group(buffer_id, group_id)
14509                .filter_map(|entry| {
14510                    let start = entry.range.start;
14511                    let end = entry.range.end;
14512                    if snapshot.is_line_folded(MultiBufferRow(start.row))
14513                        && (start.row == end.row
14514                            || snapshot.is_line_folded(MultiBufferRow(end.row)))
14515                    {
14516                        return None;
14517                    }
14518                    if entry.diagnostic.is_primary {
14519                        primary_range = Some(entry.range.clone());
14520                        primary_message = Some(entry.diagnostic.message.clone());
14521                    }
14522                    Some(entry)
14523                })
14524                .collect::<Vec<_>>();
14525            let primary_range = primary_range?;
14526            let primary_message = primary_message?;
14527
14528            let blocks = display_map
14529                .insert_blocks(
14530                    diagnostic_group.iter().map(|entry| {
14531                        let diagnostic = entry.diagnostic.clone();
14532                        let message_height = diagnostic.message.matches('\n').count() as u32 + 1;
14533                        BlockProperties {
14534                            style: BlockStyle::Fixed,
14535                            placement: BlockPlacement::Below(
14536                                buffer.anchor_after(entry.range.start),
14537                            ),
14538                            height: Some(message_height),
14539                            render: diagnostic_block_renderer(diagnostic, None, true),
14540                            priority: 0,
14541                        }
14542                    }),
14543                    cx,
14544                )
14545                .into_iter()
14546                .zip(diagnostic_group.into_iter().map(|entry| entry.diagnostic))
14547                .collect();
14548
14549            Some(ActiveDiagnosticGroup {
14550                primary_range: buffer.anchor_before(primary_range.start)
14551                    ..buffer.anchor_after(primary_range.end),
14552                primary_message,
14553                group_id,
14554                blocks,
14555                is_valid: true,
14556            })
14557        });
14558    }
14559
14560    fn dismiss_diagnostics(&mut self, cx: &mut Context<Self>) {
14561        if let Some(active_diagnostic_group) = self.active_diagnostics.take() {
14562            self.display_map.update(cx, |display_map, cx| {
14563                display_map.remove_blocks(active_diagnostic_group.blocks.into_keys().collect(), cx);
14564            });
14565            cx.notify();
14566        }
14567    }
14568
14569    /// Disable inline diagnostics rendering for this editor.
14570    pub fn disable_inline_diagnostics(&mut self) {
14571        self.inline_diagnostics_enabled = false;
14572        self.inline_diagnostics_update = Task::ready(());
14573        self.inline_diagnostics.clear();
14574    }
14575
14576    pub fn inline_diagnostics_enabled(&self) -> bool {
14577        self.inline_diagnostics_enabled
14578    }
14579
14580    pub fn show_inline_diagnostics(&self) -> bool {
14581        self.show_inline_diagnostics
14582    }
14583
14584    pub fn toggle_inline_diagnostics(
14585        &mut self,
14586        _: &ToggleInlineDiagnostics,
14587        window: &mut Window,
14588        cx: &mut Context<Editor>,
14589    ) {
14590        self.show_inline_diagnostics = !self.show_inline_diagnostics;
14591        self.refresh_inline_diagnostics(false, window, cx);
14592    }
14593
14594    fn refresh_inline_diagnostics(
14595        &mut self,
14596        debounce: bool,
14597        window: &mut Window,
14598        cx: &mut Context<Self>,
14599    ) {
14600        if !self.inline_diagnostics_enabled || !self.show_inline_diagnostics {
14601            self.inline_diagnostics_update = Task::ready(());
14602            self.inline_diagnostics.clear();
14603            return;
14604        }
14605
14606        let debounce_ms = ProjectSettings::get_global(cx)
14607            .diagnostics
14608            .inline
14609            .update_debounce_ms;
14610        let debounce = if debounce && debounce_ms > 0 {
14611            Some(Duration::from_millis(debounce_ms))
14612        } else {
14613            None
14614        };
14615        self.inline_diagnostics_update = cx.spawn_in(window, async move |editor, cx| {
14616            if let Some(debounce) = debounce {
14617                cx.background_executor().timer(debounce).await;
14618            }
14619            let Some(snapshot) = editor
14620                .update(cx, |editor, cx| editor.buffer().read(cx).snapshot(cx))
14621                .ok()
14622            else {
14623                return;
14624            };
14625
14626            let new_inline_diagnostics = cx
14627                .background_spawn(async move {
14628                    let mut inline_diagnostics = Vec::<(Anchor, InlineDiagnostic)>::new();
14629                    for diagnostic_entry in snapshot.diagnostics_in_range(0..snapshot.len()) {
14630                        let message = diagnostic_entry
14631                            .diagnostic
14632                            .message
14633                            .split_once('\n')
14634                            .map(|(line, _)| line)
14635                            .map(SharedString::new)
14636                            .unwrap_or_else(|| {
14637                                SharedString::from(diagnostic_entry.diagnostic.message)
14638                            });
14639                        let start_anchor = snapshot.anchor_before(diagnostic_entry.range.start);
14640                        let (Ok(i) | Err(i)) = inline_diagnostics
14641                            .binary_search_by(|(probe, _)| probe.cmp(&start_anchor, &snapshot));
14642                        inline_diagnostics.insert(
14643                            i,
14644                            (
14645                                start_anchor,
14646                                InlineDiagnostic {
14647                                    message,
14648                                    group_id: diagnostic_entry.diagnostic.group_id,
14649                                    start: diagnostic_entry.range.start.to_point(&snapshot),
14650                                    is_primary: diagnostic_entry.diagnostic.is_primary,
14651                                    severity: diagnostic_entry.diagnostic.severity,
14652                                },
14653                            ),
14654                        );
14655                    }
14656                    inline_diagnostics
14657                })
14658                .await;
14659
14660            editor
14661                .update(cx, |editor, cx| {
14662                    editor.inline_diagnostics = new_inline_diagnostics;
14663                    cx.notify();
14664                })
14665                .ok();
14666        });
14667    }
14668
14669    pub fn set_selections_from_remote(
14670        &mut self,
14671        selections: Vec<Selection<Anchor>>,
14672        pending_selection: Option<Selection<Anchor>>,
14673        window: &mut Window,
14674        cx: &mut Context<Self>,
14675    ) {
14676        let old_cursor_position = self.selections.newest_anchor().head();
14677        self.selections.change_with(cx, |s| {
14678            s.select_anchors(selections);
14679            if let Some(pending_selection) = pending_selection {
14680                s.set_pending(pending_selection, SelectMode::Character);
14681            } else {
14682                s.clear_pending();
14683            }
14684        });
14685        self.selections_did_change(false, &old_cursor_position, true, window, cx);
14686    }
14687
14688    fn push_to_selection_history(&mut self) {
14689        self.selection_history.push(SelectionHistoryEntry {
14690            selections: self.selections.disjoint_anchors(),
14691            select_next_state: self.select_next_state.clone(),
14692            select_prev_state: self.select_prev_state.clone(),
14693            add_selections_state: self.add_selections_state.clone(),
14694        });
14695    }
14696
14697    pub fn transact(
14698        &mut self,
14699        window: &mut Window,
14700        cx: &mut Context<Self>,
14701        update: impl FnOnce(&mut Self, &mut Window, &mut Context<Self>),
14702    ) -> Option<TransactionId> {
14703        self.start_transaction_at(Instant::now(), window, cx);
14704        update(self, window, cx);
14705        self.end_transaction_at(Instant::now(), cx)
14706    }
14707
14708    pub fn start_transaction_at(
14709        &mut self,
14710        now: Instant,
14711        window: &mut Window,
14712        cx: &mut Context<Self>,
14713    ) {
14714        self.end_selection(window, cx);
14715        if let Some(tx_id) = self
14716            .buffer
14717            .update(cx, |buffer, cx| buffer.start_transaction_at(now, cx))
14718        {
14719            self.selection_history
14720                .insert_transaction(tx_id, self.selections.disjoint_anchors());
14721            cx.emit(EditorEvent::TransactionBegun {
14722                transaction_id: tx_id,
14723            })
14724        }
14725    }
14726
14727    pub fn end_transaction_at(
14728        &mut self,
14729        now: Instant,
14730        cx: &mut Context<Self>,
14731    ) -> Option<TransactionId> {
14732        if let Some(transaction_id) = self
14733            .buffer
14734            .update(cx, |buffer, cx| buffer.end_transaction_at(now, cx))
14735        {
14736            if let Some((_, end_selections)) =
14737                self.selection_history.transaction_mut(transaction_id)
14738            {
14739                *end_selections = Some(self.selections.disjoint_anchors());
14740            } else {
14741                log::error!("unexpectedly ended a transaction that wasn't started by this editor");
14742            }
14743
14744            cx.emit(EditorEvent::Edited { transaction_id });
14745            Some(transaction_id)
14746        } else {
14747            None
14748        }
14749    }
14750
14751    pub fn set_mark(&mut self, _: &actions::SetMark, window: &mut Window, cx: &mut Context<Self>) {
14752        if self.selection_mark_mode {
14753            self.change_selections(None, window, cx, |s| {
14754                s.move_with(|_, sel| {
14755                    sel.collapse_to(sel.head(), SelectionGoal::None);
14756                });
14757            })
14758        }
14759        self.selection_mark_mode = true;
14760        cx.notify();
14761    }
14762
14763    pub fn swap_selection_ends(
14764        &mut self,
14765        _: &actions::SwapSelectionEnds,
14766        window: &mut Window,
14767        cx: &mut Context<Self>,
14768    ) {
14769        self.change_selections(None, window, cx, |s| {
14770            s.move_with(|_, sel| {
14771                if sel.start != sel.end {
14772                    sel.reversed = !sel.reversed
14773                }
14774            });
14775        });
14776        self.request_autoscroll(Autoscroll::newest(), cx);
14777        cx.notify();
14778    }
14779
14780    pub fn toggle_fold(
14781        &mut self,
14782        _: &actions::ToggleFold,
14783        window: &mut Window,
14784        cx: &mut Context<Self>,
14785    ) {
14786        if self.is_singleton(cx) {
14787            let selection = self.selections.newest::<Point>(cx);
14788
14789            let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
14790            let range = if selection.is_empty() {
14791                let point = selection.head().to_display_point(&display_map);
14792                let start = DisplayPoint::new(point.row(), 0).to_point(&display_map);
14793                let end = DisplayPoint::new(point.row(), display_map.line_len(point.row()))
14794                    .to_point(&display_map);
14795                start..end
14796            } else {
14797                selection.range()
14798            };
14799            if display_map.folds_in_range(range).next().is_some() {
14800                self.unfold_lines(&Default::default(), window, cx)
14801            } else {
14802                self.fold(&Default::default(), window, cx)
14803            }
14804        } else {
14805            let multi_buffer_snapshot = self.buffer.read(cx).snapshot(cx);
14806            let buffer_ids: HashSet<_> = self
14807                .selections
14808                .disjoint_anchor_ranges()
14809                .flat_map(|range| multi_buffer_snapshot.buffer_ids_for_range(range))
14810                .collect();
14811
14812            let should_unfold = buffer_ids
14813                .iter()
14814                .any(|buffer_id| self.is_buffer_folded(*buffer_id, cx));
14815
14816            for buffer_id in buffer_ids {
14817                if should_unfold {
14818                    self.unfold_buffer(buffer_id, cx);
14819                } else {
14820                    self.fold_buffer(buffer_id, cx);
14821                }
14822            }
14823        }
14824    }
14825
14826    pub fn toggle_fold_recursive(
14827        &mut self,
14828        _: &actions::ToggleFoldRecursive,
14829        window: &mut Window,
14830        cx: &mut Context<Self>,
14831    ) {
14832        let selection = self.selections.newest::<Point>(cx);
14833
14834        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
14835        let range = if selection.is_empty() {
14836            let point = selection.head().to_display_point(&display_map);
14837            let start = DisplayPoint::new(point.row(), 0).to_point(&display_map);
14838            let end = DisplayPoint::new(point.row(), display_map.line_len(point.row()))
14839                .to_point(&display_map);
14840            start..end
14841        } else {
14842            selection.range()
14843        };
14844        if display_map.folds_in_range(range).next().is_some() {
14845            self.unfold_recursive(&Default::default(), window, cx)
14846        } else {
14847            self.fold_recursive(&Default::default(), window, cx)
14848        }
14849    }
14850
14851    pub fn fold(&mut self, _: &actions::Fold, window: &mut Window, cx: &mut Context<Self>) {
14852        if self.is_singleton(cx) {
14853            let mut to_fold = Vec::new();
14854            let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
14855            let selections = self.selections.all_adjusted(cx);
14856
14857            for selection in selections {
14858                let range = selection.range().sorted();
14859                let buffer_start_row = range.start.row;
14860
14861                if range.start.row != range.end.row {
14862                    let mut found = false;
14863                    let mut row = range.start.row;
14864                    while row <= range.end.row {
14865                        if let Some(crease) = display_map.crease_for_buffer_row(MultiBufferRow(row))
14866                        {
14867                            found = true;
14868                            row = crease.range().end.row + 1;
14869                            to_fold.push(crease);
14870                        } else {
14871                            row += 1
14872                        }
14873                    }
14874                    if found {
14875                        continue;
14876                    }
14877                }
14878
14879                for row in (0..=range.start.row).rev() {
14880                    if let Some(crease) = display_map.crease_for_buffer_row(MultiBufferRow(row)) {
14881                        if crease.range().end.row >= buffer_start_row {
14882                            to_fold.push(crease);
14883                            if row <= range.start.row {
14884                                break;
14885                            }
14886                        }
14887                    }
14888                }
14889            }
14890
14891            self.fold_creases(to_fold, true, window, cx);
14892        } else {
14893            let multi_buffer_snapshot = self.buffer.read(cx).snapshot(cx);
14894            let buffer_ids = self
14895                .selections
14896                .disjoint_anchor_ranges()
14897                .flat_map(|range| multi_buffer_snapshot.buffer_ids_for_range(range))
14898                .collect::<HashSet<_>>();
14899            for buffer_id in buffer_ids {
14900                self.fold_buffer(buffer_id, cx);
14901            }
14902        }
14903    }
14904
14905    fn fold_at_level(
14906        &mut self,
14907        fold_at: &FoldAtLevel,
14908        window: &mut Window,
14909        cx: &mut Context<Self>,
14910    ) {
14911        if !self.buffer.read(cx).is_singleton() {
14912            return;
14913        }
14914
14915        let fold_at_level = fold_at.0;
14916        let snapshot = self.buffer.read(cx).snapshot(cx);
14917        let mut to_fold = Vec::new();
14918        let mut stack = vec![(0, snapshot.max_row().0, 1)];
14919
14920        while let Some((mut start_row, end_row, current_level)) = stack.pop() {
14921            while start_row < end_row {
14922                match self
14923                    .snapshot(window, cx)
14924                    .crease_for_buffer_row(MultiBufferRow(start_row))
14925                {
14926                    Some(crease) => {
14927                        let nested_start_row = crease.range().start.row + 1;
14928                        let nested_end_row = crease.range().end.row;
14929
14930                        if current_level < fold_at_level {
14931                            stack.push((nested_start_row, nested_end_row, current_level + 1));
14932                        } else if current_level == fold_at_level {
14933                            to_fold.push(crease);
14934                        }
14935
14936                        start_row = nested_end_row + 1;
14937                    }
14938                    None => start_row += 1,
14939                }
14940            }
14941        }
14942
14943        self.fold_creases(to_fold, true, window, cx);
14944    }
14945
14946    pub fn fold_all(&mut self, _: &actions::FoldAll, window: &mut Window, cx: &mut Context<Self>) {
14947        if self.buffer.read(cx).is_singleton() {
14948            let mut fold_ranges = Vec::new();
14949            let snapshot = self.buffer.read(cx).snapshot(cx);
14950
14951            for row in 0..snapshot.max_row().0 {
14952                if let Some(foldable_range) = self
14953                    .snapshot(window, cx)
14954                    .crease_for_buffer_row(MultiBufferRow(row))
14955                {
14956                    fold_ranges.push(foldable_range);
14957                }
14958            }
14959
14960            self.fold_creases(fold_ranges, true, window, cx);
14961        } else {
14962            self.toggle_fold_multiple_buffers = cx.spawn_in(window, async move |editor, cx| {
14963                editor
14964                    .update_in(cx, |editor, _, cx| {
14965                        for buffer_id in editor.buffer.read(cx).excerpt_buffer_ids() {
14966                            editor.fold_buffer(buffer_id, cx);
14967                        }
14968                    })
14969                    .ok();
14970            });
14971        }
14972    }
14973
14974    pub fn fold_function_bodies(
14975        &mut self,
14976        _: &actions::FoldFunctionBodies,
14977        window: &mut Window,
14978        cx: &mut Context<Self>,
14979    ) {
14980        let snapshot = self.buffer.read(cx).snapshot(cx);
14981
14982        let ranges = snapshot
14983            .text_object_ranges(0..snapshot.len(), TreeSitterOptions::default())
14984            .filter_map(|(range, obj)| (obj == TextObject::InsideFunction).then_some(range))
14985            .collect::<Vec<_>>();
14986
14987        let creases = ranges
14988            .into_iter()
14989            .map(|range| Crease::simple(range, self.display_map.read(cx).fold_placeholder.clone()))
14990            .collect();
14991
14992        self.fold_creases(creases, true, window, cx);
14993    }
14994
14995    pub fn fold_recursive(
14996        &mut self,
14997        _: &actions::FoldRecursive,
14998        window: &mut Window,
14999        cx: &mut Context<Self>,
15000    ) {
15001        let mut to_fold = Vec::new();
15002        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
15003        let selections = self.selections.all_adjusted(cx);
15004
15005        for selection in selections {
15006            let range = selection.range().sorted();
15007            let buffer_start_row = range.start.row;
15008
15009            if range.start.row != range.end.row {
15010                let mut found = false;
15011                for row in range.start.row..=range.end.row {
15012                    if let Some(crease) = display_map.crease_for_buffer_row(MultiBufferRow(row)) {
15013                        found = true;
15014                        to_fold.push(crease);
15015                    }
15016                }
15017                if found {
15018                    continue;
15019                }
15020            }
15021
15022            for row in (0..=range.start.row).rev() {
15023                if let Some(crease) = display_map.crease_for_buffer_row(MultiBufferRow(row)) {
15024                    if crease.range().end.row >= buffer_start_row {
15025                        to_fold.push(crease);
15026                    } else {
15027                        break;
15028                    }
15029                }
15030            }
15031        }
15032
15033        self.fold_creases(to_fold, true, window, cx);
15034    }
15035
15036    pub fn fold_at(
15037        &mut self,
15038        buffer_row: MultiBufferRow,
15039        window: &mut Window,
15040        cx: &mut Context<Self>,
15041    ) {
15042        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
15043
15044        if let Some(crease) = display_map.crease_for_buffer_row(buffer_row) {
15045            let autoscroll = self
15046                .selections
15047                .all::<Point>(cx)
15048                .iter()
15049                .any(|selection| crease.range().overlaps(&selection.range()));
15050
15051            self.fold_creases(vec![crease], autoscroll, window, cx);
15052        }
15053    }
15054
15055    pub fn unfold_lines(&mut self, _: &UnfoldLines, _window: &mut Window, cx: &mut Context<Self>) {
15056        if self.is_singleton(cx) {
15057            let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
15058            let buffer = &display_map.buffer_snapshot;
15059            let selections = self.selections.all::<Point>(cx);
15060            let ranges = selections
15061                .iter()
15062                .map(|s| {
15063                    let range = s.display_range(&display_map).sorted();
15064                    let mut start = range.start.to_point(&display_map);
15065                    let mut end = range.end.to_point(&display_map);
15066                    start.column = 0;
15067                    end.column = buffer.line_len(MultiBufferRow(end.row));
15068                    start..end
15069                })
15070                .collect::<Vec<_>>();
15071
15072            self.unfold_ranges(&ranges, true, true, cx);
15073        } else {
15074            let multi_buffer_snapshot = self.buffer.read(cx).snapshot(cx);
15075            let buffer_ids = self
15076                .selections
15077                .disjoint_anchor_ranges()
15078                .flat_map(|range| multi_buffer_snapshot.buffer_ids_for_range(range))
15079                .collect::<HashSet<_>>();
15080            for buffer_id in buffer_ids {
15081                self.unfold_buffer(buffer_id, cx);
15082            }
15083        }
15084    }
15085
15086    pub fn unfold_recursive(
15087        &mut self,
15088        _: &UnfoldRecursive,
15089        _window: &mut Window,
15090        cx: &mut Context<Self>,
15091    ) {
15092        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
15093        let selections = self.selections.all::<Point>(cx);
15094        let ranges = selections
15095            .iter()
15096            .map(|s| {
15097                let mut range = s.display_range(&display_map).sorted();
15098                *range.start.column_mut() = 0;
15099                *range.end.column_mut() = display_map.line_len(range.end.row());
15100                let start = range.start.to_point(&display_map);
15101                let end = range.end.to_point(&display_map);
15102                start..end
15103            })
15104            .collect::<Vec<_>>();
15105
15106        self.unfold_ranges(&ranges, true, true, cx);
15107    }
15108
15109    pub fn unfold_at(
15110        &mut self,
15111        buffer_row: MultiBufferRow,
15112        _window: &mut Window,
15113        cx: &mut Context<Self>,
15114    ) {
15115        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
15116
15117        let intersection_range = Point::new(buffer_row.0, 0)
15118            ..Point::new(
15119                buffer_row.0,
15120                display_map.buffer_snapshot.line_len(buffer_row),
15121            );
15122
15123        let autoscroll = self
15124            .selections
15125            .all::<Point>(cx)
15126            .iter()
15127            .any(|selection| RangeExt::overlaps(&selection.range(), &intersection_range));
15128
15129        self.unfold_ranges(&[intersection_range], true, autoscroll, cx);
15130    }
15131
15132    pub fn unfold_all(
15133        &mut self,
15134        _: &actions::UnfoldAll,
15135        _window: &mut Window,
15136        cx: &mut Context<Self>,
15137    ) {
15138        if self.buffer.read(cx).is_singleton() {
15139            let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
15140            self.unfold_ranges(&[0..display_map.buffer_snapshot.len()], true, true, cx);
15141        } else {
15142            self.toggle_fold_multiple_buffers = cx.spawn(async move |editor, cx| {
15143                editor
15144                    .update(cx, |editor, cx| {
15145                        for buffer_id in editor.buffer.read(cx).excerpt_buffer_ids() {
15146                            editor.unfold_buffer(buffer_id, cx);
15147                        }
15148                    })
15149                    .ok();
15150            });
15151        }
15152    }
15153
15154    pub fn fold_selected_ranges(
15155        &mut self,
15156        _: &FoldSelectedRanges,
15157        window: &mut Window,
15158        cx: &mut Context<Self>,
15159    ) {
15160        let selections = self.selections.all_adjusted(cx);
15161        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
15162        let ranges = selections
15163            .into_iter()
15164            .map(|s| Crease::simple(s.range(), display_map.fold_placeholder.clone()))
15165            .collect::<Vec<_>>();
15166        self.fold_creases(ranges, true, window, cx);
15167    }
15168
15169    pub fn fold_ranges<T: ToOffset + Clone>(
15170        &mut self,
15171        ranges: Vec<Range<T>>,
15172        auto_scroll: bool,
15173        window: &mut Window,
15174        cx: &mut Context<Self>,
15175    ) {
15176        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
15177        let ranges = ranges
15178            .into_iter()
15179            .map(|r| Crease::simple(r, display_map.fold_placeholder.clone()))
15180            .collect::<Vec<_>>();
15181        self.fold_creases(ranges, auto_scroll, window, cx);
15182    }
15183
15184    pub fn fold_creases<T: ToOffset + Clone>(
15185        &mut self,
15186        creases: Vec<Crease<T>>,
15187        auto_scroll: bool,
15188        window: &mut Window,
15189        cx: &mut Context<Self>,
15190    ) {
15191        if creases.is_empty() {
15192            return;
15193        }
15194
15195        let mut buffers_affected = HashSet::default();
15196        let multi_buffer = self.buffer().read(cx);
15197        for crease in &creases {
15198            if let Some((_, buffer, _)) =
15199                multi_buffer.excerpt_containing(crease.range().start.clone(), cx)
15200            {
15201                buffers_affected.insert(buffer.read(cx).remote_id());
15202            };
15203        }
15204
15205        self.display_map.update(cx, |map, cx| map.fold(creases, cx));
15206
15207        if auto_scroll {
15208            self.request_autoscroll(Autoscroll::fit(), cx);
15209        }
15210
15211        cx.notify();
15212
15213        if let Some(active_diagnostics) = self.active_diagnostics.take() {
15214            // Clear diagnostics block when folding a range that contains it.
15215            let snapshot = self.snapshot(window, cx);
15216            if snapshot.intersects_fold(active_diagnostics.primary_range.start) {
15217                drop(snapshot);
15218                self.active_diagnostics = Some(active_diagnostics);
15219                self.dismiss_diagnostics(cx);
15220            } else {
15221                self.active_diagnostics = Some(active_diagnostics);
15222            }
15223        }
15224
15225        self.scrollbar_marker_state.dirty = true;
15226        self.folds_did_change(cx);
15227    }
15228
15229    /// Removes any folds whose ranges intersect any of the given ranges.
15230    pub fn unfold_ranges<T: ToOffset + Clone>(
15231        &mut self,
15232        ranges: &[Range<T>],
15233        inclusive: bool,
15234        auto_scroll: bool,
15235        cx: &mut Context<Self>,
15236    ) {
15237        self.remove_folds_with(ranges, auto_scroll, cx, |map, cx| {
15238            map.unfold_intersecting(ranges.iter().cloned(), inclusive, cx)
15239        });
15240        self.folds_did_change(cx);
15241    }
15242
15243    pub fn fold_buffer(&mut self, buffer_id: BufferId, cx: &mut Context<Self>) {
15244        if self.buffer().read(cx).is_singleton() || self.is_buffer_folded(buffer_id, cx) {
15245            return;
15246        }
15247        let folded_excerpts = self.buffer().read(cx).excerpts_for_buffer(buffer_id, cx);
15248        self.display_map.update(cx, |display_map, cx| {
15249            display_map.fold_buffers([buffer_id], cx)
15250        });
15251        cx.emit(EditorEvent::BufferFoldToggled {
15252            ids: folded_excerpts.iter().map(|&(id, _)| id).collect(),
15253            folded: true,
15254        });
15255        cx.notify();
15256    }
15257
15258    pub fn unfold_buffer(&mut self, buffer_id: BufferId, cx: &mut Context<Self>) {
15259        if self.buffer().read(cx).is_singleton() || !self.is_buffer_folded(buffer_id, cx) {
15260            return;
15261        }
15262        let unfolded_excerpts = self.buffer().read(cx).excerpts_for_buffer(buffer_id, cx);
15263        self.display_map.update(cx, |display_map, cx| {
15264            display_map.unfold_buffers([buffer_id], cx);
15265        });
15266        cx.emit(EditorEvent::BufferFoldToggled {
15267            ids: unfolded_excerpts.iter().map(|&(id, _)| id).collect(),
15268            folded: false,
15269        });
15270        cx.notify();
15271    }
15272
15273    pub fn is_buffer_folded(&self, buffer: BufferId, cx: &App) -> bool {
15274        self.display_map.read(cx).is_buffer_folded(buffer)
15275    }
15276
15277    pub fn folded_buffers<'a>(&self, cx: &'a App) -> &'a HashSet<BufferId> {
15278        self.display_map.read(cx).folded_buffers()
15279    }
15280
15281    pub fn disable_header_for_buffer(&mut self, buffer_id: BufferId, cx: &mut Context<Self>) {
15282        self.display_map.update(cx, |display_map, cx| {
15283            display_map.disable_header_for_buffer(buffer_id, cx);
15284        });
15285        cx.notify();
15286    }
15287
15288    /// Removes any folds with the given ranges.
15289    pub fn remove_folds_with_type<T: ToOffset + Clone>(
15290        &mut self,
15291        ranges: &[Range<T>],
15292        type_id: TypeId,
15293        auto_scroll: bool,
15294        cx: &mut Context<Self>,
15295    ) {
15296        self.remove_folds_with(ranges, auto_scroll, cx, |map, cx| {
15297            map.remove_folds_with_type(ranges.iter().cloned(), type_id, cx)
15298        });
15299        self.folds_did_change(cx);
15300    }
15301
15302    fn remove_folds_with<T: ToOffset + Clone>(
15303        &mut self,
15304        ranges: &[Range<T>],
15305        auto_scroll: bool,
15306        cx: &mut Context<Self>,
15307        update: impl FnOnce(&mut DisplayMap, &mut Context<DisplayMap>),
15308    ) {
15309        if ranges.is_empty() {
15310            return;
15311        }
15312
15313        let mut buffers_affected = HashSet::default();
15314        let multi_buffer = self.buffer().read(cx);
15315        for range in ranges {
15316            if let Some((_, buffer, _)) = multi_buffer.excerpt_containing(range.start.clone(), cx) {
15317                buffers_affected.insert(buffer.read(cx).remote_id());
15318            };
15319        }
15320
15321        self.display_map.update(cx, update);
15322
15323        if auto_scroll {
15324            self.request_autoscroll(Autoscroll::fit(), cx);
15325        }
15326
15327        cx.notify();
15328        self.scrollbar_marker_state.dirty = true;
15329        self.active_indent_guides_state.dirty = true;
15330    }
15331
15332    pub fn update_fold_widths(
15333        &mut self,
15334        widths: impl IntoIterator<Item = (FoldId, Pixels)>,
15335        cx: &mut Context<Self>,
15336    ) -> bool {
15337        self.display_map
15338            .update(cx, |map, cx| map.update_fold_widths(widths, cx))
15339    }
15340
15341    pub fn default_fold_placeholder(&self, cx: &App) -> FoldPlaceholder {
15342        self.display_map.read(cx).fold_placeholder.clone()
15343    }
15344
15345    pub fn set_expand_all_diff_hunks(&mut self, cx: &mut App) {
15346        self.buffer.update(cx, |buffer, cx| {
15347            buffer.set_all_diff_hunks_expanded(cx);
15348        });
15349    }
15350
15351    pub fn expand_all_diff_hunks(
15352        &mut self,
15353        _: &ExpandAllDiffHunks,
15354        _window: &mut Window,
15355        cx: &mut Context<Self>,
15356    ) {
15357        self.buffer.update(cx, |buffer, cx| {
15358            buffer.expand_diff_hunks(vec![Anchor::min()..Anchor::max()], cx)
15359        });
15360    }
15361
15362    pub fn toggle_selected_diff_hunks(
15363        &mut self,
15364        _: &ToggleSelectedDiffHunks,
15365        _window: &mut Window,
15366        cx: &mut Context<Self>,
15367    ) {
15368        let ranges: Vec<_> = self.selections.disjoint.iter().map(|s| s.range()).collect();
15369        self.toggle_diff_hunks_in_ranges(ranges, cx);
15370    }
15371
15372    pub fn diff_hunks_in_ranges<'a>(
15373        &'a self,
15374        ranges: &'a [Range<Anchor>],
15375        buffer: &'a MultiBufferSnapshot,
15376    ) -> impl 'a + Iterator<Item = MultiBufferDiffHunk> {
15377        ranges.iter().flat_map(move |range| {
15378            let end_excerpt_id = range.end.excerpt_id;
15379            let range = range.to_point(buffer);
15380            let mut peek_end = range.end;
15381            if range.end.row < buffer.max_row().0 {
15382                peek_end = Point::new(range.end.row + 1, 0);
15383            }
15384            buffer
15385                .diff_hunks_in_range(range.start..peek_end)
15386                .filter(move |hunk| hunk.excerpt_id.cmp(&end_excerpt_id, buffer).is_le())
15387        })
15388    }
15389
15390    pub fn has_stageable_diff_hunks_in_ranges(
15391        &self,
15392        ranges: &[Range<Anchor>],
15393        snapshot: &MultiBufferSnapshot,
15394    ) -> bool {
15395        let mut hunks = self.diff_hunks_in_ranges(ranges, &snapshot);
15396        hunks.any(|hunk| hunk.status().has_secondary_hunk())
15397    }
15398
15399    pub fn toggle_staged_selected_diff_hunks(
15400        &mut self,
15401        _: &::git::ToggleStaged,
15402        _: &mut Window,
15403        cx: &mut Context<Self>,
15404    ) {
15405        let snapshot = self.buffer.read(cx).snapshot(cx);
15406        let ranges: Vec<_> = self.selections.disjoint.iter().map(|s| s.range()).collect();
15407        let stage = self.has_stageable_diff_hunks_in_ranges(&ranges, &snapshot);
15408        self.stage_or_unstage_diff_hunks(stage, ranges, cx);
15409    }
15410
15411    pub fn set_render_diff_hunk_controls(
15412        &mut self,
15413        render_diff_hunk_controls: RenderDiffHunkControlsFn,
15414        cx: &mut Context<Self>,
15415    ) {
15416        self.render_diff_hunk_controls = render_diff_hunk_controls;
15417        cx.notify();
15418    }
15419
15420    pub fn stage_and_next(
15421        &mut self,
15422        _: &::git::StageAndNext,
15423        window: &mut Window,
15424        cx: &mut Context<Self>,
15425    ) {
15426        self.do_stage_or_unstage_and_next(true, window, cx);
15427    }
15428
15429    pub fn unstage_and_next(
15430        &mut self,
15431        _: &::git::UnstageAndNext,
15432        window: &mut Window,
15433        cx: &mut Context<Self>,
15434    ) {
15435        self.do_stage_or_unstage_and_next(false, window, cx);
15436    }
15437
15438    pub fn stage_or_unstage_diff_hunks(
15439        &mut self,
15440        stage: bool,
15441        ranges: Vec<Range<Anchor>>,
15442        cx: &mut Context<Self>,
15443    ) {
15444        let task = self.save_buffers_for_ranges_if_needed(&ranges, cx);
15445        cx.spawn(async move |this, cx| {
15446            task.await?;
15447            this.update(cx, |this, cx| {
15448                let snapshot = this.buffer.read(cx).snapshot(cx);
15449                let chunk_by = this
15450                    .diff_hunks_in_ranges(&ranges, &snapshot)
15451                    .chunk_by(|hunk| hunk.buffer_id);
15452                for (buffer_id, hunks) in &chunk_by {
15453                    this.do_stage_or_unstage(stage, buffer_id, hunks, cx);
15454                }
15455            })
15456        })
15457        .detach_and_log_err(cx);
15458    }
15459
15460    fn save_buffers_for_ranges_if_needed(
15461        &mut self,
15462        ranges: &[Range<Anchor>],
15463        cx: &mut Context<Editor>,
15464    ) -> Task<Result<()>> {
15465        let multibuffer = self.buffer.read(cx);
15466        let snapshot = multibuffer.read(cx);
15467        let buffer_ids: HashSet<_> = ranges
15468            .iter()
15469            .flat_map(|range| snapshot.buffer_ids_for_range(range.clone()))
15470            .collect();
15471        drop(snapshot);
15472
15473        let mut buffers = HashSet::default();
15474        for buffer_id in buffer_ids {
15475            if let Some(buffer_entity) = multibuffer.buffer(buffer_id) {
15476                let buffer = buffer_entity.read(cx);
15477                if buffer.file().is_some_and(|file| file.disk_state().exists()) && buffer.is_dirty()
15478                {
15479                    buffers.insert(buffer_entity);
15480                }
15481            }
15482        }
15483
15484        if let Some(project) = &self.project {
15485            project.update(cx, |project, cx| project.save_buffers(buffers, cx))
15486        } else {
15487            Task::ready(Ok(()))
15488        }
15489    }
15490
15491    fn do_stage_or_unstage_and_next(
15492        &mut self,
15493        stage: bool,
15494        window: &mut Window,
15495        cx: &mut Context<Self>,
15496    ) {
15497        let ranges = self.selections.disjoint_anchor_ranges().collect::<Vec<_>>();
15498
15499        if ranges.iter().any(|range| range.start != range.end) {
15500            self.stage_or_unstage_diff_hunks(stage, ranges, cx);
15501            return;
15502        }
15503
15504        self.stage_or_unstage_diff_hunks(stage, ranges, cx);
15505        let snapshot = self.snapshot(window, cx);
15506        let position = self.selections.newest::<Point>(cx).head();
15507        let mut row = snapshot
15508            .buffer_snapshot
15509            .diff_hunks_in_range(position..snapshot.buffer_snapshot.max_point())
15510            .find(|hunk| hunk.row_range.start.0 > position.row)
15511            .map(|hunk| hunk.row_range.start);
15512
15513        let all_diff_hunks_expanded = self.buffer().read(cx).all_diff_hunks_expanded();
15514        // Outside of the project diff editor, wrap around to the beginning.
15515        if !all_diff_hunks_expanded {
15516            row = row.or_else(|| {
15517                snapshot
15518                    .buffer_snapshot
15519                    .diff_hunks_in_range(Point::zero()..position)
15520                    .find(|hunk| hunk.row_range.end.0 < position.row)
15521                    .map(|hunk| hunk.row_range.start)
15522            });
15523        }
15524
15525        if let Some(row) = row {
15526            let destination = Point::new(row.0, 0);
15527            let autoscroll = Autoscroll::center();
15528
15529            self.unfold_ranges(&[destination..destination], false, false, cx);
15530            self.change_selections(Some(autoscroll), window, cx, |s| {
15531                s.select_ranges([destination..destination]);
15532            });
15533        }
15534    }
15535
15536    fn do_stage_or_unstage(
15537        &self,
15538        stage: bool,
15539        buffer_id: BufferId,
15540        hunks: impl Iterator<Item = MultiBufferDiffHunk>,
15541        cx: &mut App,
15542    ) -> Option<()> {
15543        let project = self.project.as_ref()?;
15544        let buffer = project.read(cx).buffer_for_id(buffer_id, cx)?;
15545        let diff = self.buffer.read(cx).diff_for(buffer_id)?;
15546        let buffer_snapshot = buffer.read(cx).snapshot();
15547        let file_exists = buffer_snapshot
15548            .file()
15549            .is_some_and(|file| file.disk_state().exists());
15550        diff.update(cx, |diff, cx| {
15551            diff.stage_or_unstage_hunks(
15552                stage,
15553                &hunks
15554                    .map(|hunk| buffer_diff::DiffHunk {
15555                        buffer_range: hunk.buffer_range,
15556                        diff_base_byte_range: hunk.diff_base_byte_range,
15557                        secondary_status: hunk.secondary_status,
15558                        range: Point::zero()..Point::zero(), // unused
15559                    })
15560                    .collect::<Vec<_>>(),
15561                &buffer_snapshot,
15562                file_exists,
15563                cx,
15564            )
15565        });
15566        None
15567    }
15568
15569    pub fn expand_selected_diff_hunks(&mut self, cx: &mut Context<Self>) {
15570        let ranges: Vec<_> = self.selections.disjoint.iter().map(|s| s.range()).collect();
15571        self.buffer
15572            .update(cx, |buffer, cx| buffer.expand_diff_hunks(ranges, cx))
15573    }
15574
15575    pub fn clear_expanded_diff_hunks(&mut self, cx: &mut Context<Self>) -> bool {
15576        self.buffer.update(cx, |buffer, cx| {
15577            let ranges = vec![Anchor::min()..Anchor::max()];
15578            if !buffer.all_diff_hunks_expanded()
15579                && buffer.has_expanded_diff_hunks_in_ranges(&ranges, cx)
15580            {
15581                buffer.collapse_diff_hunks(ranges, cx);
15582                true
15583            } else {
15584                false
15585            }
15586        })
15587    }
15588
15589    fn toggle_diff_hunks_in_ranges(
15590        &mut self,
15591        ranges: Vec<Range<Anchor>>,
15592        cx: &mut Context<Editor>,
15593    ) {
15594        self.buffer.update(cx, |buffer, cx| {
15595            let expand = !buffer.has_expanded_diff_hunks_in_ranges(&ranges, cx);
15596            buffer.expand_or_collapse_diff_hunks(ranges, expand, cx);
15597        })
15598    }
15599
15600    fn toggle_single_diff_hunk(&mut self, range: Range<Anchor>, cx: &mut Context<Self>) {
15601        self.buffer.update(cx, |buffer, cx| {
15602            let snapshot = buffer.snapshot(cx);
15603            let excerpt_id = range.end.excerpt_id;
15604            let point_range = range.to_point(&snapshot);
15605            let expand = !buffer.single_hunk_is_expanded(range, cx);
15606            buffer.expand_or_collapse_diff_hunks_inner([(point_range, excerpt_id)], expand, cx);
15607        })
15608    }
15609
15610    pub(crate) fn apply_all_diff_hunks(
15611        &mut self,
15612        _: &ApplyAllDiffHunks,
15613        window: &mut Window,
15614        cx: &mut Context<Self>,
15615    ) {
15616        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
15617
15618        let buffers = self.buffer.read(cx).all_buffers();
15619        for branch_buffer in buffers {
15620            branch_buffer.update(cx, |branch_buffer, cx| {
15621                branch_buffer.merge_into_base(Vec::new(), cx);
15622            });
15623        }
15624
15625        if let Some(project) = self.project.clone() {
15626            self.save(true, project, window, cx).detach_and_log_err(cx);
15627        }
15628    }
15629
15630    pub(crate) fn apply_selected_diff_hunks(
15631        &mut self,
15632        _: &ApplyDiffHunk,
15633        window: &mut Window,
15634        cx: &mut Context<Self>,
15635    ) {
15636        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
15637        let snapshot = self.snapshot(window, cx);
15638        let hunks = snapshot.hunks_for_ranges(self.selections.ranges(cx));
15639        let mut ranges_by_buffer = HashMap::default();
15640        self.transact(window, cx, |editor, _window, cx| {
15641            for hunk in hunks {
15642                if let Some(buffer) = editor.buffer.read(cx).buffer(hunk.buffer_id) {
15643                    ranges_by_buffer
15644                        .entry(buffer.clone())
15645                        .or_insert_with(Vec::new)
15646                        .push(hunk.buffer_range.to_offset(buffer.read(cx)));
15647                }
15648            }
15649
15650            for (buffer, ranges) in ranges_by_buffer {
15651                buffer.update(cx, |buffer, cx| {
15652                    buffer.merge_into_base(ranges, cx);
15653                });
15654            }
15655        });
15656
15657        if let Some(project) = self.project.clone() {
15658            self.save(true, project, window, cx).detach_and_log_err(cx);
15659        }
15660    }
15661
15662    pub fn set_gutter_hovered(&mut self, hovered: bool, cx: &mut Context<Self>) {
15663        if hovered != self.gutter_hovered {
15664            self.gutter_hovered = hovered;
15665            cx.notify();
15666        }
15667    }
15668
15669    pub fn insert_blocks(
15670        &mut self,
15671        blocks: impl IntoIterator<Item = BlockProperties<Anchor>>,
15672        autoscroll: Option<Autoscroll>,
15673        cx: &mut Context<Self>,
15674    ) -> Vec<CustomBlockId> {
15675        let blocks = self
15676            .display_map
15677            .update(cx, |display_map, cx| display_map.insert_blocks(blocks, cx));
15678        if let Some(autoscroll) = autoscroll {
15679            self.request_autoscroll(autoscroll, cx);
15680        }
15681        cx.notify();
15682        blocks
15683    }
15684
15685    pub fn resize_blocks(
15686        &mut self,
15687        heights: HashMap<CustomBlockId, u32>,
15688        autoscroll: Option<Autoscroll>,
15689        cx: &mut Context<Self>,
15690    ) {
15691        self.display_map
15692            .update(cx, |display_map, cx| display_map.resize_blocks(heights, cx));
15693        if let Some(autoscroll) = autoscroll {
15694            self.request_autoscroll(autoscroll, cx);
15695        }
15696        cx.notify();
15697    }
15698
15699    pub fn replace_blocks(
15700        &mut self,
15701        renderers: HashMap<CustomBlockId, RenderBlock>,
15702        autoscroll: Option<Autoscroll>,
15703        cx: &mut Context<Self>,
15704    ) {
15705        self.display_map
15706            .update(cx, |display_map, _cx| display_map.replace_blocks(renderers));
15707        if let Some(autoscroll) = autoscroll {
15708            self.request_autoscroll(autoscroll, cx);
15709        }
15710        cx.notify();
15711    }
15712
15713    pub fn remove_blocks(
15714        &mut self,
15715        block_ids: HashSet<CustomBlockId>,
15716        autoscroll: Option<Autoscroll>,
15717        cx: &mut Context<Self>,
15718    ) {
15719        self.display_map.update(cx, |display_map, cx| {
15720            display_map.remove_blocks(block_ids, cx)
15721        });
15722        if let Some(autoscroll) = autoscroll {
15723            self.request_autoscroll(autoscroll, cx);
15724        }
15725        cx.notify();
15726    }
15727
15728    pub fn row_for_block(
15729        &self,
15730        block_id: CustomBlockId,
15731        cx: &mut Context<Self>,
15732    ) -> Option<DisplayRow> {
15733        self.display_map
15734            .update(cx, |map, cx| map.row_for_block(block_id, cx))
15735    }
15736
15737    pub(crate) fn set_focused_block(&mut self, focused_block: FocusedBlock) {
15738        self.focused_block = Some(focused_block);
15739    }
15740
15741    pub(crate) fn take_focused_block(&mut self) -> Option<FocusedBlock> {
15742        self.focused_block.take()
15743    }
15744
15745    pub fn insert_creases(
15746        &mut self,
15747        creases: impl IntoIterator<Item = Crease<Anchor>>,
15748        cx: &mut Context<Self>,
15749    ) -> Vec<CreaseId> {
15750        self.display_map
15751            .update(cx, |map, cx| map.insert_creases(creases, cx))
15752    }
15753
15754    pub fn remove_creases(
15755        &mut self,
15756        ids: impl IntoIterator<Item = CreaseId>,
15757        cx: &mut Context<Self>,
15758    ) {
15759        self.display_map
15760            .update(cx, |map, cx| map.remove_creases(ids, cx));
15761    }
15762
15763    pub fn longest_row(&self, cx: &mut App) -> DisplayRow {
15764        self.display_map
15765            .update(cx, |map, cx| map.snapshot(cx))
15766            .longest_row()
15767    }
15768
15769    pub fn max_point(&self, cx: &mut App) -> DisplayPoint {
15770        self.display_map
15771            .update(cx, |map, cx| map.snapshot(cx))
15772            .max_point()
15773    }
15774
15775    pub fn text(&self, cx: &App) -> String {
15776        self.buffer.read(cx).read(cx).text()
15777    }
15778
15779    pub fn is_empty(&self, cx: &App) -> bool {
15780        self.buffer.read(cx).read(cx).is_empty()
15781    }
15782
15783    pub fn text_option(&self, cx: &App) -> Option<String> {
15784        let text = self.text(cx);
15785        let text = text.trim();
15786
15787        if text.is_empty() {
15788            return None;
15789        }
15790
15791        Some(text.to_string())
15792    }
15793
15794    pub fn set_text(
15795        &mut self,
15796        text: impl Into<Arc<str>>,
15797        window: &mut Window,
15798        cx: &mut Context<Self>,
15799    ) {
15800        self.transact(window, cx, |this, _, cx| {
15801            this.buffer
15802                .read(cx)
15803                .as_singleton()
15804                .expect("you can only call set_text on editors for singleton buffers")
15805                .update(cx, |buffer, cx| buffer.set_text(text, cx));
15806        });
15807    }
15808
15809    pub fn display_text(&self, cx: &mut App) -> String {
15810        self.display_map
15811            .update(cx, |map, cx| map.snapshot(cx))
15812            .text()
15813    }
15814
15815    pub fn wrap_guides(&self, cx: &App) -> SmallVec<[(usize, bool); 2]> {
15816        let mut wrap_guides = smallvec::smallvec![];
15817
15818        if self.show_wrap_guides == Some(false) {
15819            return wrap_guides;
15820        }
15821
15822        let settings = self.buffer.read(cx).language_settings(cx);
15823        if settings.show_wrap_guides {
15824            match self.soft_wrap_mode(cx) {
15825                SoftWrap::Column(soft_wrap) => {
15826                    wrap_guides.push((soft_wrap as usize, true));
15827                }
15828                SoftWrap::Bounded(soft_wrap) => {
15829                    wrap_guides.push((soft_wrap as usize, true));
15830                }
15831                SoftWrap::GitDiff | SoftWrap::None | SoftWrap::EditorWidth => {}
15832            }
15833            wrap_guides.extend(settings.wrap_guides.iter().map(|guide| (*guide, false)))
15834        }
15835
15836        wrap_guides
15837    }
15838
15839    pub fn soft_wrap_mode(&self, cx: &App) -> SoftWrap {
15840        let settings = self.buffer.read(cx).language_settings(cx);
15841        let mode = self.soft_wrap_mode_override.unwrap_or(settings.soft_wrap);
15842        match mode {
15843            language_settings::SoftWrap::PreferLine | language_settings::SoftWrap::None => {
15844                SoftWrap::None
15845            }
15846            language_settings::SoftWrap::EditorWidth => SoftWrap::EditorWidth,
15847            language_settings::SoftWrap::PreferredLineLength => {
15848                SoftWrap::Column(settings.preferred_line_length)
15849            }
15850            language_settings::SoftWrap::Bounded => {
15851                SoftWrap::Bounded(settings.preferred_line_length)
15852            }
15853        }
15854    }
15855
15856    pub fn set_soft_wrap_mode(
15857        &mut self,
15858        mode: language_settings::SoftWrap,
15859
15860        cx: &mut Context<Self>,
15861    ) {
15862        self.soft_wrap_mode_override = Some(mode);
15863        cx.notify();
15864    }
15865
15866    pub fn set_hard_wrap(&mut self, hard_wrap: Option<usize>, cx: &mut Context<Self>) {
15867        self.hard_wrap = hard_wrap;
15868        cx.notify();
15869    }
15870
15871    pub fn set_text_style_refinement(&mut self, style: TextStyleRefinement) {
15872        self.text_style_refinement = Some(style);
15873    }
15874
15875    /// called by the Element so we know what style we were most recently rendered with.
15876    pub(crate) fn set_style(
15877        &mut self,
15878        style: EditorStyle,
15879        window: &mut Window,
15880        cx: &mut Context<Self>,
15881    ) {
15882        let rem_size = window.rem_size();
15883        self.display_map.update(cx, |map, cx| {
15884            map.set_font(
15885                style.text.font(),
15886                style.text.font_size.to_pixels(rem_size),
15887                cx,
15888            )
15889        });
15890        self.style = Some(style);
15891    }
15892
15893    pub fn style(&self) -> Option<&EditorStyle> {
15894        self.style.as_ref()
15895    }
15896
15897    // Called by the element. This method is not designed to be called outside of the editor
15898    // element's layout code because it does not notify when rewrapping is computed synchronously.
15899    pub(crate) fn set_wrap_width(&self, width: Option<Pixels>, cx: &mut App) -> bool {
15900        self.display_map
15901            .update(cx, |map, cx| map.set_wrap_width(width, cx))
15902    }
15903
15904    pub fn set_soft_wrap(&mut self) {
15905        self.soft_wrap_mode_override = Some(language_settings::SoftWrap::EditorWidth)
15906    }
15907
15908    pub fn toggle_soft_wrap(&mut self, _: &ToggleSoftWrap, _: &mut Window, cx: &mut Context<Self>) {
15909        if self.soft_wrap_mode_override.is_some() {
15910            self.soft_wrap_mode_override.take();
15911        } else {
15912            let soft_wrap = match self.soft_wrap_mode(cx) {
15913                SoftWrap::GitDiff => return,
15914                SoftWrap::None => language_settings::SoftWrap::EditorWidth,
15915                SoftWrap::EditorWidth | SoftWrap::Column(_) | SoftWrap::Bounded(_) => {
15916                    language_settings::SoftWrap::None
15917                }
15918            };
15919            self.soft_wrap_mode_override = Some(soft_wrap);
15920        }
15921        cx.notify();
15922    }
15923
15924    pub fn toggle_tab_bar(&mut self, _: &ToggleTabBar, _: &mut Window, cx: &mut Context<Self>) {
15925        let Some(workspace) = self.workspace() else {
15926            return;
15927        };
15928        let fs = workspace.read(cx).app_state().fs.clone();
15929        let current_show = TabBarSettings::get_global(cx).show;
15930        update_settings_file::<TabBarSettings>(fs, cx, move |setting, _| {
15931            setting.show = Some(!current_show);
15932        });
15933    }
15934
15935    pub fn toggle_indent_guides(
15936        &mut self,
15937        _: &ToggleIndentGuides,
15938        _: &mut Window,
15939        cx: &mut Context<Self>,
15940    ) {
15941        let currently_enabled = self.should_show_indent_guides().unwrap_or_else(|| {
15942            self.buffer
15943                .read(cx)
15944                .language_settings(cx)
15945                .indent_guides
15946                .enabled
15947        });
15948        self.show_indent_guides = Some(!currently_enabled);
15949        cx.notify();
15950    }
15951
15952    fn should_show_indent_guides(&self) -> Option<bool> {
15953        self.show_indent_guides
15954    }
15955
15956    pub fn toggle_line_numbers(
15957        &mut self,
15958        _: &ToggleLineNumbers,
15959        _: &mut Window,
15960        cx: &mut Context<Self>,
15961    ) {
15962        let mut editor_settings = EditorSettings::get_global(cx).clone();
15963        editor_settings.gutter.line_numbers = !editor_settings.gutter.line_numbers;
15964        EditorSettings::override_global(editor_settings, cx);
15965    }
15966
15967    pub fn line_numbers_enabled(&self, cx: &App) -> bool {
15968        if let Some(show_line_numbers) = self.show_line_numbers {
15969            return show_line_numbers;
15970        }
15971        EditorSettings::get_global(cx).gutter.line_numbers
15972    }
15973
15974    pub fn should_use_relative_line_numbers(&self, cx: &mut App) -> bool {
15975        self.use_relative_line_numbers
15976            .unwrap_or(EditorSettings::get_global(cx).relative_line_numbers)
15977    }
15978
15979    pub fn toggle_relative_line_numbers(
15980        &mut self,
15981        _: &ToggleRelativeLineNumbers,
15982        _: &mut Window,
15983        cx: &mut Context<Self>,
15984    ) {
15985        let is_relative = self.should_use_relative_line_numbers(cx);
15986        self.set_relative_line_number(Some(!is_relative), cx)
15987    }
15988
15989    pub fn set_relative_line_number(&mut self, is_relative: Option<bool>, cx: &mut Context<Self>) {
15990        self.use_relative_line_numbers = is_relative;
15991        cx.notify();
15992    }
15993
15994    pub fn set_show_gutter(&mut self, show_gutter: bool, cx: &mut Context<Self>) {
15995        self.show_gutter = show_gutter;
15996        cx.notify();
15997    }
15998
15999    pub fn set_show_scrollbars(&mut self, show_scrollbars: bool, cx: &mut Context<Self>) {
16000        self.show_scrollbars = show_scrollbars;
16001        cx.notify();
16002    }
16003
16004    pub fn set_show_line_numbers(&mut self, show_line_numbers: bool, cx: &mut Context<Self>) {
16005        self.show_line_numbers = Some(show_line_numbers);
16006        cx.notify();
16007    }
16008
16009    pub fn set_show_git_diff_gutter(&mut self, show_git_diff_gutter: bool, cx: &mut Context<Self>) {
16010        self.show_git_diff_gutter = Some(show_git_diff_gutter);
16011        cx.notify();
16012    }
16013
16014    pub fn set_show_code_actions(&mut self, show_code_actions: bool, cx: &mut Context<Self>) {
16015        self.show_code_actions = Some(show_code_actions);
16016        cx.notify();
16017    }
16018
16019    pub fn set_show_runnables(&mut self, show_runnables: bool, cx: &mut Context<Self>) {
16020        self.show_runnables = Some(show_runnables);
16021        cx.notify();
16022    }
16023
16024    pub fn set_show_breakpoints(&mut self, show_breakpoints: bool, cx: &mut Context<Self>) {
16025        self.show_breakpoints = Some(show_breakpoints);
16026        cx.notify();
16027    }
16028
16029    pub fn set_masked(&mut self, masked: bool, cx: &mut Context<Self>) {
16030        if self.display_map.read(cx).masked != masked {
16031            self.display_map.update(cx, |map, _| map.masked = masked);
16032        }
16033        cx.notify()
16034    }
16035
16036    pub fn set_show_wrap_guides(&mut self, show_wrap_guides: bool, cx: &mut Context<Self>) {
16037        self.show_wrap_guides = Some(show_wrap_guides);
16038        cx.notify();
16039    }
16040
16041    pub fn set_show_indent_guides(&mut self, show_indent_guides: bool, cx: &mut Context<Self>) {
16042        self.show_indent_guides = Some(show_indent_guides);
16043        cx.notify();
16044    }
16045
16046    pub fn working_directory(&self, cx: &App) -> Option<PathBuf> {
16047        if let Some(buffer) = self.buffer().read(cx).as_singleton() {
16048            if let Some(file) = buffer.read(cx).file().and_then(|f| f.as_local()) {
16049                if let Some(dir) = file.abs_path(cx).parent() {
16050                    return Some(dir.to_owned());
16051                }
16052            }
16053
16054            if let Some(project_path) = buffer.read(cx).project_path(cx) {
16055                return Some(project_path.path.to_path_buf());
16056            }
16057        }
16058
16059        None
16060    }
16061
16062    fn target_file<'a>(&self, cx: &'a App) -> Option<&'a dyn language::LocalFile> {
16063        self.active_excerpt(cx)?
16064            .1
16065            .read(cx)
16066            .file()
16067            .and_then(|f| f.as_local())
16068    }
16069
16070    pub fn target_file_abs_path(&self, cx: &mut Context<Self>) -> Option<PathBuf> {
16071        self.active_excerpt(cx).and_then(|(_, buffer, _)| {
16072            let buffer = buffer.read(cx);
16073            if let Some(project_path) = buffer.project_path(cx) {
16074                let project = self.project.as_ref()?.read(cx);
16075                project.absolute_path(&project_path, cx)
16076            } else {
16077                buffer
16078                    .file()
16079                    .and_then(|file| file.as_local().map(|file| file.abs_path(cx)))
16080            }
16081        })
16082    }
16083
16084    fn target_file_path(&self, cx: &mut Context<Self>) -> Option<PathBuf> {
16085        self.active_excerpt(cx).and_then(|(_, buffer, _)| {
16086            let project_path = buffer.read(cx).project_path(cx)?;
16087            let project = self.project.as_ref()?.read(cx);
16088            let entry = project.entry_for_path(&project_path, cx)?;
16089            let path = entry.path.to_path_buf();
16090            Some(path)
16091        })
16092    }
16093
16094    pub fn reveal_in_finder(
16095        &mut self,
16096        _: &RevealInFileManager,
16097        _window: &mut Window,
16098        cx: &mut Context<Self>,
16099    ) {
16100        if let Some(target) = self.target_file(cx) {
16101            cx.reveal_path(&target.abs_path(cx));
16102        }
16103    }
16104
16105    pub fn copy_path(
16106        &mut self,
16107        _: &zed_actions::workspace::CopyPath,
16108        _window: &mut Window,
16109        cx: &mut Context<Self>,
16110    ) {
16111        if let Some(path) = self.target_file_abs_path(cx) {
16112            if let Some(path) = path.to_str() {
16113                cx.write_to_clipboard(ClipboardItem::new_string(path.to_string()));
16114            }
16115        }
16116    }
16117
16118    pub fn copy_relative_path(
16119        &mut self,
16120        _: &zed_actions::workspace::CopyRelativePath,
16121        _window: &mut Window,
16122        cx: &mut Context<Self>,
16123    ) {
16124        if let Some(path) = self.target_file_path(cx) {
16125            if let Some(path) = path.to_str() {
16126                cx.write_to_clipboard(ClipboardItem::new_string(path.to_string()));
16127            }
16128        }
16129    }
16130
16131    pub fn project_path(&self, cx: &App) -> Option<ProjectPath> {
16132        if let Some(buffer) = self.buffer.read(cx).as_singleton() {
16133            buffer.read(cx).project_path(cx)
16134        } else {
16135            None
16136        }
16137    }
16138
16139    // Returns true if the editor handled a go-to-line request
16140    pub fn go_to_active_debug_line(&mut self, window: &mut Window, cx: &mut Context<Self>) -> bool {
16141        maybe!({
16142            let breakpoint_store = self.breakpoint_store.as_ref()?;
16143
16144            let Some((_, _, active_position)) =
16145                breakpoint_store.read(cx).active_position().cloned()
16146            else {
16147                self.clear_row_highlights::<DebugCurrentRowHighlight>();
16148                return None;
16149            };
16150
16151            let snapshot = self
16152                .project
16153                .as_ref()?
16154                .read(cx)
16155                .buffer_for_id(active_position.buffer_id?, cx)?
16156                .read(cx)
16157                .snapshot();
16158
16159            let mut handled = false;
16160            for (id, ExcerptRange { context, .. }) in self
16161                .buffer
16162                .read(cx)
16163                .excerpts_for_buffer(active_position.buffer_id?, cx)
16164            {
16165                if context.start.cmp(&active_position, &snapshot).is_ge()
16166                    || context.end.cmp(&active_position, &snapshot).is_lt()
16167                {
16168                    continue;
16169                }
16170                let snapshot = self.buffer.read(cx).snapshot(cx);
16171                let multibuffer_anchor = snapshot.anchor_in_excerpt(id, active_position)?;
16172
16173                handled = true;
16174                self.clear_row_highlights::<DebugCurrentRowHighlight>();
16175                self.go_to_line::<DebugCurrentRowHighlight>(
16176                    multibuffer_anchor,
16177                    Some(cx.theme().colors().editor_debugger_active_line_background),
16178                    window,
16179                    cx,
16180                );
16181
16182                cx.notify();
16183            }
16184            handled.then_some(())
16185        })
16186        .is_some()
16187    }
16188
16189    pub fn copy_file_name_without_extension(
16190        &mut self,
16191        _: &CopyFileNameWithoutExtension,
16192        _: &mut Window,
16193        cx: &mut Context<Self>,
16194    ) {
16195        if let Some(file) = self.target_file(cx) {
16196            if let Some(file_stem) = file.path().file_stem() {
16197                if let Some(name) = file_stem.to_str() {
16198                    cx.write_to_clipboard(ClipboardItem::new_string(name.to_string()));
16199                }
16200            }
16201        }
16202    }
16203
16204    pub fn copy_file_name(&mut self, _: &CopyFileName, _: &mut Window, cx: &mut Context<Self>) {
16205        if let Some(file) = self.target_file(cx) {
16206            if let Some(file_name) = file.path().file_name() {
16207                if let Some(name) = file_name.to_str() {
16208                    cx.write_to_clipboard(ClipboardItem::new_string(name.to_string()));
16209                }
16210            }
16211        }
16212    }
16213
16214    pub fn toggle_git_blame(
16215        &mut self,
16216        _: &::git::Blame,
16217        window: &mut Window,
16218        cx: &mut Context<Self>,
16219    ) {
16220        self.show_git_blame_gutter = !self.show_git_blame_gutter;
16221
16222        if self.show_git_blame_gutter && !self.has_blame_entries(cx) {
16223            self.start_git_blame(true, window, cx);
16224        }
16225
16226        cx.notify();
16227    }
16228
16229    pub fn toggle_git_blame_inline(
16230        &mut self,
16231        _: &ToggleGitBlameInline,
16232        window: &mut Window,
16233        cx: &mut Context<Self>,
16234    ) {
16235        self.toggle_git_blame_inline_internal(true, window, cx);
16236        cx.notify();
16237    }
16238
16239    pub fn open_git_blame_commit(
16240        &mut self,
16241        _: &OpenGitBlameCommit,
16242        window: &mut Window,
16243        cx: &mut Context<Self>,
16244    ) {
16245        self.open_git_blame_commit_internal(window, cx);
16246    }
16247
16248    fn open_git_blame_commit_internal(
16249        &mut self,
16250        window: &mut Window,
16251        cx: &mut Context<Self>,
16252    ) -> Option<()> {
16253        let blame = self.blame.as_ref()?;
16254        let snapshot = self.snapshot(window, cx);
16255        let cursor = self.selections.newest::<Point>(cx).head();
16256        let (buffer, point, _) = snapshot.buffer_snapshot.point_to_buffer_point(cursor)?;
16257        let blame_entry = blame
16258            .update(cx, |blame, cx| {
16259                blame
16260                    .blame_for_rows(
16261                        &[RowInfo {
16262                            buffer_id: Some(buffer.remote_id()),
16263                            buffer_row: Some(point.row),
16264                            ..Default::default()
16265                        }],
16266                        cx,
16267                    )
16268                    .next()
16269            })
16270            .flatten()?;
16271        let renderer = cx.global::<GlobalBlameRenderer>().0.clone();
16272        let repo = blame.read(cx).repository(cx)?;
16273        let workspace = self.workspace()?.downgrade();
16274        renderer.open_blame_commit(blame_entry, repo, workspace, window, cx);
16275        None
16276    }
16277
16278    pub fn git_blame_inline_enabled(&self) -> bool {
16279        self.git_blame_inline_enabled
16280    }
16281
16282    pub fn toggle_selection_menu(
16283        &mut self,
16284        _: &ToggleSelectionMenu,
16285        _: &mut Window,
16286        cx: &mut Context<Self>,
16287    ) {
16288        self.show_selection_menu = self
16289            .show_selection_menu
16290            .map(|show_selections_menu| !show_selections_menu)
16291            .or_else(|| Some(!EditorSettings::get_global(cx).toolbar.selections_menu));
16292
16293        cx.notify();
16294    }
16295
16296    pub fn selection_menu_enabled(&self, cx: &App) -> bool {
16297        self.show_selection_menu
16298            .unwrap_or_else(|| EditorSettings::get_global(cx).toolbar.selections_menu)
16299    }
16300
16301    fn start_git_blame(
16302        &mut self,
16303        user_triggered: bool,
16304        window: &mut Window,
16305        cx: &mut Context<Self>,
16306    ) {
16307        if let Some(project) = self.project.as_ref() {
16308            let Some(buffer) = self.buffer().read(cx).as_singleton() else {
16309                return;
16310            };
16311
16312            if buffer.read(cx).file().is_none() {
16313                return;
16314            }
16315
16316            let focused = self.focus_handle(cx).contains_focused(window, cx);
16317
16318            let project = project.clone();
16319            let blame = cx.new(|cx| GitBlame::new(buffer, project, user_triggered, focused, cx));
16320            self.blame_subscription =
16321                Some(cx.observe_in(&blame, window, |_, _, _, cx| cx.notify()));
16322            self.blame = Some(blame);
16323        }
16324    }
16325
16326    fn toggle_git_blame_inline_internal(
16327        &mut self,
16328        user_triggered: bool,
16329        window: &mut Window,
16330        cx: &mut Context<Self>,
16331    ) {
16332        if self.git_blame_inline_enabled {
16333            self.git_blame_inline_enabled = false;
16334            self.show_git_blame_inline = false;
16335            self.show_git_blame_inline_delay_task.take();
16336        } else {
16337            self.git_blame_inline_enabled = true;
16338            self.start_git_blame_inline(user_triggered, window, cx);
16339        }
16340
16341        cx.notify();
16342    }
16343
16344    fn start_git_blame_inline(
16345        &mut self,
16346        user_triggered: bool,
16347        window: &mut Window,
16348        cx: &mut Context<Self>,
16349    ) {
16350        self.start_git_blame(user_triggered, window, cx);
16351
16352        if ProjectSettings::get_global(cx)
16353            .git
16354            .inline_blame_delay()
16355            .is_some()
16356        {
16357            self.start_inline_blame_timer(window, cx);
16358        } else {
16359            self.show_git_blame_inline = true
16360        }
16361    }
16362
16363    pub fn blame(&self) -> Option<&Entity<GitBlame>> {
16364        self.blame.as_ref()
16365    }
16366
16367    pub fn show_git_blame_gutter(&self) -> bool {
16368        self.show_git_blame_gutter
16369    }
16370
16371    pub fn render_git_blame_gutter(&self, cx: &App) -> bool {
16372        self.show_git_blame_gutter && self.has_blame_entries(cx)
16373    }
16374
16375    pub fn render_git_blame_inline(&self, window: &Window, cx: &App) -> bool {
16376        self.show_git_blame_inline
16377            && (self.focus_handle.is_focused(window)
16378                || self
16379                    .git_blame_inline_tooltip
16380                    .as_ref()
16381                    .and_then(|t| t.upgrade())
16382                    .is_some())
16383            && !self.newest_selection_head_on_empty_line(cx)
16384            && self.has_blame_entries(cx)
16385    }
16386
16387    fn has_blame_entries(&self, cx: &App) -> bool {
16388        self.blame()
16389            .map_or(false, |blame| blame.read(cx).has_generated_entries())
16390    }
16391
16392    fn newest_selection_head_on_empty_line(&self, cx: &App) -> bool {
16393        let cursor_anchor = self.selections.newest_anchor().head();
16394
16395        let snapshot = self.buffer.read(cx).snapshot(cx);
16396        let buffer_row = MultiBufferRow(cursor_anchor.to_point(&snapshot).row);
16397
16398        snapshot.line_len(buffer_row) == 0
16399    }
16400
16401    fn get_permalink_to_line(&self, cx: &mut Context<Self>) -> Task<Result<url::Url>> {
16402        let buffer_and_selection = maybe!({
16403            let selection = self.selections.newest::<Point>(cx);
16404            let selection_range = selection.range();
16405
16406            let multi_buffer = self.buffer().read(cx);
16407            let multi_buffer_snapshot = multi_buffer.snapshot(cx);
16408            let buffer_ranges = multi_buffer_snapshot.range_to_buffer_ranges(selection_range);
16409
16410            let (buffer, range, _) = if selection.reversed {
16411                buffer_ranges.first()
16412            } else {
16413                buffer_ranges.last()
16414            }?;
16415
16416            let selection = text::ToPoint::to_point(&range.start, &buffer).row
16417                ..text::ToPoint::to_point(&range.end, &buffer).row;
16418            Some((
16419                multi_buffer.buffer(buffer.remote_id()).unwrap().clone(),
16420                selection,
16421            ))
16422        });
16423
16424        let Some((buffer, selection)) = buffer_and_selection else {
16425            return Task::ready(Err(anyhow!("failed to determine buffer and selection")));
16426        };
16427
16428        let Some(project) = self.project.as_ref() else {
16429            return Task::ready(Err(anyhow!("editor does not have project")));
16430        };
16431
16432        project.update(cx, |project, cx| {
16433            project.get_permalink_to_line(&buffer, selection, cx)
16434        })
16435    }
16436
16437    pub fn copy_permalink_to_line(
16438        &mut self,
16439        _: &CopyPermalinkToLine,
16440        window: &mut Window,
16441        cx: &mut Context<Self>,
16442    ) {
16443        let permalink_task = self.get_permalink_to_line(cx);
16444        let workspace = self.workspace();
16445
16446        cx.spawn_in(window, async move |_, cx| match permalink_task.await {
16447            Ok(permalink) => {
16448                cx.update(|_, cx| {
16449                    cx.write_to_clipboard(ClipboardItem::new_string(permalink.to_string()));
16450                })
16451                .ok();
16452            }
16453            Err(err) => {
16454                let message = format!("Failed to copy permalink: {err}");
16455
16456                Err::<(), anyhow::Error>(err).log_err();
16457
16458                if let Some(workspace) = workspace {
16459                    workspace
16460                        .update_in(cx, |workspace, _, cx| {
16461                            struct CopyPermalinkToLine;
16462
16463                            workspace.show_toast(
16464                                Toast::new(
16465                                    NotificationId::unique::<CopyPermalinkToLine>(),
16466                                    message,
16467                                ),
16468                                cx,
16469                            )
16470                        })
16471                        .ok();
16472                }
16473            }
16474        })
16475        .detach();
16476    }
16477
16478    pub fn copy_file_location(
16479        &mut self,
16480        _: &CopyFileLocation,
16481        _: &mut Window,
16482        cx: &mut Context<Self>,
16483    ) {
16484        let selection = self.selections.newest::<Point>(cx).start.row + 1;
16485        if let Some(file) = self.target_file(cx) {
16486            if let Some(path) = file.path().to_str() {
16487                cx.write_to_clipboard(ClipboardItem::new_string(format!("{path}:{selection}")));
16488            }
16489        }
16490    }
16491
16492    pub fn open_permalink_to_line(
16493        &mut self,
16494        _: &OpenPermalinkToLine,
16495        window: &mut Window,
16496        cx: &mut Context<Self>,
16497    ) {
16498        let permalink_task = self.get_permalink_to_line(cx);
16499        let workspace = self.workspace();
16500
16501        cx.spawn_in(window, async move |_, cx| match permalink_task.await {
16502            Ok(permalink) => {
16503                cx.update(|_, cx| {
16504                    cx.open_url(permalink.as_ref());
16505                })
16506                .ok();
16507            }
16508            Err(err) => {
16509                let message = format!("Failed to open permalink: {err}");
16510
16511                Err::<(), anyhow::Error>(err).log_err();
16512
16513                if let Some(workspace) = workspace {
16514                    workspace
16515                        .update(cx, |workspace, cx| {
16516                            struct OpenPermalinkToLine;
16517
16518                            workspace.show_toast(
16519                                Toast::new(
16520                                    NotificationId::unique::<OpenPermalinkToLine>(),
16521                                    message,
16522                                ),
16523                                cx,
16524                            )
16525                        })
16526                        .ok();
16527                }
16528            }
16529        })
16530        .detach();
16531    }
16532
16533    pub fn insert_uuid_v4(
16534        &mut self,
16535        _: &InsertUuidV4,
16536        window: &mut Window,
16537        cx: &mut Context<Self>,
16538    ) {
16539        self.insert_uuid(UuidVersion::V4, window, cx);
16540    }
16541
16542    pub fn insert_uuid_v7(
16543        &mut self,
16544        _: &InsertUuidV7,
16545        window: &mut Window,
16546        cx: &mut Context<Self>,
16547    ) {
16548        self.insert_uuid(UuidVersion::V7, window, cx);
16549    }
16550
16551    fn insert_uuid(&mut self, version: UuidVersion, window: &mut Window, cx: &mut Context<Self>) {
16552        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
16553        self.transact(window, cx, |this, window, cx| {
16554            let edits = this
16555                .selections
16556                .all::<Point>(cx)
16557                .into_iter()
16558                .map(|selection| {
16559                    let uuid = match version {
16560                        UuidVersion::V4 => uuid::Uuid::new_v4(),
16561                        UuidVersion::V7 => uuid::Uuid::now_v7(),
16562                    };
16563
16564                    (selection.range(), uuid.to_string())
16565                });
16566            this.edit(edits, cx);
16567            this.refresh_inline_completion(true, false, window, cx);
16568        });
16569    }
16570
16571    pub fn open_selections_in_multibuffer(
16572        &mut self,
16573        _: &OpenSelectionsInMultibuffer,
16574        window: &mut Window,
16575        cx: &mut Context<Self>,
16576    ) {
16577        let multibuffer = self.buffer.read(cx);
16578
16579        let Some(buffer) = multibuffer.as_singleton() else {
16580            return;
16581        };
16582
16583        let Some(workspace) = self.workspace() else {
16584            return;
16585        };
16586
16587        let locations = self
16588            .selections
16589            .disjoint_anchors()
16590            .iter()
16591            .map(|range| Location {
16592                buffer: buffer.clone(),
16593                range: range.start.text_anchor..range.end.text_anchor,
16594            })
16595            .collect::<Vec<_>>();
16596
16597        let title = multibuffer.title(cx).to_string();
16598
16599        cx.spawn_in(window, async move |_, cx| {
16600            workspace.update_in(cx, |workspace, window, cx| {
16601                Self::open_locations_in_multibuffer(
16602                    workspace,
16603                    locations,
16604                    format!("Selections for '{title}'"),
16605                    false,
16606                    MultibufferSelectionMode::All,
16607                    window,
16608                    cx,
16609                );
16610            })
16611        })
16612        .detach();
16613    }
16614
16615    /// Adds a row highlight for the given range. If a row has multiple highlights, the
16616    /// last highlight added will be used.
16617    ///
16618    /// If the range ends at the beginning of a line, then that line will not be highlighted.
16619    pub fn highlight_rows<T: 'static>(
16620        &mut self,
16621        range: Range<Anchor>,
16622        color: Hsla,
16623        should_autoscroll: bool,
16624        cx: &mut Context<Self>,
16625    ) {
16626        let snapshot = self.buffer().read(cx).snapshot(cx);
16627        let row_highlights = self.highlighted_rows.entry(TypeId::of::<T>()).or_default();
16628        let ix = row_highlights.binary_search_by(|highlight| {
16629            Ordering::Equal
16630                .then_with(|| highlight.range.start.cmp(&range.start, &snapshot))
16631                .then_with(|| highlight.range.end.cmp(&range.end, &snapshot))
16632        });
16633
16634        if let Err(mut ix) = ix {
16635            let index = post_inc(&mut self.highlight_order);
16636
16637            // If this range intersects with the preceding highlight, then merge it with
16638            // the preceding highlight. Otherwise insert a new highlight.
16639            let mut merged = false;
16640            if ix > 0 {
16641                let prev_highlight = &mut row_highlights[ix - 1];
16642                if prev_highlight
16643                    .range
16644                    .end
16645                    .cmp(&range.start, &snapshot)
16646                    .is_ge()
16647                {
16648                    ix -= 1;
16649                    if prev_highlight.range.end.cmp(&range.end, &snapshot).is_lt() {
16650                        prev_highlight.range.end = range.end;
16651                    }
16652                    merged = true;
16653                    prev_highlight.index = index;
16654                    prev_highlight.color = color;
16655                    prev_highlight.should_autoscroll = should_autoscroll;
16656                }
16657            }
16658
16659            if !merged {
16660                row_highlights.insert(
16661                    ix,
16662                    RowHighlight {
16663                        range: range.clone(),
16664                        index,
16665                        color,
16666                        should_autoscroll,
16667                    },
16668                );
16669            }
16670
16671            // If any of the following highlights intersect with this one, merge them.
16672            while let Some(next_highlight) = row_highlights.get(ix + 1) {
16673                let highlight = &row_highlights[ix];
16674                if next_highlight
16675                    .range
16676                    .start
16677                    .cmp(&highlight.range.end, &snapshot)
16678                    .is_le()
16679                {
16680                    if next_highlight
16681                        .range
16682                        .end
16683                        .cmp(&highlight.range.end, &snapshot)
16684                        .is_gt()
16685                    {
16686                        row_highlights[ix].range.end = next_highlight.range.end;
16687                    }
16688                    row_highlights.remove(ix + 1);
16689                } else {
16690                    break;
16691                }
16692            }
16693        }
16694    }
16695
16696    /// Remove any highlighted row ranges of the given type that intersect the
16697    /// given ranges.
16698    pub fn remove_highlighted_rows<T: 'static>(
16699        &mut self,
16700        ranges_to_remove: Vec<Range<Anchor>>,
16701        cx: &mut Context<Self>,
16702    ) {
16703        let snapshot = self.buffer().read(cx).snapshot(cx);
16704        let row_highlights = self.highlighted_rows.entry(TypeId::of::<T>()).or_default();
16705        let mut ranges_to_remove = ranges_to_remove.iter().peekable();
16706        row_highlights.retain(|highlight| {
16707            while let Some(range_to_remove) = ranges_to_remove.peek() {
16708                match range_to_remove.end.cmp(&highlight.range.start, &snapshot) {
16709                    Ordering::Less | Ordering::Equal => {
16710                        ranges_to_remove.next();
16711                    }
16712                    Ordering::Greater => {
16713                        match range_to_remove.start.cmp(&highlight.range.end, &snapshot) {
16714                            Ordering::Less | Ordering::Equal => {
16715                                return false;
16716                            }
16717                            Ordering::Greater => break,
16718                        }
16719                    }
16720                }
16721            }
16722
16723            true
16724        })
16725    }
16726
16727    /// Clear all anchor ranges for a certain highlight context type, so no corresponding rows will be highlighted.
16728    pub fn clear_row_highlights<T: 'static>(&mut self) {
16729        self.highlighted_rows.remove(&TypeId::of::<T>());
16730    }
16731
16732    /// For a highlight given context type, gets all anchor ranges that will be used for row highlighting.
16733    pub fn highlighted_rows<T: 'static>(&self) -> impl '_ + Iterator<Item = (Range<Anchor>, Hsla)> {
16734        self.highlighted_rows
16735            .get(&TypeId::of::<T>())
16736            .map_or(&[] as &[_], |vec| vec.as_slice())
16737            .iter()
16738            .map(|highlight| (highlight.range.clone(), highlight.color))
16739    }
16740
16741    /// Merges all anchor ranges for all context types ever set, picking the last highlight added in case of a row conflict.
16742    /// Returns a map of display rows that are highlighted and their corresponding highlight color.
16743    /// Allows to ignore certain kinds of highlights.
16744    pub fn highlighted_display_rows(
16745        &self,
16746        window: &mut Window,
16747        cx: &mut App,
16748    ) -> BTreeMap<DisplayRow, LineHighlight> {
16749        let snapshot = self.snapshot(window, cx);
16750        let mut used_highlight_orders = HashMap::default();
16751        self.highlighted_rows
16752            .iter()
16753            .flat_map(|(_, highlighted_rows)| highlighted_rows.iter())
16754            .fold(
16755                BTreeMap::<DisplayRow, LineHighlight>::new(),
16756                |mut unique_rows, highlight| {
16757                    let start = highlight.range.start.to_display_point(&snapshot);
16758                    let end = highlight.range.end.to_display_point(&snapshot);
16759                    let start_row = start.row().0;
16760                    let end_row = if highlight.range.end.text_anchor != text::Anchor::MAX
16761                        && end.column() == 0
16762                    {
16763                        end.row().0.saturating_sub(1)
16764                    } else {
16765                        end.row().0
16766                    };
16767                    for row in start_row..=end_row {
16768                        let used_index =
16769                            used_highlight_orders.entry(row).or_insert(highlight.index);
16770                        if highlight.index >= *used_index {
16771                            *used_index = highlight.index;
16772                            unique_rows.insert(DisplayRow(row), highlight.color.into());
16773                        }
16774                    }
16775                    unique_rows
16776                },
16777            )
16778    }
16779
16780    pub fn highlighted_display_row_for_autoscroll(
16781        &self,
16782        snapshot: &DisplaySnapshot,
16783    ) -> Option<DisplayRow> {
16784        self.highlighted_rows
16785            .values()
16786            .flat_map(|highlighted_rows| highlighted_rows.iter())
16787            .filter_map(|highlight| {
16788                if highlight.should_autoscroll {
16789                    Some(highlight.range.start.to_display_point(snapshot).row())
16790                } else {
16791                    None
16792                }
16793            })
16794            .min()
16795    }
16796
16797    pub fn set_search_within_ranges(&mut self, ranges: &[Range<Anchor>], cx: &mut Context<Self>) {
16798        self.highlight_background::<SearchWithinRange>(
16799            ranges,
16800            |colors| colors.editor_document_highlight_read_background,
16801            cx,
16802        )
16803    }
16804
16805    pub fn set_breadcrumb_header(&mut self, new_header: String) {
16806        self.breadcrumb_header = Some(new_header);
16807    }
16808
16809    pub fn clear_search_within_ranges(&mut self, cx: &mut Context<Self>) {
16810        self.clear_background_highlights::<SearchWithinRange>(cx);
16811    }
16812
16813    pub fn highlight_background<T: 'static>(
16814        &mut self,
16815        ranges: &[Range<Anchor>],
16816        color_fetcher: fn(&ThemeColors) -> Hsla,
16817        cx: &mut Context<Self>,
16818    ) {
16819        self.background_highlights
16820            .insert(TypeId::of::<T>(), (color_fetcher, Arc::from(ranges)));
16821        self.scrollbar_marker_state.dirty = true;
16822        cx.notify();
16823    }
16824
16825    pub fn clear_background_highlights<T: 'static>(
16826        &mut self,
16827        cx: &mut Context<Self>,
16828    ) -> Option<BackgroundHighlight> {
16829        let text_highlights = self.background_highlights.remove(&TypeId::of::<T>())?;
16830        if !text_highlights.1.is_empty() {
16831            self.scrollbar_marker_state.dirty = true;
16832            cx.notify();
16833        }
16834        Some(text_highlights)
16835    }
16836
16837    pub fn highlight_gutter<T: 'static>(
16838        &mut self,
16839        ranges: &[Range<Anchor>],
16840        color_fetcher: fn(&App) -> Hsla,
16841        cx: &mut Context<Self>,
16842    ) {
16843        self.gutter_highlights
16844            .insert(TypeId::of::<T>(), (color_fetcher, Arc::from(ranges)));
16845        cx.notify();
16846    }
16847
16848    pub fn clear_gutter_highlights<T: 'static>(
16849        &mut self,
16850        cx: &mut Context<Self>,
16851    ) -> Option<GutterHighlight> {
16852        cx.notify();
16853        self.gutter_highlights.remove(&TypeId::of::<T>())
16854    }
16855
16856    #[cfg(feature = "test-support")]
16857    pub fn all_text_background_highlights(
16858        &self,
16859        window: &mut Window,
16860        cx: &mut Context<Self>,
16861    ) -> Vec<(Range<DisplayPoint>, Hsla)> {
16862        let snapshot = self.snapshot(window, cx);
16863        let buffer = &snapshot.buffer_snapshot;
16864        let start = buffer.anchor_before(0);
16865        let end = buffer.anchor_after(buffer.len());
16866        let theme = cx.theme().colors();
16867        self.background_highlights_in_range(start..end, &snapshot, theme)
16868    }
16869
16870    #[cfg(feature = "test-support")]
16871    pub fn search_background_highlights(&mut self, cx: &mut Context<Self>) -> Vec<Range<Point>> {
16872        let snapshot = self.buffer().read(cx).snapshot(cx);
16873
16874        let highlights = self
16875            .background_highlights
16876            .get(&TypeId::of::<items::BufferSearchHighlights>());
16877
16878        if let Some((_color, ranges)) = highlights {
16879            ranges
16880                .iter()
16881                .map(|range| range.start.to_point(&snapshot)..range.end.to_point(&snapshot))
16882                .collect_vec()
16883        } else {
16884            vec![]
16885        }
16886    }
16887
16888    fn document_highlights_for_position<'a>(
16889        &'a self,
16890        position: Anchor,
16891        buffer: &'a MultiBufferSnapshot,
16892    ) -> impl 'a + Iterator<Item = &'a Range<Anchor>> {
16893        let read_highlights = self
16894            .background_highlights
16895            .get(&TypeId::of::<DocumentHighlightRead>())
16896            .map(|h| &h.1);
16897        let write_highlights = self
16898            .background_highlights
16899            .get(&TypeId::of::<DocumentHighlightWrite>())
16900            .map(|h| &h.1);
16901        let left_position = position.bias_left(buffer);
16902        let right_position = position.bias_right(buffer);
16903        read_highlights
16904            .into_iter()
16905            .chain(write_highlights)
16906            .flat_map(move |ranges| {
16907                let start_ix = match ranges.binary_search_by(|probe| {
16908                    let cmp = probe.end.cmp(&left_position, buffer);
16909                    if cmp.is_ge() {
16910                        Ordering::Greater
16911                    } else {
16912                        Ordering::Less
16913                    }
16914                }) {
16915                    Ok(i) | Err(i) => i,
16916                };
16917
16918                ranges[start_ix..]
16919                    .iter()
16920                    .take_while(move |range| range.start.cmp(&right_position, buffer).is_le())
16921            })
16922    }
16923
16924    pub fn has_background_highlights<T: 'static>(&self) -> bool {
16925        self.background_highlights
16926            .get(&TypeId::of::<T>())
16927            .map_or(false, |(_, highlights)| !highlights.is_empty())
16928    }
16929
16930    pub fn background_highlights_in_range(
16931        &self,
16932        search_range: Range<Anchor>,
16933        display_snapshot: &DisplaySnapshot,
16934        theme: &ThemeColors,
16935    ) -> Vec<(Range<DisplayPoint>, Hsla)> {
16936        let mut results = Vec::new();
16937        for (color_fetcher, ranges) in self.background_highlights.values() {
16938            let color = color_fetcher(theme);
16939            let start_ix = match ranges.binary_search_by(|probe| {
16940                let cmp = probe
16941                    .end
16942                    .cmp(&search_range.start, &display_snapshot.buffer_snapshot);
16943                if cmp.is_gt() {
16944                    Ordering::Greater
16945                } else {
16946                    Ordering::Less
16947                }
16948            }) {
16949                Ok(i) | Err(i) => i,
16950            };
16951            for range in &ranges[start_ix..] {
16952                if range
16953                    .start
16954                    .cmp(&search_range.end, &display_snapshot.buffer_snapshot)
16955                    .is_ge()
16956                {
16957                    break;
16958                }
16959
16960                let start = range.start.to_display_point(display_snapshot);
16961                let end = range.end.to_display_point(display_snapshot);
16962                results.push((start..end, color))
16963            }
16964        }
16965        results
16966    }
16967
16968    pub fn background_highlight_row_ranges<T: 'static>(
16969        &self,
16970        search_range: Range<Anchor>,
16971        display_snapshot: &DisplaySnapshot,
16972        count: usize,
16973    ) -> Vec<RangeInclusive<DisplayPoint>> {
16974        let mut results = Vec::new();
16975        let Some((_, ranges)) = self.background_highlights.get(&TypeId::of::<T>()) else {
16976            return vec![];
16977        };
16978
16979        let start_ix = match ranges.binary_search_by(|probe| {
16980            let cmp = probe
16981                .end
16982                .cmp(&search_range.start, &display_snapshot.buffer_snapshot);
16983            if cmp.is_gt() {
16984                Ordering::Greater
16985            } else {
16986                Ordering::Less
16987            }
16988        }) {
16989            Ok(i) | Err(i) => i,
16990        };
16991        let mut push_region = |start: Option<Point>, end: Option<Point>| {
16992            if let (Some(start_display), Some(end_display)) = (start, end) {
16993                results.push(
16994                    start_display.to_display_point(display_snapshot)
16995                        ..=end_display.to_display_point(display_snapshot),
16996                );
16997            }
16998        };
16999        let mut start_row: Option<Point> = None;
17000        let mut end_row: Option<Point> = None;
17001        if ranges.len() > count {
17002            return Vec::new();
17003        }
17004        for range in &ranges[start_ix..] {
17005            if range
17006                .start
17007                .cmp(&search_range.end, &display_snapshot.buffer_snapshot)
17008                .is_ge()
17009            {
17010                break;
17011            }
17012            let end = range.end.to_point(&display_snapshot.buffer_snapshot);
17013            if let Some(current_row) = &end_row {
17014                if end.row == current_row.row {
17015                    continue;
17016                }
17017            }
17018            let start = range.start.to_point(&display_snapshot.buffer_snapshot);
17019            if start_row.is_none() {
17020                assert_eq!(end_row, None);
17021                start_row = Some(start);
17022                end_row = Some(end);
17023                continue;
17024            }
17025            if let Some(current_end) = end_row.as_mut() {
17026                if start.row > current_end.row + 1 {
17027                    push_region(start_row, end_row);
17028                    start_row = Some(start);
17029                    end_row = Some(end);
17030                } else {
17031                    // Merge two hunks.
17032                    *current_end = end;
17033                }
17034            } else {
17035                unreachable!();
17036            }
17037        }
17038        // We might still have a hunk that was not rendered (if there was a search hit on the last line)
17039        push_region(start_row, end_row);
17040        results
17041    }
17042
17043    pub fn gutter_highlights_in_range(
17044        &self,
17045        search_range: Range<Anchor>,
17046        display_snapshot: &DisplaySnapshot,
17047        cx: &App,
17048    ) -> Vec<(Range<DisplayPoint>, Hsla)> {
17049        let mut results = Vec::new();
17050        for (color_fetcher, ranges) in self.gutter_highlights.values() {
17051            let color = color_fetcher(cx);
17052            let start_ix = match ranges.binary_search_by(|probe| {
17053                let cmp = probe
17054                    .end
17055                    .cmp(&search_range.start, &display_snapshot.buffer_snapshot);
17056                if cmp.is_gt() {
17057                    Ordering::Greater
17058                } else {
17059                    Ordering::Less
17060                }
17061            }) {
17062                Ok(i) | Err(i) => i,
17063            };
17064            for range in &ranges[start_ix..] {
17065                if range
17066                    .start
17067                    .cmp(&search_range.end, &display_snapshot.buffer_snapshot)
17068                    .is_ge()
17069                {
17070                    break;
17071                }
17072
17073                let start = range.start.to_display_point(display_snapshot);
17074                let end = range.end.to_display_point(display_snapshot);
17075                results.push((start..end, color))
17076            }
17077        }
17078        results
17079    }
17080
17081    /// Get the text ranges corresponding to the redaction query
17082    pub fn redacted_ranges(
17083        &self,
17084        search_range: Range<Anchor>,
17085        display_snapshot: &DisplaySnapshot,
17086        cx: &App,
17087    ) -> Vec<Range<DisplayPoint>> {
17088        display_snapshot
17089            .buffer_snapshot
17090            .redacted_ranges(search_range, |file| {
17091                if let Some(file) = file {
17092                    file.is_private()
17093                        && EditorSettings::get(
17094                            Some(SettingsLocation {
17095                                worktree_id: file.worktree_id(cx),
17096                                path: file.path().as_ref(),
17097                            }),
17098                            cx,
17099                        )
17100                        .redact_private_values
17101                } else {
17102                    false
17103                }
17104            })
17105            .map(|range| {
17106                range.start.to_display_point(display_snapshot)
17107                    ..range.end.to_display_point(display_snapshot)
17108            })
17109            .collect()
17110    }
17111
17112    pub fn highlight_text<T: 'static>(
17113        &mut self,
17114        ranges: Vec<Range<Anchor>>,
17115        style: HighlightStyle,
17116        cx: &mut Context<Self>,
17117    ) {
17118        self.display_map.update(cx, |map, _| {
17119            map.highlight_text(TypeId::of::<T>(), ranges, style)
17120        });
17121        cx.notify();
17122    }
17123
17124    pub(crate) fn highlight_inlays<T: 'static>(
17125        &mut self,
17126        highlights: Vec<InlayHighlight>,
17127        style: HighlightStyle,
17128        cx: &mut Context<Self>,
17129    ) {
17130        self.display_map.update(cx, |map, _| {
17131            map.highlight_inlays(TypeId::of::<T>(), highlights, style)
17132        });
17133        cx.notify();
17134    }
17135
17136    pub fn text_highlights<'a, T: 'static>(
17137        &'a self,
17138        cx: &'a App,
17139    ) -> Option<(HighlightStyle, &'a [Range<Anchor>])> {
17140        self.display_map.read(cx).text_highlights(TypeId::of::<T>())
17141    }
17142
17143    pub fn clear_highlights<T: 'static>(&mut self, cx: &mut Context<Self>) {
17144        let cleared = self
17145            .display_map
17146            .update(cx, |map, _| map.clear_highlights(TypeId::of::<T>()));
17147        if cleared {
17148            cx.notify();
17149        }
17150    }
17151
17152    pub fn show_local_cursors(&self, window: &mut Window, cx: &mut App) -> bool {
17153        (self.read_only(cx) || self.blink_manager.read(cx).visible())
17154            && self.focus_handle.is_focused(window)
17155    }
17156
17157    pub fn set_show_cursor_when_unfocused(&mut self, is_enabled: bool, cx: &mut Context<Self>) {
17158        self.show_cursor_when_unfocused = is_enabled;
17159        cx.notify();
17160    }
17161
17162    fn on_buffer_changed(&mut self, _: Entity<MultiBuffer>, cx: &mut Context<Self>) {
17163        cx.notify();
17164    }
17165
17166    fn on_buffer_event(
17167        &mut self,
17168        multibuffer: &Entity<MultiBuffer>,
17169        event: &multi_buffer::Event,
17170        window: &mut Window,
17171        cx: &mut Context<Self>,
17172    ) {
17173        match event {
17174            multi_buffer::Event::Edited {
17175                singleton_buffer_edited,
17176                edited_buffer: buffer_edited,
17177            } => {
17178                self.scrollbar_marker_state.dirty = true;
17179                self.active_indent_guides_state.dirty = true;
17180                self.refresh_active_diagnostics(cx);
17181                self.refresh_code_actions(window, cx);
17182                if self.has_active_inline_completion() {
17183                    self.update_visible_inline_completion(window, cx);
17184                }
17185                if let Some(buffer) = buffer_edited {
17186                    let buffer_id = buffer.read(cx).remote_id();
17187                    if !self.registered_buffers.contains_key(&buffer_id) {
17188                        if let Some(project) = self.project.as_ref() {
17189                            project.update(cx, |project, cx| {
17190                                self.registered_buffers.insert(
17191                                    buffer_id,
17192                                    project.register_buffer_with_language_servers(&buffer, cx),
17193                                );
17194                            })
17195                        }
17196                    }
17197                }
17198                cx.emit(EditorEvent::BufferEdited);
17199                cx.emit(SearchEvent::MatchesInvalidated);
17200                if *singleton_buffer_edited {
17201                    if let Some(project) = &self.project {
17202                        #[allow(clippy::mutable_key_type)]
17203                        let languages_affected = multibuffer.update(cx, |multibuffer, cx| {
17204                            multibuffer
17205                                .all_buffers()
17206                                .into_iter()
17207                                .filter_map(|buffer| {
17208                                    buffer.update(cx, |buffer, cx| {
17209                                        let language = buffer.language()?;
17210                                        let should_discard = project.update(cx, |project, cx| {
17211                                            project.is_local()
17212                                                && !project.has_language_servers_for(buffer, cx)
17213                                        });
17214                                        should_discard.not().then_some(language.clone())
17215                                    })
17216                                })
17217                                .collect::<HashSet<_>>()
17218                        });
17219                        if !languages_affected.is_empty() {
17220                            self.refresh_inlay_hints(
17221                                InlayHintRefreshReason::BufferEdited(languages_affected),
17222                                cx,
17223                            );
17224                        }
17225                    }
17226                }
17227
17228                let Some(project) = &self.project else { return };
17229                let (telemetry, is_via_ssh) = {
17230                    let project = project.read(cx);
17231                    let telemetry = project.client().telemetry().clone();
17232                    let is_via_ssh = project.is_via_ssh();
17233                    (telemetry, is_via_ssh)
17234                };
17235                refresh_linked_ranges(self, window, cx);
17236                telemetry.log_edit_event("editor", is_via_ssh);
17237            }
17238            multi_buffer::Event::ExcerptsAdded {
17239                buffer,
17240                predecessor,
17241                excerpts,
17242            } => {
17243                self.tasks_update_task = Some(self.refresh_runnables(window, cx));
17244                let buffer_id = buffer.read(cx).remote_id();
17245                if self.buffer.read(cx).diff_for(buffer_id).is_none() {
17246                    if let Some(project) = &self.project {
17247                        get_uncommitted_diff_for_buffer(
17248                            project,
17249                            [buffer.clone()],
17250                            self.buffer.clone(),
17251                            cx,
17252                        )
17253                        .detach();
17254                    }
17255                }
17256                cx.emit(EditorEvent::ExcerptsAdded {
17257                    buffer: buffer.clone(),
17258                    predecessor: *predecessor,
17259                    excerpts: excerpts.clone(),
17260                });
17261                self.refresh_inlay_hints(InlayHintRefreshReason::NewLinesShown, cx);
17262            }
17263            multi_buffer::Event::ExcerptsRemoved { ids } => {
17264                self.refresh_inlay_hints(InlayHintRefreshReason::ExcerptsRemoved(ids.clone()), cx);
17265                let buffer = self.buffer.read(cx);
17266                self.registered_buffers
17267                    .retain(|buffer_id, _| buffer.buffer(*buffer_id).is_some());
17268                jsx_tag_auto_close::refresh_enabled_in_any_buffer(self, multibuffer, cx);
17269                cx.emit(EditorEvent::ExcerptsRemoved { ids: ids.clone() })
17270            }
17271            multi_buffer::Event::ExcerptsEdited {
17272                excerpt_ids,
17273                buffer_ids,
17274            } => {
17275                self.display_map.update(cx, |map, cx| {
17276                    map.unfold_buffers(buffer_ids.iter().copied(), cx)
17277                });
17278                cx.emit(EditorEvent::ExcerptsEdited {
17279                    ids: excerpt_ids.clone(),
17280                })
17281            }
17282            multi_buffer::Event::ExcerptsExpanded { ids } => {
17283                self.refresh_inlay_hints(InlayHintRefreshReason::NewLinesShown, cx);
17284                cx.emit(EditorEvent::ExcerptsExpanded { ids: ids.clone() })
17285            }
17286            multi_buffer::Event::Reparsed(buffer_id) => {
17287                self.tasks_update_task = Some(self.refresh_runnables(window, cx));
17288                jsx_tag_auto_close::refresh_enabled_in_any_buffer(self, multibuffer, cx);
17289
17290                cx.emit(EditorEvent::Reparsed(*buffer_id));
17291            }
17292            multi_buffer::Event::DiffHunksToggled => {
17293                self.tasks_update_task = Some(self.refresh_runnables(window, cx));
17294            }
17295            multi_buffer::Event::LanguageChanged(buffer_id) => {
17296                linked_editing_ranges::refresh_linked_ranges(self, window, cx);
17297                jsx_tag_auto_close::refresh_enabled_in_any_buffer(self, multibuffer, cx);
17298                cx.emit(EditorEvent::Reparsed(*buffer_id));
17299                cx.notify();
17300            }
17301            multi_buffer::Event::DirtyChanged => cx.emit(EditorEvent::DirtyChanged),
17302            multi_buffer::Event::Saved => cx.emit(EditorEvent::Saved),
17303            multi_buffer::Event::FileHandleChanged
17304            | multi_buffer::Event::Reloaded
17305            | multi_buffer::Event::BufferDiffChanged => cx.emit(EditorEvent::TitleChanged),
17306            multi_buffer::Event::Closed => cx.emit(EditorEvent::Closed),
17307            multi_buffer::Event::DiagnosticsUpdated => {
17308                self.refresh_active_diagnostics(cx);
17309                self.refresh_inline_diagnostics(true, window, cx);
17310                self.scrollbar_marker_state.dirty = true;
17311                cx.notify();
17312            }
17313            _ => {}
17314        };
17315    }
17316
17317    fn on_display_map_changed(
17318        &mut self,
17319        _: Entity<DisplayMap>,
17320        _: &mut Window,
17321        cx: &mut Context<Self>,
17322    ) {
17323        cx.notify();
17324    }
17325
17326    fn settings_changed(&mut self, window: &mut Window, cx: &mut Context<Self>) {
17327        self.tasks_update_task = Some(self.refresh_runnables(window, cx));
17328        self.update_edit_prediction_settings(cx);
17329        self.refresh_inline_completion(true, false, window, cx);
17330        self.refresh_inlay_hints(
17331            InlayHintRefreshReason::SettingsChange(inlay_hint_settings(
17332                self.selections.newest_anchor().head(),
17333                &self.buffer.read(cx).snapshot(cx),
17334                cx,
17335            )),
17336            cx,
17337        );
17338
17339        let old_cursor_shape = self.cursor_shape;
17340
17341        {
17342            let editor_settings = EditorSettings::get_global(cx);
17343            self.scroll_manager.vertical_scroll_margin = editor_settings.vertical_scroll_margin;
17344            self.show_breadcrumbs = editor_settings.toolbar.breadcrumbs;
17345            self.cursor_shape = editor_settings.cursor_shape.unwrap_or_default();
17346            self.hide_mouse_mode = editor_settings.hide_mouse.unwrap_or_default();
17347        }
17348
17349        if old_cursor_shape != self.cursor_shape {
17350            cx.emit(EditorEvent::CursorShapeChanged);
17351        }
17352
17353        let project_settings = ProjectSettings::get_global(cx);
17354        self.serialize_dirty_buffers = project_settings.session.restore_unsaved_buffers;
17355
17356        if self.mode.is_full() {
17357            let show_inline_diagnostics = project_settings.diagnostics.inline.enabled;
17358            let inline_blame_enabled = project_settings.git.inline_blame_enabled();
17359            if self.show_inline_diagnostics != show_inline_diagnostics {
17360                self.show_inline_diagnostics = show_inline_diagnostics;
17361                self.refresh_inline_diagnostics(false, window, cx);
17362            }
17363
17364            if self.git_blame_inline_enabled != inline_blame_enabled {
17365                self.toggle_git_blame_inline_internal(false, window, cx);
17366            }
17367        }
17368
17369        cx.notify();
17370    }
17371
17372    pub fn set_searchable(&mut self, searchable: bool) {
17373        self.searchable = searchable;
17374    }
17375
17376    pub fn searchable(&self) -> bool {
17377        self.searchable
17378    }
17379
17380    fn open_proposed_changes_editor(
17381        &mut self,
17382        _: &OpenProposedChangesEditor,
17383        window: &mut Window,
17384        cx: &mut Context<Self>,
17385    ) {
17386        let Some(workspace) = self.workspace() else {
17387            cx.propagate();
17388            return;
17389        };
17390
17391        let selections = self.selections.all::<usize>(cx);
17392        let multi_buffer = self.buffer.read(cx);
17393        let multi_buffer_snapshot = multi_buffer.snapshot(cx);
17394        let mut new_selections_by_buffer = HashMap::default();
17395        for selection in selections {
17396            for (buffer, range, _) in
17397                multi_buffer_snapshot.range_to_buffer_ranges(selection.start..selection.end)
17398            {
17399                let mut range = range.to_point(buffer);
17400                range.start.column = 0;
17401                range.end.column = buffer.line_len(range.end.row);
17402                new_selections_by_buffer
17403                    .entry(multi_buffer.buffer(buffer.remote_id()).unwrap())
17404                    .or_insert(Vec::new())
17405                    .push(range)
17406            }
17407        }
17408
17409        let proposed_changes_buffers = new_selections_by_buffer
17410            .into_iter()
17411            .map(|(buffer, ranges)| ProposedChangeLocation { buffer, ranges })
17412            .collect::<Vec<_>>();
17413        let proposed_changes_editor = cx.new(|cx| {
17414            ProposedChangesEditor::new(
17415                "Proposed changes",
17416                proposed_changes_buffers,
17417                self.project.clone(),
17418                window,
17419                cx,
17420            )
17421        });
17422
17423        window.defer(cx, move |window, cx| {
17424            workspace.update(cx, |workspace, cx| {
17425                workspace.active_pane().update(cx, |pane, cx| {
17426                    pane.add_item(
17427                        Box::new(proposed_changes_editor),
17428                        true,
17429                        true,
17430                        None,
17431                        window,
17432                        cx,
17433                    );
17434                });
17435            });
17436        });
17437    }
17438
17439    pub fn open_excerpts_in_split(
17440        &mut self,
17441        _: &OpenExcerptsSplit,
17442        window: &mut Window,
17443        cx: &mut Context<Self>,
17444    ) {
17445        self.open_excerpts_common(None, true, window, cx)
17446    }
17447
17448    pub fn open_excerpts(&mut self, _: &OpenExcerpts, window: &mut Window, cx: &mut Context<Self>) {
17449        self.open_excerpts_common(None, false, window, cx)
17450    }
17451
17452    fn open_excerpts_common(
17453        &mut self,
17454        jump_data: Option<JumpData>,
17455        split: bool,
17456        window: &mut Window,
17457        cx: &mut Context<Self>,
17458    ) {
17459        let Some(workspace) = self.workspace() else {
17460            cx.propagate();
17461            return;
17462        };
17463
17464        if self.buffer.read(cx).is_singleton() {
17465            cx.propagate();
17466            return;
17467        }
17468
17469        let mut new_selections_by_buffer = HashMap::default();
17470        match &jump_data {
17471            Some(JumpData::MultiBufferPoint {
17472                excerpt_id,
17473                position,
17474                anchor,
17475                line_offset_from_top,
17476            }) => {
17477                let multi_buffer_snapshot = self.buffer.read(cx).snapshot(cx);
17478                if let Some(buffer) = multi_buffer_snapshot
17479                    .buffer_id_for_excerpt(*excerpt_id)
17480                    .and_then(|buffer_id| self.buffer.read(cx).buffer(buffer_id))
17481                {
17482                    let buffer_snapshot = buffer.read(cx).snapshot();
17483                    let jump_to_point = if buffer_snapshot.can_resolve(anchor) {
17484                        language::ToPoint::to_point(anchor, &buffer_snapshot)
17485                    } else {
17486                        buffer_snapshot.clip_point(*position, Bias::Left)
17487                    };
17488                    let jump_to_offset = buffer_snapshot.point_to_offset(jump_to_point);
17489                    new_selections_by_buffer.insert(
17490                        buffer,
17491                        (
17492                            vec![jump_to_offset..jump_to_offset],
17493                            Some(*line_offset_from_top),
17494                        ),
17495                    );
17496                }
17497            }
17498            Some(JumpData::MultiBufferRow {
17499                row,
17500                line_offset_from_top,
17501            }) => {
17502                let point = MultiBufferPoint::new(row.0, 0);
17503                if let Some((buffer, buffer_point, _)) =
17504                    self.buffer.read(cx).point_to_buffer_point(point, cx)
17505                {
17506                    let buffer_offset = buffer.read(cx).point_to_offset(buffer_point);
17507                    new_selections_by_buffer
17508                        .entry(buffer)
17509                        .or_insert((Vec::new(), Some(*line_offset_from_top)))
17510                        .0
17511                        .push(buffer_offset..buffer_offset)
17512                }
17513            }
17514            None => {
17515                let selections = self.selections.all::<usize>(cx);
17516                let multi_buffer = self.buffer.read(cx);
17517                for selection in selections {
17518                    for (snapshot, range, _, anchor) in multi_buffer
17519                        .snapshot(cx)
17520                        .range_to_buffer_ranges_with_deleted_hunks(selection.range())
17521                    {
17522                        if let Some(anchor) = anchor {
17523                            // selection is in a deleted hunk
17524                            let Some(buffer_id) = anchor.buffer_id else {
17525                                continue;
17526                            };
17527                            let Some(buffer_handle) = multi_buffer.buffer(buffer_id) else {
17528                                continue;
17529                            };
17530                            let offset = text::ToOffset::to_offset(
17531                                &anchor.text_anchor,
17532                                &buffer_handle.read(cx).snapshot(),
17533                            );
17534                            let range = offset..offset;
17535                            new_selections_by_buffer
17536                                .entry(buffer_handle)
17537                                .or_insert((Vec::new(), None))
17538                                .0
17539                                .push(range)
17540                        } else {
17541                            let Some(buffer_handle) = multi_buffer.buffer(snapshot.remote_id())
17542                            else {
17543                                continue;
17544                            };
17545                            new_selections_by_buffer
17546                                .entry(buffer_handle)
17547                                .or_insert((Vec::new(), None))
17548                                .0
17549                                .push(range)
17550                        }
17551                    }
17552                }
17553            }
17554        }
17555
17556        new_selections_by_buffer
17557            .retain(|buffer, _| Self::can_open_excerpts_in_file(buffer.read(cx).file()));
17558
17559        if new_selections_by_buffer.is_empty() {
17560            return;
17561        }
17562
17563        // We defer the pane interaction because we ourselves are a workspace item
17564        // and activating a new item causes the pane to call a method on us reentrantly,
17565        // which panics if we're on the stack.
17566        window.defer(cx, move |window, cx| {
17567            workspace.update(cx, |workspace, cx| {
17568                let pane = if split {
17569                    workspace.adjacent_pane(window, cx)
17570                } else {
17571                    workspace.active_pane().clone()
17572                };
17573
17574                for (buffer, (ranges, scroll_offset)) in new_selections_by_buffer {
17575                    let editor = buffer
17576                        .read(cx)
17577                        .file()
17578                        .is_none()
17579                        .then(|| {
17580                            // Handle file-less buffers separately: those are not really the project items, so won't have a project path or entity id,
17581                            // so `workspace.open_project_item` will never find them, always opening a new editor.
17582                            // Instead, we try to activate the existing editor in the pane first.
17583                            let (editor, pane_item_index) =
17584                                pane.read(cx).items().enumerate().find_map(|(i, item)| {
17585                                    let editor = item.downcast::<Editor>()?;
17586                                    let singleton_buffer =
17587                                        editor.read(cx).buffer().read(cx).as_singleton()?;
17588                                    if singleton_buffer == buffer {
17589                                        Some((editor, i))
17590                                    } else {
17591                                        None
17592                                    }
17593                                })?;
17594                            pane.update(cx, |pane, cx| {
17595                                pane.activate_item(pane_item_index, true, true, window, cx)
17596                            });
17597                            Some(editor)
17598                        })
17599                        .flatten()
17600                        .unwrap_or_else(|| {
17601                            workspace.open_project_item::<Self>(
17602                                pane.clone(),
17603                                buffer,
17604                                true,
17605                                true,
17606                                window,
17607                                cx,
17608                            )
17609                        });
17610
17611                    editor.update(cx, |editor, cx| {
17612                        let autoscroll = match scroll_offset {
17613                            Some(scroll_offset) => Autoscroll::top_relative(scroll_offset as usize),
17614                            None => Autoscroll::newest(),
17615                        };
17616                        let nav_history = editor.nav_history.take();
17617                        editor.change_selections(Some(autoscroll), window, cx, |s| {
17618                            s.select_ranges(ranges);
17619                        });
17620                        editor.nav_history = nav_history;
17621                    });
17622                }
17623            })
17624        });
17625    }
17626
17627    // For now, don't allow opening excerpts in buffers that aren't backed by
17628    // regular project files.
17629    fn can_open_excerpts_in_file(file: Option<&Arc<dyn language::File>>) -> bool {
17630        file.map_or(true, |file| project::File::from_dyn(Some(file)).is_some())
17631    }
17632
17633    fn marked_text_ranges(&self, cx: &App) -> Option<Vec<Range<OffsetUtf16>>> {
17634        let snapshot = self.buffer.read(cx).read(cx);
17635        let (_, ranges) = self.text_highlights::<InputComposition>(cx)?;
17636        Some(
17637            ranges
17638                .iter()
17639                .map(move |range| {
17640                    range.start.to_offset_utf16(&snapshot)..range.end.to_offset_utf16(&snapshot)
17641                })
17642                .collect(),
17643        )
17644    }
17645
17646    fn selection_replacement_ranges(
17647        &self,
17648        range: Range<OffsetUtf16>,
17649        cx: &mut App,
17650    ) -> Vec<Range<OffsetUtf16>> {
17651        let selections = self.selections.all::<OffsetUtf16>(cx);
17652        let newest_selection = selections
17653            .iter()
17654            .max_by_key(|selection| selection.id)
17655            .unwrap();
17656        let start_delta = range.start.0 as isize - newest_selection.start.0 as isize;
17657        let end_delta = range.end.0 as isize - newest_selection.end.0 as isize;
17658        let snapshot = self.buffer.read(cx).read(cx);
17659        selections
17660            .into_iter()
17661            .map(|mut selection| {
17662                selection.start.0 =
17663                    (selection.start.0 as isize).saturating_add(start_delta) as usize;
17664                selection.end.0 = (selection.end.0 as isize).saturating_add(end_delta) as usize;
17665                snapshot.clip_offset_utf16(selection.start, Bias::Left)
17666                    ..snapshot.clip_offset_utf16(selection.end, Bias::Right)
17667            })
17668            .collect()
17669    }
17670
17671    fn report_editor_event(
17672        &self,
17673        event_type: &'static str,
17674        file_extension: Option<String>,
17675        cx: &App,
17676    ) {
17677        if cfg!(any(test, feature = "test-support")) {
17678            return;
17679        }
17680
17681        let Some(project) = &self.project else { return };
17682
17683        // If None, we are in a file without an extension
17684        let file = self
17685            .buffer
17686            .read(cx)
17687            .as_singleton()
17688            .and_then(|b| b.read(cx).file());
17689        let file_extension = file_extension.or(file
17690            .as_ref()
17691            .and_then(|file| Path::new(file.file_name(cx)).extension())
17692            .and_then(|e| e.to_str())
17693            .map(|a| a.to_string()));
17694
17695        let vim_mode = cx
17696            .global::<SettingsStore>()
17697            .raw_user_settings()
17698            .get("vim_mode")
17699            == Some(&serde_json::Value::Bool(true));
17700
17701        let edit_predictions_provider = all_language_settings(file, cx).edit_predictions.provider;
17702        let copilot_enabled = edit_predictions_provider
17703            == language::language_settings::EditPredictionProvider::Copilot;
17704        let copilot_enabled_for_language = self
17705            .buffer
17706            .read(cx)
17707            .language_settings(cx)
17708            .show_edit_predictions;
17709
17710        let project = project.read(cx);
17711        telemetry::event!(
17712            event_type,
17713            file_extension,
17714            vim_mode,
17715            copilot_enabled,
17716            copilot_enabled_for_language,
17717            edit_predictions_provider,
17718            is_via_ssh = project.is_via_ssh(),
17719        );
17720    }
17721
17722    /// Copy the highlighted chunks to the clipboard as JSON. The format is an array of lines,
17723    /// with each line being an array of {text, highlight} objects.
17724    fn copy_highlight_json(
17725        &mut self,
17726        _: &CopyHighlightJson,
17727        window: &mut Window,
17728        cx: &mut Context<Self>,
17729    ) {
17730        #[derive(Serialize)]
17731        struct Chunk<'a> {
17732            text: String,
17733            highlight: Option<&'a str>,
17734        }
17735
17736        let snapshot = self.buffer.read(cx).snapshot(cx);
17737        let range = self
17738            .selected_text_range(false, window, cx)
17739            .and_then(|selection| {
17740                if selection.range.is_empty() {
17741                    None
17742                } else {
17743                    Some(selection.range)
17744                }
17745            })
17746            .unwrap_or_else(|| 0..snapshot.len());
17747
17748        let chunks = snapshot.chunks(range, true);
17749        let mut lines = Vec::new();
17750        let mut line: VecDeque<Chunk> = VecDeque::new();
17751
17752        let Some(style) = self.style.as_ref() else {
17753            return;
17754        };
17755
17756        for chunk in chunks {
17757            let highlight = chunk
17758                .syntax_highlight_id
17759                .and_then(|id| id.name(&style.syntax));
17760            let mut chunk_lines = chunk.text.split('\n').peekable();
17761            while let Some(text) = chunk_lines.next() {
17762                let mut merged_with_last_token = false;
17763                if let Some(last_token) = line.back_mut() {
17764                    if last_token.highlight == highlight {
17765                        last_token.text.push_str(text);
17766                        merged_with_last_token = true;
17767                    }
17768                }
17769
17770                if !merged_with_last_token {
17771                    line.push_back(Chunk {
17772                        text: text.into(),
17773                        highlight,
17774                    });
17775                }
17776
17777                if chunk_lines.peek().is_some() {
17778                    if line.len() > 1 && line.front().unwrap().text.is_empty() {
17779                        line.pop_front();
17780                    }
17781                    if line.len() > 1 && line.back().unwrap().text.is_empty() {
17782                        line.pop_back();
17783                    }
17784
17785                    lines.push(mem::take(&mut line));
17786                }
17787            }
17788        }
17789
17790        let Some(lines) = serde_json::to_string_pretty(&lines).log_err() else {
17791            return;
17792        };
17793        cx.write_to_clipboard(ClipboardItem::new_string(lines));
17794    }
17795
17796    pub fn open_context_menu(
17797        &mut self,
17798        _: &OpenContextMenu,
17799        window: &mut Window,
17800        cx: &mut Context<Self>,
17801    ) {
17802        self.request_autoscroll(Autoscroll::newest(), cx);
17803        let position = self.selections.newest_display(cx).start;
17804        mouse_context_menu::deploy_context_menu(self, None, position, window, cx);
17805    }
17806
17807    pub fn inlay_hint_cache(&self) -> &InlayHintCache {
17808        &self.inlay_hint_cache
17809    }
17810
17811    pub fn replay_insert_event(
17812        &mut self,
17813        text: &str,
17814        relative_utf16_range: Option<Range<isize>>,
17815        window: &mut Window,
17816        cx: &mut Context<Self>,
17817    ) {
17818        if !self.input_enabled {
17819            cx.emit(EditorEvent::InputIgnored { text: text.into() });
17820            return;
17821        }
17822        if let Some(relative_utf16_range) = relative_utf16_range {
17823            let selections = self.selections.all::<OffsetUtf16>(cx);
17824            self.change_selections(None, window, cx, |s| {
17825                let new_ranges = selections.into_iter().map(|range| {
17826                    let start = OffsetUtf16(
17827                        range
17828                            .head()
17829                            .0
17830                            .saturating_add_signed(relative_utf16_range.start),
17831                    );
17832                    let end = OffsetUtf16(
17833                        range
17834                            .head()
17835                            .0
17836                            .saturating_add_signed(relative_utf16_range.end),
17837                    );
17838                    start..end
17839                });
17840                s.select_ranges(new_ranges);
17841            });
17842        }
17843
17844        self.handle_input(text, window, cx);
17845    }
17846
17847    pub fn supports_inlay_hints(&self, cx: &mut App) -> bool {
17848        let Some(provider) = self.semantics_provider.as_ref() else {
17849            return false;
17850        };
17851
17852        let mut supports = false;
17853        self.buffer().update(cx, |this, cx| {
17854            this.for_each_buffer(|buffer| {
17855                supports |= provider.supports_inlay_hints(buffer, cx);
17856            });
17857        });
17858
17859        supports
17860    }
17861
17862    pub fn is_focused(&self, window: &Window) -> bool {
17863        self.focus_handle.is_focused(window)
17864    }
17865
17866    fn handle_focus(&mut self, window: &mut Window, cx: &mut Context<Self>) {
17867        cx.emit(EditorEvent::Focused);
17868
17869        if let Some(descendant) = self
17870            .last_focused_descendant
17871            .take()
17872            .and_then(|descendant| descendant.upgrade())
17873        {
17874            window.focus(&descendant);
17875        } else {
17876            if let Some(blame) = self.blame.as_ref() {
17877                blame.update(cx, GitBlame::focus)
17878            }
17879
17880            self.blink_manager.update(cx, BlinkManager::enable);
17881            self.show_cursor_names(window, cx);
17882            self.buffer.update(cx, |buffer, cx| {
17883                buffer.finalize_last_transaction(cx);
17884                if self.leader_peer_id.is_none() {
17885                    buffer.set_active_selections(
17886                        &self.selections.disjoint_anchors(),
17887                        self.selections.line_mode,
17888                        self.cursor_shape,
17889                        cx,
17890                    );
17891                }
17892            });
17893        }
17894    }
17895
17896    fn handle_focus_in(&mut self, _: &mut Window, cx: &mut Context<Self>) {
17897        cx.emit(EditorEvent::FocusedIn)
17898    }
17899
17900    fn handle_focus_out(
17901        &mut self,
17902        event: FocusOutEvent,
17903        _window: &mut Window,
17904        cx: &mut Context<Self>,
17905    ) {
17906        if event.blurred != self.focus_handle {
17907            self.last_focused_descendant = Some(event.blurred);
17908        }
17909        self.refresh_inlay_hints(InlayHintRefreshReason::ModifiersChanged(false), cx);
17910    }
17911
17912    pub fn handle_blur(&mut self, window: &mut Window, cx: &mut Context<Self>) {
17913        self.blink_manager.update(cx, BlinkManager::disable);
17914        self.buffer
17915            .update(cx, |buffer, cx| buffer.remove_active_selections(cx));
17916
17917        if let Some(blame) = self.blame.as_ref() {
17918            blame.update(cx, GitBlame::blur)
17919        }
17920        if !self.hover_state.focused(window, cx) {
17921            hide_hover(self, cx);
17922        }
17923        if !self
17924            .context_menu
17925            .borrow()
17926            .as_ref()
17927            .is_some_and(|context_menu| context_menu.focused(window, cx))
17928        {
17929            self.hide_context_menu(window, cx);
17930        }
17931        self.discard_inline_completion(false, cx);
17932        cx.emit(EditorEvent::Blurred);
17933        cx.notify();
17934    }
17935
17936    pub fn register_action<A: Action>(
17937        &mut self,
17938        listener: impl Fn(&A, &mut Window, &mut App) + 'static,
17939    ) -> Subscription {
17940        let id = self.next_editor_action_id.post_inc();
17941        let listener = Arc::new(listener);
17942        self.editor_actions.borrow_mut().insert(
17943            id,
17944            Box::new(move |window, _| {
17945                let listener = listener.clone();
17946                window.on_action(TypeId::of::<A>(), move |action, phase, window, cx| {
17947                    let action = action.downcast_ref().unwrap();
17948                    if phase == DispatchPhase::Bubble {
17949                        listener(action, window, cx)
17950                    }
17951                })
17952            }),
17953        );
17954
17955        let editor_actions = self.editor_actions.clone();
17956        Subscription::new(move || {
17957            editor_actions.borrow_mut().remove(&id);
17958        })
17959    }
17960
17961    pub fn file_header_size(&self) -> u32 {
17962        FILE_HEADER_HEIGHT
17963    }
17964
17965    pub fn restore(
17966        &mut self,
17967        revert_changes: HashMap<BufferId, Vec<(Range<text::Anchor>, Rope)>>,
17968        window: &mut Window,
17969        cx: &mut Context<Self>,
17970    ) {
17971        let workspace = self.workspace();
17972        let project = self.project.as_ref();
17973        let save_tasks = self.buffer().update(cx, |multi_buffer, cx| {
17974            let mut tasks = Vec::new();
17975            for (buffer_id, changes) in revert_changes {
17976                if let Some(buffer) = multi_buffer.buffer(buffer_id) {
17977                    buffer.update(cx, |buffer, cx| {
17978                        buffer.edit(
17979                            changes
17980                                .into_iter()
17981                                .map(|(range, text)| (range, text.to_string())),
17982                            None,
17983                            cx,
17984                        );
17985                    });
17986
17987                    if let Some(project) =
17988                        project.filter(|_| multi_buffer.all_diff_hunks_expanded())
17989                    {
17990                        project.update(cx, |project, cx| {
17991                            tasks.push((buffer.clone(), project.save_buffer(buffer, cx)));
17992                        })
17993                    }
17994                }
17995            }
17996            tasks
17997        });
17998        cx.spawn_in(window, async move |_, cx| {
17999            for (buffer, task) in save_tasks {
18000                let result = task.await;
18001                if result.is_err() {
18002                    let Some(path) = buffer
18003                        .read_with(cx, |buffer, cx| buffer.project_path(cx))
18004                        .ok()
18005                    else {
18006                        continue;
18007                    };
18008                    if let Some((workspace, path)) = workspace.as_ref().zip(path) {
18009                        let Some(task) = cx
18010                            .update_window_entity(&workspace, |workspace, window, cx| {
18011                                workspace
18012                                    .open_path_preview(path, None, false, false, false, window, cx)
18013                            })
18014                            .ok()
18015                        else {
18016                            continue;
18017                        };
18018                        task.await.log_err();
18019                    }
18020                }
18021            }
18022        })
18023        .detach();
18024        self.change_selections(None, window, cx, |selections| selections.refresh());
18025    }
18026
18027    pub fn to_pixel_point(
18028        &self,
18029        source: multi_buffer::Anchor,
18030        editor_snapshot: &EditorSnapshot,
18031        window: &mut Window,
18032    ) -> Option<gpui::Point<Pixels>> {
18033        let source_point = source.to_display_point(editor_snapshot);
18034        self.display_to_pixel_point(source_point, editor_snapshot, window)
18035    }
18036
18037    pub fn display_to_pixel_point(
18038        &self,
18039        source: DisplayPoint,
18040        editor_snapshot: &EditorSnapshot,
18041        window: &mut Window,
18042    ) -> Option<gpui::Point<Pixels>> {
18043        let line_height = self.style()?.text.line_height_in_pixels(window.rem_size());
18044        let text_layout_details = self.text_layout_details(window);
18045        let scroll_top = text_layout_details
18046            .scroll_anchor
18047            .scroll_position(editor_snapshot)
18048            .y;
18049
18050        if source.row().as_f32() < scroll_top.floor() {
18051            return None;
18052        }
18053        let source_x = editor_snapshot.x_for_display_point(source, &text_layout_details);
18054        let source_y = line_height * (source.row().as_f32() - scroll_top);
18055        Some(gpui::Point::new(source_x, source_y))
18056    }
18057
18058    pub fn has_visible_completions_menu(&self) -> bool {
18059        !self.edit_prediction_preview_is_active()
18060            && self.context_menu.borrow().as_ref().map_or(false, |menu| {
18061                menu.visible() && matches!(menu, CodeContextMenu::Completions(_))
18062            })
18063    }
18064
18065    pub fn register_addon<T: Addon>(&mut self, instance: T) {
18066        self.addons
18067            .insert(std::any::TypeId::of::<T>(), Box::new(instance));
18068    }
18069
18070    pub fn unregister_addon<T: Addon>(&mut self) {
18071        self.addons.remove(&std::any::TypeId::of::<T>());
18072    }
18073
18074    pub fn addon<T: Addon>(&self) -> Option<&T> {
18075        let type_id = std::any::TypeId::of::<T>();
18076        self.addons
18077            .get(&type_id)
18078            .and_then(|item| item.to_any().downcast_ref::<T>())
18079    }
18080
18081    fn character_size(&self, window: &mut Window) -> gpui::Size<Pixels> {
18082        let text_layout_details = self.text_layout_details(window);
18083        let style = &text_layout_details.editor_style;
18084        let font_id = window.text_system().resolve_font(&style.text.font());
18085        let font_size = style.text.font_size.to_pixels(window.rem_size());
18086        let line_height = style.text.line_height_in_pixels(window.rem_size());
18087        let em_width = window.text_system().em_width(font_id, font_size).unwrap();
18088
18089        gpui::Size::new(em_width, line_height)
18090    }
18091
18092    pub fn wait_for_diff_to_load(&self) -> Option<Shared<Task<()>>> {
18093        self.load_diff_task.clone()
18094    }
18095
18096    fn read_metadata_from_db(
18097        &mut self,
18098        item_id: u64,
18099        workspace_id: WorkspaceId,
18100        window: &mut Window,
18101        cx: &mut Context<Editor>,
18102    ) {
18103        if self.is_singleton(cx)
18104            && WorkspaceSettings::get(None, cx).restore_on_startup != RestoreOnStartupBehavior::None
18105        {
18106            let buffer_snapshot = OnceCell::new();
18107
18108            if let Some(folds) = DB.get_editor_folds(item_id, workspace_id).log_err() {
18109                if !folds.is_empty() {
18110                    let snapshot =
18111                        buffer_snapshot.get_or_init(|| self.buffer.read(cx).snapshot(cx));
18112                    self.fold_ranges(
18113                        folds
18114                            .into_iter()
18115                            .map(|(start, end)| {
18116                                snapshot.clip_offset(start, Bias::Left)
18117                                    ..snapshot.clip_offset(end, Bias::Right)
18118                            })
18119                            .collect(),
18120                        false,
18121                        window,
18122                        cx,
18123                    );
18124                }
18125            }
18126
18127            if let Some(selections) = DB.get_editor_selections(item_id, workspace_id).log_err() {
18128                if !selections.is_empty() {
18129                    let snapshot =
18130                        buffer_snapshot.get_or_init(|| self.buffer.read(cx).snapshot(cx));
18131                    self.change_selections(None, window, cx, |s| {
18132                        s.select_ranges(selections.into_iter().map(|(start, end)| {
18133                            snapshot.clip_offset(start, Bias::Left)
18134                                ..snapshot.clip_offset(end, Bias::Right)
18135                        }));
18136                    });
18137                }
18138            };
18139        }
18140
18141        self.read_scroll_position_from_db(item_id, workspace_id, window, cx);
18142    }
18143}
18144
18145// Consider user intent and default settings
18146fn choose_completion_range(
18147    completion: &Completion,
18148    intent: CompletionIntent,
18149    buffer: &Entity<Buffer>,
18150    cx: &mut Context<Editor>,
18151) -> Range<usize> {
18152    fn should_replace(
18153        completion: &Completion,
18154        insert_range: &Range<text::Anchor>,
18155        intent: CompletionIntent,
18156        completion_mode_setting: LspInsertMode,
18157        buffer: &Buffer,
18158    ) -> bool {
18159        // specific actions take precedence over settings
18160        match intent {
18161            CompletionIntent::CompleteWithInsert => return false,
18162            CompletionIntent::CompleteWithReplace => return true,
18163            CompletionIntent::Complete | CompletionIntent::Compose => {}
18164        }
18165
18166        match completion_mode_setting {
18167            LspInsertMode::Insert => false,
18168            LspInsertMode::Replace => true,
18169            LspInsertMode::ReplaceSubsequence => {
18170                let mut text_to_replace = buffer.chars_for_range(
18171                    buffer.anchor_before(completion.replace_range.start)
18172                        ..buffer.anchor_after(completion.replace_range.end),
18173                );
18174                let mut completion_text = completion.new_text.chars();
18175
18176                // is `text_to_replace` a subsequence of `completion_text`
18177                text_to_replace
18178                    .all(|needle_ch| completion_text.any(|haystack_ch| haystack_ch == needle_ch))
18179            }
18180            LspInsertMode::ReplaceSuffix => {
18181                let range_after_cursor = insert_range.end..completion.replace_range.end;
18182
18183                let text_after_cursor = buffer
18184                    .text_for_range(
18185                        buffer.anchor_before(range_after_cursor.start)
18186                            ..buffer.anchor_after(range_after_cursor.end),
18187                    )
18188                    .collect::<String>();
18189                completion.new_text.ends_with(&text_after_cursor)
18190            }
18191        }
18192    }
18193
18194    let buffer = buffer.read(cx);
18195
18196    if let CompletionSource::Lsp {
18197        insert_range: Some(insert_range),
18198        ..
18199    } = &completion.source
18200    {
18201        let completion_mode_setting =
18202            language_settings(buffer.language().map(|l| l.name()), buffer.file(), cx)
18203                .completions
18204                .lsp_insert_mode;
18205
18206        if !should_replace(
18207            completion,
18208            &insert_range,
18209            intent,
18210            completion_mode_setting,
18211            buffer,
18212        ) {
18213            return insert_range.to_offset(buffer);
18214        }
18215    }
18216
18217    completion.replace_range.to_offset(buffer)
18218}
18219
18220fn insert_extra_newline_brackets(
18221    buffer: &MultiBufferSnapshot,
18222    range: Range<usize>,
18223    language: &language::LanguageScope,
18224) -> bool {
18225    let leading_whitespace_len = buffer
18226        .reversed_chars_at(range.start)
18227        .take_while(|c| c.is_whitespace() && *c != '\n')
18228        .map(|c| c.len_utf8())
18229        .sum::<usize>();
18230    let trailing_whitespace_len = buffer
18231        .chars_at(range.end)
18232        .take_while(|c| c.is_whitespace() && *c != '\n')
18233        .map(|c| c.len_utf8())
18234        .sum::<usize>();
18235    let range = range.start - leading_whitespace_len..range.end + trailing_whitespace_len;
18236
18237    language.brackets().any(|(pair, enabled)| {
18238        let pair_start = pair.start.trim_end();
18239        let pair_end = pair.end.trim_start();
18240
18241        enabled
18242            && pair.newline
18243            && buffer.contains_str_at(range.end, pair_end)
18244            && buffer.contains_str_at(range.start.saturating_sub(pair_start.len()), pair_start)
18245    })
18246}
18247
18248fn insert_extra_newline_tree_sitter(buffer: &MultiBufferSnapshot, range: Range<usize>) -> bool {
18249    let (buffer, range) = match buffer.range_to_buffer_ranges(range).as_slice() {
18250        [(buffer, range, _)] => (*buffer, range.clone()),
18251        _ => return false,
18252    };
18253    let pair = {
18254        let mut result: Option<BracketMatch> = None;
18255
18256        for pair in buffer
18257            .all_bracket_ranges(range.clone())
18258            .filter(move |pair| {
18259                pair.open_range.start <= range.start && pair.close_range.end >= range.end
18260            })
18261        {
18262            let len = pair.close_range.end - pair.open_range.start;
18263
18264            if let Some(existing) = &result {
18265                let existing_len = existing.close_range.end - existing.open_range.start;
18266                if len > existing_len {
18267                    continue;
18268                }
18269            }
18270
18271            result = Some(pair);
18272        }
18273
18274        result
18275    };
18276    let Some(pair) = pair else {
18277        return false;
18278    };
18279    pair.newline_only
18280        && buffer
18281            .chars_for_range(pair.open_range.end..range.start)
18282            .chain(buffer.chars_for_range(range.end..pair.close_range.start))
18283            .all(|c| c.is_whitespace() && c != '\n')
18284}
18285
18286fn get_uncommitted_diff_for_buffer(
18287    project: &Entity<Project>,
18288    buffers: impl IntoIterator<Item = Entity<Buffer>>,
18289    buffer: Entity<MultiBuffer>,
18290    cx: &mut App,
18291) -> Task<()> {
18292    let mut tasks = Vec::new();
18293    project.update(cx, |project, cx| {
18294        for buffer in buffers {
18295            if project::File::from_dyn(buffer.read(cx).file()).is_some() {
18296                tasks.push(project.open_uncommitted_diff(buffer.clone(), cx))
18297            }
18298        }
18299    });
18300    cx.spawn(async move |cx| {
18301        let diffs = future::join_all(tasks).await;
18302        buffer
18303            .update(cx, |buffer, cx| {
18304                for diff in diffs.into_iter().flatten() {
18305                    buffer.add_diff(diff, cx);
18306                }
18307            })
18308            .ok();
18309    })
18310}
18311
18312fn char_len_with_expanded_tabs(offset: usize, text: &str, tab_size: NonZeroU32) -> usize {
18313    let tab_size = tab_size.get() as usize;
18314    let mut width = offset;
18315
18316    for ch in text.chars() {
18317        width += if ch == '\t' {
18318            tab_size - (width % tab_size)
18319        } else {
18320            1
18321        };
18322    }
18323
18324    width - offset
18325}
18326
18327#[cfg(test)]
18328mod tests {
18329    use super::*;
18330
18331    #[test]
18332    fn test_string_size_with_expanded_tabs() {
18333        let nz = |val| NonZeroU32::new(val).unwrap();
18334        assert_eq!(char_len_with_expanded_tabs(0, "", nz(4)), 0);
18335        assert_eq!(char_len_with_expanded_tabs(0, "hello", nz(4)), 5);
18336        assert_eq!(char_len_with_expanded_tabs(0, "\thello", nz(4)), 9);
18337        assert_eq!(char_len_with_expanded_tabs(0, "abc\tab", nz(4)), 6);
18338        assert_eq!(char_len_with_expanded_tabs(0, "hello\t", nz(4)), 8);
18339        assert_eq!(char_len_with_expanded_tabs(0, "\t\t", nz(8)), 16);
18340        assert_eq!(char_len_with_expanded_tabs(0, "x\t", nz(8)), 8);
18341        assert_eq!(char_len_with_expanded_tabs(7, "x\t", nz(8)), 9);
18342    }
18343}
18344
18345/// Tokenizes a string into runs of text that should stick together, or that is whitespace.
18346struct WordBreakingTokenizer<'a> {
18347    input: &'a str,
18348}
18349
18350impl<'a> WordBreakingTokenizer<'a> {
18351    fn new(input: &'a str) -> Self {
18352        Self { input }
18353    }
18354}
18355
18356fn is_char_ideographic(ch: char) -> bool {
18357    use unicode_script::Script::*;
18358    use unicode_script::UnicodeScript;
18359    matches!(ch.script(), Han | Tangut | Yi)
18360}
18361
18362fn is_grapheme_ideographic(text: &str) -> bool {
18363    text.chars().any(is_char_ideographic)
18364}
18365
18366fn is_grapheme_whitespace(text: &str) -> bool {
18367    text.chars().any(|x| x.is_whitespace())
18368}
18369
18370fn should_stay_with_preceding_ideograph(text: &str) -> bool {
18371    text.chars().next().map_or(false, |ch| {
18372        matches!(ch, '。' | '、' | ',' | '?' | '!' | ':' | ';' | '…')
18373    })
18374}
18375
18376#[derive(PartialEq, Eq, Debug, Clone, Copy)]
18377enum WordBreakToken<'a> {
18378    Word { token: &'a str, grapheme_len: usize },
18379    InlineWhitespace { token: &'a str, grapheme_len: usize },
18380    Newline,
18381}
18382
18383impl<'a> Iterator for WordBreakingTokenizer<'a> {
18384    /// Yields a span, the count of graphemes in the token, and whether it was
18385    /// whitespace. Note that it also breaks at word boundaries.
18386    type Item = WordBreakToken<'a>;
18387
18388    fn next(&mut self) -> Option<Self::Item> {
18389        use unicode_segmentation::UnicodeSegmentation;
18390        if self.input.is_empty() {
18391            return None;
18392        }
18393
18394        let mut iter = self.input.graphemes(true).peekable();
18395        let mut offset = 0;
18396        let mut grapheme_len = 0;
18397        if let Some(first_grapheme) = iter.next() {
18398            let is_newline = first_grapheme == "\n";
18399            let is_whitespace = is_grapheme_whitespace(first_grapheme);
18400            offset += first_grapheme.len();
18401            grapheme_len += 1;
18402            if is_grapheme_ideographic(first_grapheme) && !is_whitespace {
18403                if let Some(grapheme) = iter.peek().copied() {
18404                    if should_stay_with_preceding_ideograph(grapheme) {
18405                        offset += grapheme.len();
18406                        grapheme_len += 1;
18407                    }
18408                }
18409            } else {
18410                let mut words = self.input[offset..].split_word_bound_indices().peekable();
18411                let mut next_word_bound = words.peek().copied();
18412                if next_word_bound.map_or(false, |(i, _)| i == 0) {
18413                    next_word_bound = words.next();
18414                }
18415                while let Some(grapheme) = iter.peek().copied() {
18416                    if next_word_bound.map_or(false, |(i, _)| i == offset) {
18417                        break;
18418                    };
18419                    if is_grapheme_whitespace(grapheme) != is_whitespace
18420                        || (grapheme == "\n") != is_newline
18421                    {
18422                        break;
18423                    };
18424                    offset += grapheme.len();
18425                    grapheme_len += 1;
18426                    iter.next();
18427                }
18428            }
18429            let token = &self.input[..offset];
18430            self.input = &self.input[offset..];
18431            if token == "\n" {
18432                Some(WordBreakToken::Newline)
18433            } else if is_whitespace {
18434                Some(WordBreakToken::InlineWhitespace {
18435                    token,
18436                    grapheme_len,
18437                })
18438            } else {
18439                Some(WordBreakToken::Word {
18440                    token,
18441                    grapheme_len,
18442                })
18443            }
18444        } else {
18445            None
18446        }
18447    }
18448}
18449
18450#[test]
18451fn test_word_breaking_tokenizer() {
18452    let tests: &[(&str, &[WordBreakToken<'static>])] = &[
18453        ("", &[]),
18454        ("  ", &[whitespace("  ", 2)]),
18455        ("Ʒ", &[word("Ʒ", 1)]),
18456        ("Ǽ", &[word("Ǽ", 1)]),
18457        ("", &[word("", 1)]),
18458        ("⋑⋑", &[word("⋑⋑", 2)]),
18459        (
18460            "原理,进而",
18461            &[word("", 1), word("理,", 2), word("", 1), word("", 1)],
18462        ),
18463        (
18464            "hello world",
18465            &[word("hello", 5), whitespace(" ", 1), word("world", 5)],
18466        ),
18467        (
18468            "hello, world",
18469            &[word("hello,", 6), whitespace(" ", 1), word("world", 5)],
18470        ),
18471        (
18472            "  hello world",
18473            &[
18474                whitespace("  ", 2),
18475                word("hello", 5),
18476                whitespace(" ", 1),
18477                word("world", 5),
18478            ],
18479        ),
18480        (
18481            "这是什么 \n 钢笔",
18482            &[
18483                word("", 1),
18484                word("", 1),
18485                word("", 1),
18486                word("", 1),
18487                whitespace(" ", 1),
18488                newline(),
18489                whitespace(" ", 1),
18490                word("", 1),
18491                word("", 1),
18492            ],
18493        ),
18494        (" mutton", &[whitespace("", 1), word("mutton", 6)]),
18495    ];
18496
18497    fn word(token: &'static str, grapheme_len: usize) -> WordBreakToken<'static> {
18498        WordBreakToken::Word {
18499            token,
18500            grapheme_len,
18501        }
18502    }
18503
18504    fn whitespace(token: &'static str, grapheme_len: usize) -> WordBreakToken<'static> {
18505        WordBreakToken::InlineWhitespace {
18506            token,
18507            grapheme_len,
18508        }
18509    }
18510
18511    fn newline() -> WordBreakToken<'static> {
18512        WordBreakToken::Newline
18513    }
18514
18515    for (input, result) in tests {
18516        assert_eq!(
18517            WordBreakingTokenizer::new(input)
18518                .collect::<Vec<_>>()
18519                .as_slice(),
18520            *result,
18521        );
18522    }
18523}
18524
18525fn wrap_with_prefix(
18526    line_prefix: String,
18527    unwrapped_text: String,
18528    wrap_column: usize,
18529    tab_size: NonZeroU32,
18530    preserve_existing_whitespace: bool,
18531) -> String {
18532    let line_prefix_len = char_len_with_expanded_tabs(0, &line_prefix, tab_size);
18533    let mut wrapped_text = String::new();
18534    let mut current_line = line_prefix.clone();
18535
18536    let tokenizer = WordBreakingTokenizer::new(&unwrapped_text);
18537    let mut current_line_len = line_prefix_len;
18538    let mut in_whitespace = false;
18539    for token in tokenizer {
18540        let have_preceding_whitespace = in_whitespace;
18541        match token {
18542            WordBreakToken::Word {
18543                token,
18544                grapheme_len,
18545            } => {
18546                in_whitespace = false;
18547                if current_line_len + grapheme_len > wrap_column
18548                    && current_line_len != line_prefix_len
18549                {
18550                    wrapped_text.push_str(current_line.trim_end());
18551                    wrapped_text.push('\n');
18552                    current_line.truncate(line_prefix.len());
18553                    current_line_len = line_prefix_len;
18554                }
18555                current_line.push_str(token);
18556                current_line_len += grapheme_len;
18557            }
18558            WordBreakToken::InlineWhitespace {
18559                mut token,
18560                mut grapheme_len,
18561            } => {
18562                in_whitespace = true;
18563                if have_preceding_whitespace && !preserve_existing_whitespace {
18564                    continue;
18565                }
18566                if !preserve_existing_whitespace {
18567                    token = " ";
18568                    grapheme_len = 1;
18569                }
18570                if current_line_len + grapheme_len > wrap_column {
18571                    wrapped_text.push_str(current_line.trim_end());
18572                    wrapped_text.push('\n');
18573                    current_line.truncate(line_prefix.len());
18574                    current_line_len = line_prefix_len;
18575                } else if current_line_len != line_prefix_len || preserve_existing_whitespace {
18576                    current_line.push_str(token);
18577                    current_line_len += grapheme_len;
18578                }
18579            }
18580            WordBreakToken::Newline => {
18581                in_whitespace = true;
18582                if preserve_existing_whitespace {
18583                    wrapped_text.push_str(current_line.trim_end());
18584                    wrapped_text.push('\n');
18585                    current_line.truncate(line_prefix.len());
18586                    current_line_len = line_prefix_len;
18587                } else if have_preceding_whitespace {
18588                    continue;
18589                } else if current_line_len + 1 > wrap_column && current_line_len != line_prefix_len
18590                {
18591                    wrapped_text.push_str(current_line.trim_end());
18592                    wrapped_text.push('\n');
18593                    current_line.truncate(line_prefix.len());
18594                    current_line_len = line_prefix_len;
18595                } else if current_line_len != line_prefix_len {
18596                    current_line.push(' ');
18597                    current_line_len += 1;
18598                }
18599            }
18600        }
18601    }
18602
18603    if !current_line.is_empty() {
18604        wrapped_text.push_str(&current_line);
18605    }
18606    wrapped_text
18607}
18608
18609#[test]
18610fn test_wrap_with_prefix() {
18611    assert_eq!(
18612        wrap_with_prefix(
18613            "# ".to_string(),
18614            "abcdefg".to_string(),
18615            4,
18616            NonZeroU32::new(4).unwrap(),
18617            false,
18618        ),
18619        "# abcdefg"
18620    );
18621    assert_eq!(
18622        wrap_with_prefix(
18623            "".to_string(),
18624            "\thello world".to_string(),
18625            8,
18626            NonZeroU32::new(4).unwrap(),
18627            false,
18628        ),
18629        "hello\nworld"
18630    );
18631    assert_eq!(
18632        wrap_with_prefix(
18633            "// ".to_string(),
18634            "xx \nyy zz aa bb cc".to_string(),
18635            12,
18636            NonZeroU32::new(4).unwrap(),
18637            false,
18638        ),
18639        "// xx yy zz\n// aa bb cc"
18640    );
18641    assert_eq!(
18642        wrap_with_prefix(
18643            String::new(),
18644            "这是什么 \n 钢笔".to_string(),
18645            3,
18646            NonZeroU32::new(4).unwrap(),
18647            false,
18648        ),
18649        "这是什\n么 钢\n"
18650    );
18651}
18652
18653pub trait CollaborationHub {
18654    fn collaborators<'a>(&self, cx: &'a App) -> &'a HashMap<PeerId, Collaborator>;
18655    fn user_participant_indices<'a>(&self, cx: &'a App) -> &'a HashMap<u64, ParticipantIndex>;
18656    fn user_names(&self, cx: &App) -> HashMap<u64, SharedString>;
18657}
18658
18659impl CollaborationHub for Entity<Project> {
18660    fn collaborators<'a>(&self, cx: &'a App) -> &'a HashMap<PeerId, Collaborator> {
18661        self.read(cx).collaborators()
18662    }
18663
18664    fn user_participant_indices<'a>(&self, cx: &'a App) -> &'a HashMap<u64, ParticipantIndex> {
18665        self.read(cx).user_store().read(cx).participant_indices()
18666    }
18667
18668    fn user_names(&self, cx: &App) -> HashMap<u64, SharedString> {
18669        let this = self.read(cx);
18670        let user_ids = this.collaborators().values().map(|c| c.user_id);
18671        this.user_store().read_with(cx, |user_store, cx| {
18672            user_store.participant_names(user_ids, cx)
18673        })
18674    }
18675}
18676
18677pub trait SemanticsProvider {
18678    fn hover(
18679        &self,
18680        buffer: &Entity<Buffer>,
18681        position: text::Anchor,
18682        cx: &mut App,
18683    ) -> Option<Task<Vec<project::Hover>>>;
18684
18685    fn inlay_hints(
18686        &self,
18687        buffer_handle: Entity<Buffer>,
18688        range: Range<text::Anchor>,
18689        cx: &mut App,
18690    ) -> Option<Task<anyhow::Result<Vec<InlayHint>>>>;
18691
18692    fn resolve_inlay_hint(
18693        &self,
18694        hint: InlayHint,
18695        buffer_handle: Entity<Buffer>,
18696        server_id: LanguageServerId,
18697        cx: &mut App,
18698    ) -> Option<Task<anyhow::Result<InlayHint>>>;
18699
18700    fn supports_inlay_hints(&self, buffer: &Entity<Buffer>, cx: &mut App) -> bool;
18701
18702    fn document_highlights(
18703        &self,
18704        buffer: &Entity<Buffer>,
18705        position: text::Anchor,
18706        cx: &mut App,
18707    ) -> Option<Task<Result<Vec<DocumentHighlight>>>>;
18708
18709    fn definitions(
18710        &self,
18711        buffer: &Entity<Buffer>,
18712        position: text::Anchor,
18713        kind: GotoDefinitionKind,
18714        cx: &mut App,
18715    ) -> Option<Task<Result<Vec<LocationLink>>>>;
18716
18717    fn range_for_rename(
18718        &self,
18719        buffer: &Entity<Buffer>,
18720        position: text::Anchor,
18721        cx: &mut App,
18722    ) -> Option<Task<Result<Option<Range<text::Anchor>>>>>;
18723
18724    fn perform_rename(
18725        &self,
18726        buffer: &Entity<Buffer>,
18727        position: text::Anchor,
18728        new_name: String,
18729        cx: &mut App,
18730    ) -> Option<Task<Result<ProjectTransaction>>>;
18731}
18732
18733pub trait CompletionProvider {
18734    fn completions(
18735        &self,
18736        excerpt_id: ExcerptId,
18737        buffer: &Entity<Buffer>,
18738        buffer_position: text::Anchor,
18739        trigger: CompletionContext,
18740        window: &mut Window,
18741        cx: &mut Context<Editor>,
18742    ) -> Task<Result<Option<Vec<Completion>>>>;
18743
18744    fn resolve_completions(
18745        &self,
18746        buffer: Entity<Buffer>,
18747        completion_indices: Vec<usize>,
18748        completions: Rc<RefCell<Box<[Completion]>>>,
18749        cx: &mut Context<Editor>,
18750    ) -> Task<Result<bool>>;
18751
18752    fn apply_additional_edits_for_completion(
18753        &self,
18754        _buffer: Entity<Buffer>,
18755        _completions: Rc<RefCell<Box<[Completion]>>>,
18756        _completion_index: usize,
18757        _push_to_history: bool,
18758        _cx: &mut Context<Editor>,
18759    ) -> Task<Result<Option<language::Transaction>>> {
18760        Task::ready(Ok(None))
18761    }
18762
18763    fn is_completion_trigger(
18764        &self,
18765        buffer: &Entity<Buffer>,
18766        position: language::Anchor,
18767        text: &str,
18768        trigger_in_words: bool,
18769        cx: &mut Context<Editor>,
18770    ) -> bool;
18771
18772    fn sort_completions(&self) -> bool {
18773        true
18774    }
18775
18776    fn filter_completions(&self) -> bool {
18777        true
18778    }
18779}
18780
18781pub trait CodeActionProvider {
18782    fn id(&self) -> Arc<str>;
18783
18784    fn code_actions(
18785        &self,
18786        buffer: &Entity<Buffer>,
18787        range: Range<text::Anchor>,
18788        window: &mut Window,
18789        cx: &mut App,
18790    ) -> Task<Result<Vec<CodeAction>>>;
18791
18792    fn apply_code_action(
18793        &self,
18794        buffer_handle: Entity<Buffer>,
18795        action: CodeAction,
18796        excerpt_id: ExcerptId,
18797        push_to_history: bool,
18798        window: &mut Window,
18799        cx: &mut App,
18800    ) -> Task<Result<ProjectTransaction>>;
18801}
18802
18803impl CodeActionProvider for Entity<Project> {
18804    fn id(&self) -> Arc<str> {
18805        "project".into()
18806    }
18807
18808    fn code_actions(
18809        &self,
18810        buffer: &Entity<Buffer>,
18811        range: Range<text::Anchor>,
18812        _window: &mut Window,
18813        cx: &mut App,
18814    ) -> Task<Result<Vec<CodeAction>>> {
18815        self.update(cx, |project, cx| {
18816            let code_lens = project.code_lens(buffer, range.clone(), cx);
18817            let code_actions = project.code_actions(buffer, range, None, cx);
18818            cx.background_spawn(async move {
18819                let (code_lens, code_actions) = join(code_lens, code_actions).await;
18820                Ok(code_lens
18821                    .context("code lens fetch")?
18822                    .into_iter()
18823                    .chain(code_actions.context("code action fetch")?)
18824                    .collect())
18825            })
18826        })
18827    }
18828
18829    fn apply_code_action(
18830        &self,
18831        buffer_handle: Entity<Buffer>,
18832        action: CodeAction,
18833        _excerpt_id: ExcerptId,
18834        push_to_history: bool,
18835        _window: &mut Window,
18836        cx: &mut App,
18837    ) -> Task<Result<ProjectTransaction>> {
18838        self.update(cx, |project, cx| {
18839            project.apply_code_action(buffer_handle, action, push_to_history, cx)
18840        })
18841    }
18842}
18843
18844fn snippet_completions(
18845    project: &Project,
18846    buffer: &Entity<Buffer>,
18847    buffer_position: text::Anchor,
18848    cx: &mut App,
18849) -> Task<Result<Vec<Completion>>> {
18850    let language = buffer.read(cx).language_at(buffer_position);
18851    let language_name = language.as_ref().map(|language| language.lsp_id());
18852    let snippet_store = project.snippets().read(cx);
18853    let snippets = snippet_store.snippets_for(language_name, cx);
18854
18855    if snippets.is_empty() {
18856        return Task::ready(Ok(vec![]));
18857    }
18858    let snapshot = buffer.read(cx).text_snapshot();
18859    let chars: String = snapshot
18860        .reversed_chars_for_range(text::Anchor::MIN..buffer_position)
18861        .collect();
18862
18863    let scope = language.map(|language| language.default_scope());
18864    let executor = cx.background_executor().clone();
18865
18866    cx.background_spawn(async move {
18867        let classifier = CharClassifier::new(scope).for_completion(true);
18868        let mut last_word = chars
18869            .chars()
18870            .take_while(|c| classifier.is_word(*c))
18871            .collect::<String>();
18872        last_word = last_word.chars().rev().collect();
18873
18874        if last_word.is_empty() {
18875            return Ok(vec![]);
18876        }
18877
18878        let as_offset = text::ToOffset::to_offset(&buffer_position, &snapshot);
18879        let to_lsp = |point: &text::Anchor| {
18880            let end = text::ToPointUtf16::to_point_utf16(point, &snapshot);
18881            point_to_lsp(end)
18882        };
18883        let lsp_end = to_lsp(&buffer_position);
18884
18885        let candidates = snippets
18886            .iter()
18887            .enumerate()
18888            .flat_map(|(ix, snippet)| {
18889                snippet
18890                    .prefix
18891                    .iter()
18892                    .map(move |prefix| StringMatchCandidate::new(ix, &prefix))
18893            })
18894            .collect::<Vec<StringMatchCandidate>>();
18895
18896        let mut matches = fuzzy::match_strings(
18897            &candidates,
18898            &last_word,
18899            last_word.chars().any(|c| c.is_uppercase()),
18900            100,
18901            &Default::default(),
18902            executor,
18903        )
18904        .await;
18905
18906        // Remove all candidates where the query's start does not match the start of any word in the candidate
18907        if let Some(query_start) = last_word.chars().next() {
18908            matches.retain(|string_match| {
18909                split_words(&string_match.string).any(|word| {
18910                    // Check that the first codepoint of the word as lowercase matches the first
18911                    // codepoint of the query as lowercase
18912                    word.chars()
18913                        .flat_map(|codepoint| codepoint.to_lowercase())
18914                        .zip(query_start.to_lowercase())
18915                        .all(|(word_cp, query_cp)| word_cp == query_cp)
18916                })
18917            });
18918        }
18919
18920        let matched_strings = matches
18921            .into_iter()
18922            .map(|m| m.string)
18923            .collect::<HashSet<_>>();
18924
18925        let result: Vec<Completion> = snippets
18926            .into_iter()
18927            .filter_map(|snippet| {
18928                let matching_prefix = snippet
18929                    .prefix
18930                    .iter()
18931                    .find(|prefix| matched_strings.contains(*prefix))?;
18932                let start = as_offset - last_word.len();
18933                let start = snapshot.anchor_before(start);
18934                let range = start..buffer_position;
18935                let lsp_start = to_lsp(&start);
18936                let lsp_range = lsp::Range {
18937                    start: lsp_start,
18938                    end: lsp_end,
18939                };
18940                Some(Completion {
18941                    replace_range: range,
18942                    new_text: snippet.body.clone(),
18943                    source: CompletionSource::Lsp {
18944                        insert_range: None,
18945                        server_id: LanguageServerId(usize::MAX),
18946                        resolved: true,
18947                        lsp_completion: Box::new(lsp::CompletionItem {
18948                            label: snippet.prefix.first().unwrap().clone(),
18949                            kind: Some(CompletionItemKind::SNIPPET),
18950                            label_details: snippet.description.as_ref().map(|description| {
18951                                lsp::CompletionItemLabelDetails {
18952                                    detail: Some(description.clone()),
18953                                    description: None,
18954                                }
18955                            }),
18956                            insert_text_format: Some(InsertTextFormat::SNIPPET),
18957                            text_edit: Some(lsp::CompletionTextEdit::InsertAndReplace(
18958                                lsp::InsertReplaceEdit {
18959                                    new_text: snippet.body.clone(),
18960                                    insert: lsp_range,
18961                                    replace: lsp_range,
18962                                },
18963                            )),
18964                            filter_text: Some(snippet.body.clone()),
18965                            sort_text: Some(char::MAX.to_string()),
18966                            ..lsp::CompletionItem::default()
18967                        }),
18968                        lsp_defaults: None,
18969                    },
18970                    label: CodeLabel {
18971                        text: matching_prefix.clone(),
18972                        runs: Vec::new(),
18973                        filter_range: 0..matching_prefix.len(),
18974                    },
18975                    icon_path: None,
18976                    documentation: snippet
18977                        .description
18978                        .clone()
18979                        .map(|description| CompletionDocumentation::SingleLine(description.into())),
18980                    insert_text_mode: None,
18981                    confirm: None,
18982                })
18983            })
18984            .collect();
18985
18986        Ok(result)
18987    })
18988}
18989
18990impl CompletionProvider for Entity<Project> {
18991    fn completions(
18992        &self,
18993        _excerpt_id: ExcerptId,
18994        buffer: &Entity<Buffer>,
18995        buffer_position: text::Anchor,
18996        options: CompletionContext,
18997        _window: &mut Window,
18998        cx: &mut Context<Editor>,
18999    ) -> Task<Result<Option<Vec<Completion>>>> {
19000        self.update(cx, |project, cx| {
19001            let snippets = snippet_completions(project, buffer, buffer_position, cx);
19002            let project_completions = project.completions(buffer, buffer_position, options, cx);
19003            cx.background_spawn(async move {
19004                let snippets_completions = snippets.await?;
19005                match project_completions.await? {
19006                    Some(mut completions) => {
19007                        completions.extend(snippets_completions);
19008                        Ok(Some(completions))
19009                    }
19010                    None => {
19011                        if snippets_completions.is_empty() {
19012                            Ok(None)
19013                        } else {
19014                            Ok(Some(snippets_completions))
19015                        }
19016                    }
19017                }
19018            })
19019        })
19020    }
19021
19022    fn resolve_completions(
19023        &self,
19024        buffer: Entity<Buffer>,
19025        completion_indices: Vec<usize>,
19026        completions: Rc<RefCell<Box<[Completion]>>>,
19027        cx: &mut Context<Editor>,
19028    ) -> Task<Result<bool>> {
19029        self.update(cx, |project, cx| {
19030            project.lsp_store().update(cx, |lsp_store, cx| {
19031                lsp_store.resolve_completions(buffer, completion_indices, completions, cx)
19032            })
19033        })
19034    }
19035
19036    fn apply_additional_edits_for_completion(
19037        &self,
19038        buffer: Entity<Buffer>,
19039        completions: Rc<RefCell<Box<[Completion]>>>,
19040        completion_index: usize,
19041        push_to_history: bool,
19042        cx: &mut Context<Editor>,
19043    ) -> Task<Result<Option<language::Transaction>>> {
19044        self.update(cx, |project, cx| {
19045            project.lsp_store().update(cx, |lsp_store, cx| {
19046                lsp_store.apply_additional_edits_for_completion(
19047                    buffer,
19048                    completions,
19049                    completion_index,
19050                    push_to_history,
19051                    cx,
19052                )
19053            })
19054        })
19055    }
19056
19057    fn is_completion_trigger(
19058        &self,
19059        buffer: &Entity<Buffer>,
19060        position: language::Anchor,
19061        text: &str,
19062        trigger_in_words: bool,
19063        cx: &mut Context<Editor>,
19064    ) -> bool {
19065        let mut chars = text.chars();
19066        let char = if let Some(char) = chars.next() {
19067            char
19068        } else {
19069            return false;
19070        };
19071        if chars.next().is_some() {
19072            return false;
19073        }
19074
19075        let buffer = buffer.read(cx);
19076        let snapshot = buffer.snapshot();
19077        if !snapshot.settings_at(position, cx).show_completions_on_input {
19078            return false;
19079        }
19080        let classifier = snapshot.char_classifier_at(position).for_completion(true);
19081        if trigger_in_words && classifier.is_word(char) {
19082            return true;
19083        }
19084
19085        buffer.completion_triggers().contains(text)
19086    }
19087}
19088
19089impl SemanticsProvider for Entity<Project> {
19090    fn hover(
19091        &self,
19092        buffer: &Entity<Buffer>,
19093        position: text::Anchor,
19094        cx: &mut App,
19095    ) -> Option<Task<Vec<project::Hover>>> {
19096        Some(self.update(cx, |project, cx| project.hover(buffer, position, cx)))
19097    }
19098
19099    fn document_highlights(
19100        &self,
19101        buffer: &Entity<Buffer>,
19102        position: text::Anchor,
19103        cx: &mut App,
19104    ) -> Option<Task<Result<Vec<DocumentHighlight>>>> {
19105        Some(self.update(cx, |project, cx| {
19106            project.document_highlights(buffer, position, cx)
19107        }))
19108    }
19109
19110    fn definitions(
19111        &self,
19112        buffer: &Entity<Buffer>,
19113        position: text::Anchor,
19114        kind: GotoDefinitionKind,
19115        cx: &mut App,
19116    ) -> Option<Task<Result<Vec<LocationLink>>>> {
19117        Some(self.update(cx, |project, cx| match kind {
19118            GotoDefinitionKind::Symbol => project.definition(&buffer, position, cx),
19119            GotoDefinitionKind::Declaration => project.declaration(&buffer, position, cx),
19120            GotoDefinitionKind::Type => project.type_definition(&buffer, position, cx),
19121            GotoDefinitionKind::Implementation => project.implementation(&buffer, position, cx),
19122        }))
19123    }
19124
19125    fn supports_inlay_hints(&self, buffer: &Entity<Buffer>, cx: &mut App) -> bool {
19126        // TODO: make this work for remote projects
19127        self.update(cx, |this, cx| {
19128            buffer.update(cx, |buffer, cx| {
19129                this.any_language_server_supports_inlay_hints(buffer, cx)
19130            })
19131        })
19132    }
19133
19134    fn inlay_hints(
19135        &self,
19136        buffer_handle: Entity<Buffer>,
19137        range: Range<text::Anchor>,
19138        cx: &mut App,
19139    ) -> Option<Task<anyhow::Result<Vec<InlayHint>>>> {
19140        Some(self.update(cx, |project, cx| {
19141            project.inlay_hints(buffer_handle, range, cx)
19142        }))
19143    }
19144
19145    fn resolve_inlay_hint(
19146        &self,
19147        hint: InlayHint,
19148        buffer_handle: Entity<Buffer>,
19149        server_id: LanguageServerId,
19150        cx: &mut App,
19151    ) -> Option<Task<anyhow::Result<InlayHint>>> {
19152        Some(self.update(cx, |project, cx| {
19153            project.resolve_inlay_hint(hint, buffer_handle, server_id, cx)
19154        }))
19155    }
19156
19157    fn range_for_rename(
19158        &self,
19159        buffer: &Entity<Buffer>,
19160        position: text::Anchor,
19161        cx: &mut App,
19162    ) -> Option<Task<Result<Option<Range<text::Anchor>>>>> {
19163        Some(self.update(cx, |project, cx| {
19164            let buffer = buffer.clone();
19165            let task = project.prepare_rename(buffer.clone(), position, cx);
19166            cx.spawn(async move |_, cx| {
19167                Ok(match task.await? {
19168                    PrepareRenameResponse::Success(range) => Some(range),
19169                    PrepareRenameResponse::InvalidPosition => None,
19170                    PrepareRenameResponse::OnlyUnpreparedRenameSupported => {
19171                        // Fallback on using TreeSitter info to determine identifier range
19172                        buffer.update(cx, |buffer, _| {
19173                            let snapshot = buffer.snapshot();
19174                            let (range, kind) = snapshot.surrounding_word(position);
19175                            if kind != Some(CharKind::Word) {
19176                                return None;
19177                            }
19178                            Some(
19179                                snapshot.anchor_before(range.start)
19180                                    ..snapshot.anchor_after(range.end),
19181                            )
19182                        })?
19183                    }
19184                })
19185            })
19186        }))
19187    }
19188
19189    fn perform_rename(
19190        &self,
19191        buffer: &Entity<Buffer>,
19192        position: text::Anchor,
19193        new_name: String,
19194        cx: &mut App,
19195    ) -> Option<Task<Result<ProjectTransaction>>> {
19196        Some(self.update(cx, |project, cx| {
19197            project.perform_rename(buffer.clone(), position, new_name, cx)
19198        }))
19199    }
19200}
19201
19202fn inlay_hint_settings(
19203    location: Anchor,
19204    snapshot: &MultiBufferSnapshot,
19205    cx: &mut Context<Editor>,
19206) -> InlayHintSettings {
19207    let file = snapshot.file_at(location);
19208    let language = snapshot.language_at(location).map(|l| l.name());
19209    language_settings(language, file, cx).inlay_hints
19210}
19211
19212fn consume_contiguous_rows(
19213    contiguous_row_selections: &mut Vec<Selection<Point>>,
19214    selection: &Selection<Point>,
19215    display_map: &DisplaySnapshot,
19216    selections: &mut Peekable<std::slice::Iter<Selection<Point>>>,
19217) -> (MultiBufferRow, MultiBufferRow) {
19218    contiguous_row_selections.push(selection.clone());
19219    let start_row = MultiBufferRow(selection.start.row);
19220    let mut end_row = ending_row(selection, display_map);
19221
19222    while let Some(next_selection) = selections.peek() {
19223        if next_selection.start.row <= end_row.0 {
19224            end_row = ending_row(next_selection, display_map);
19225            contiguous_row_selections.push(selections.next().unwrap().clone());
19226        } else {
19227            break;
19228        }
19229    }
19230    (start_row, end_row)
19231}
19232
19233fn ending_row(next_selection: &Selection<Point>, display_map: &DisplaySnapshot) -> MultiBufferRow {
19234    if next_selection.end.column > 0 || next_selection.is_empty() {
19235        MultiBufferRow(display_map.next_line_boundary(next_selection.end).0.row + 1)
19236    } else {
19237        MultiBufferRow(next_selection.end.row)
19238    }
19239}
19240
19241impl EditorSnapshot {
19242    pub fn remote_selections_in_range<'a>(
19243        &'a self,
19244        range: &'a Range<Anchor>,
19245        collaboration_hub: &dyn CollaborationHub,
19246        cx: &'a App,
19247    ) -> impl 'a + Iterator<Item = RemoteSelection> {
19248        let participant_names = collaboration_hub.user_names(cx);
19249        let participant_indices = collaboration_hub.user_participant_indices(cx);
19250        let collaborators_by_peer_id = collaboration_hub.collaborators(cx);
19251        let collaborators_by_replica_id = collaborators_by_peer_id
19252            .iter()
19253            .map(|(_, collaborator)| (collaborator.replica_id, collaborator))
19254            .collect::<HashMap<_, _>>();
19255        self.buffer_snapshot
19256            .selections_in_range(range, false)
19257            .filter_map(move |(replica_id, line_mode, cursor_shape, selection)| {
19258                let collaborator = collaborators_by_replica_id.get(&replica_id)?;
19259                let participant_index = participant_indices.get(&collaborator.user_id).copied();
19260                let user_name = participant_names.get(&collaborator.user_id).cloned();
19261                Some(RemoteSelection {
19262                    replica_id,
19263                    selection,
19264                    cursor_shape,
19265                    line_mode,
19266                    participant_index,
19267                    peer_id: collaborator.peer_id,
19268                    user_name,
19269                })
19270            })
19271    }
19272
19273    pub fn hunks_for_ranges(
19274        &self,
19275        ranges: impl IntoIterator<Item = Range<Point>>,
19276    ) -> Vec<MultiBufferDiffHunk> {
19277        let mut hunks = Vec::new();
19278        let mut processed_buffer_rows: HashMap<BufferId, HashSet<Range<text::Anchor>>> =
19279            HashMap::default();
19280        for query_range in ranges {
19281            let query_rows =
19282                MultiBufferRow(query_range.start.row)..MultiBufferRow(query_range.end.row + 1);
19283            for hunk in self.buffer_snapshot.diff_hunks_in_range(
19284                Point::new(query_rows.start.0, 0)..Point::new(query_rows.end.0, 0),
19285            ) {
19286                // Include deleted hunks that are adjacent to the query range, because
19287                // otherwise they would be missed.
19288                let mut intersects_range = hunk.row_range.overlaps(&query_rows);
19289                if hunk.status().is_deleted() {
19290                    intersects_range |= hunk.row_range.start == query_rows.end;
19291                    intersects_range |= hunk.row_range.end == query_rows.start;
19292                }
19293                if intersects_range {
19294                    if !processed_buffer_rows
19295                        .entry(hunk.buffer_id)
19296                        .or_default()
19297                        .insert(hunk.buffer_range.start..hunk.buffer_range.end)
19298                    {
19299                        continue;
19300                    }
19301                    hunks.push(hunk);
19302                }
19303            }
19304        }
19305
19306        hunks
19307    }
19308
19309    fn display_diff_hunks_for_rows<'a>(
19310        &'a self,
19311        display_rows: Range<DisplayRow>,
19312        folded_buffers: &'a HashSet<BufferId>,
19313    ) -> impl 'a + Iterator<Item = DisplayDiffHunk> {
19314        let buffer_start = DisplayPoint::new(display_rows.start, 0).to_point(self);
19315        let buffer_end = DisplayPoint::new(display_rows.end, 0).to_point(self);
19316
19317        self.buffer_snapshot
19318            .diff_hunks_in_range(buffer_start..buffer_end)
19319            .filter_map(|hunk| {
19320                if folded_buffers.contains(&hunk.buffer_id) {
19321                    return None;
19322                }
19323
19324                let hunk_start_point = Point::new(hunk.row_range.start.0, 0);
19325                let hunk_end_point = Point::new(hunk.row_range.end.0, 0);
19326
19327                let hunk_display_start = self.point_to_display_point(hunk_start_point, Bias::Left);
19328                let hunk_display_end = self.point_to_display_point(hunk_end_point, Bias::Right);
19329
19330                let display_hunk = if hunk_display_start.column() != 0 {
19331                    DisplayDiffHunk::Folded {
19332                        display_row: hunk_display_start.row(),
19333                    }
19334                } else {
19335                    let mut end_row = hunk_display_end.row();
19336                    if hunk_display_end.column() > 0 {
19337                        end_row.0 += 1;
19338                    }
19339                    let is_created_file = hunk.is_created_file();
19340                    DisplayDiffHunk::Unfolded {
19341                        status: hunk.status(),
19342                        diff_base_byte_range: hunk.diff_base_byte_range,
19343                        display_row_range: hunk_display_start.row()..end_row,
19344                        multi_buffer_range: Anchor::range_in_buffer(
19345                            hunk.excerpt_id,
19346                            hunk.buffer_id,
19347                            hunk.buffer_range,
19348                        ),
19349                        is_created_file,
19350                    }
19351                };
19352
19353                Some(display_hunk)
19354            })
19355    }
19356
19357    pub fn language_at<T: ToOffset>(&self, position: T) -> Option<&Arc<Language>> {
19358        self.display_snapshot.buffer_snapshot.language_at(position)
19359    }
19360
19361    pub fn is_focused(&self) -> bool {
19362        self.is_focused
19363    }
19364
19365    pub fn placeholder_text(&self) -> Option<&Arc<str>> {
19366        self.placeholder_text.as_ref()
19367    }
19368
19369    pub fn scroll_position(&self) -> gpui::Point<f32> {
19370        self.scroll_anchor.scroll_position(&self.display_snapshot)
19371    }
19372
19373    fn gutter_dimensions(
19374        &self,
19375        font_id: FontId,
19376        font_size: Pixels,
19377        max_line_number_width: Pixels,
19378        cx: &App,
19379    ) -> Option<GutterDimensions> {
19380        if !self.show_gutter {
19381            return None;
19382        }
19383
19384        let descent = cx.text_system().descent(font_id, font_size);
19385        let em_width = cx.text_system().em_width(font_id, font_size).log_err()?;
19386        let em_advance = cx.text_system().em_advance(font_id, font_size).log_err()?;
19387
19388        let show_git_gutter = self.show_git_diff_gutter.unwrap_or_else(|| {
19389            matches!(
19390                ProjectSettings::get_global(cx).git.git_gutter,
19391                Some(GitGutterSetting::TrackedFiles)
19392            )
19393        });
19394        let gutter_settings = EditorSettings::get_global(cx).gutter;
19395        let show_line_numbers = self
19396            .show_line_numbers
19397            .unwrap_or(gutter_settings.line_numbers);
19398        let line_gutter_width = if show_line_numbers {
19399            // Avoid flicker-like gutter resizes when the line number gains another digit and only resize the gutter on files with N*10^5 lines.
19400            let min_width_for_number_on_gutter = em_advance * MIN_LINE_NUMBER_DIGITS as f32;
19401            max_line_number_width.max(min_width_for_number_on_gutter)
19402        } else {
19403            0.0.into()
19404        };
19405
19406        let show_code_actions = self
19407            .show_code_actions
19408            .unwrap_or(gutter_settings.code_actions);
19409
19410        let show_runnables = self.show_runnables.unwrap_or(gutter_settings.runnables);
19411        let show_breakpoints = self.show_breakpoints.unwrap_or(gutter_settings.breakpoints);
19412
19413        let git_blame_entries_width =
19414            self.git_blame_gutter_max_author_length
19415                .map(|max_author_length| {
19416                    let renderer = cx.global::<GlobalBlameRenderer>().0.clone();
19417                    const MAX_RELATIVE_TIMESTAMP: &str = "60 minutes ago";
19418
19419                    /// The number of characters to dedicate to gaps and margins.
19420                    const SPACING_WIDTH: usize = 4;
19421
19422                    let max_char_count = max_author_length.min(renderer.max_author_length())
19423                        + ::git::SHORT_SHA_LENGTH
19424                        + MAX_RELATIVE_TIMESTAMP.len()
19425                        + SPACING_WIDTH;
19426
19427                    em_advance * max_char_count
19428                });
19429
19430        let is_singleton = self.buffer_snapshot.is_singleton();
19431
19432        let mut left_padding = git_blame_entries_width.unwrap_or(Pixels::ZERO);
19433        left_padding += if !is_singleton {
19434            em_width * 4.0
19435        } else if show_code_actions || show_runnables || show_breakpoints {
19436            em_width * 3.0
19437        } else if show_git_gutter && show_line_numbers {
19438            em_width * 2.0
19439        } else if show_git_gutter || show_line_numbers {
19440            em_width
19441        } else {
19442            px(0.)
19443        };
19444
19445        let shows_folds = is_singleton && gutter_settings.folds;
19446
19447        let right_padding = if shows_folds && show_line_numbers {
19448            em_width * 4.0
19449        } else if shows_folds || (!is_singleton && show_line_numbers) {
19450            em_width * 3.0
19451        } else if show_line_numbers {
19452            em_width
19453        } else {
19454            px(0.)
19455        };
19456
19457        Some(GutterDimensions {
19458            left_padding,
19459            right_padding,
19460            width: line_gutter_width + left_padding + right_padding,
19461            margin: -descent,
19462            git_blame_entries_width,
19463        })
19464    }
19465
19466    pub fn render_crease_toggle(
19467        &self,
19468        buffer_row: MultiBufferRow,
19469        row_contains_cursor: bool,
19470        editor: Entity<Editor>,
19471        window: &mut Window,
19472        cx: &mut App,
19473    ) -> Option<AnyElement> {
19474        let folded = self.is_line_folded(buffer_row);
19475        let mut is_foldable = false;
19476
19477        if let Some(crease) = self
19478            .crease_snapshot
19479            .query_row(buffer_row, &self.buffer_snapshot)
19480        {
19481            is_foldable = true;
19482            match crease {
19483                Crease::Inline { render_toggle, .. } | Crease::Block { render_toggle, .. } => {
19484                    if let Some(render_toggle) = render_toggle {
19485                        let toggle_callback =
19486                            Arc::new(move |folded, window: &mut Window, cx: &mut App| {
19487                                if folded {
19488                                    editor.update(cx, |editor, cx| {
19489                                        editor.fold_at(buffer_row, window, cx)
19490                                    });
19491                                } else {
19492                                    editor.update(cx, |editor, cx| {
19493                                        editor.unfold_at(buffer_row, window, cx)
19494                                    });
19495                                }
19496                            });
19497                        return Some((render_toggle)(
19498                            buffer_row,
19499                            folded,
19500                            toggle_callback,
19501                            window,
19502                            cx,
19503                        ));
19504                    }
19505                }
19506            }
19507        }
19508
19509        is_foldable |= self.starts_indent(buffer_row);
19510
19511        if folded || (is_foldable && (row_contains_cursor || self.gutter_hovered)) {
19512            Some(
19513                Disclosure::new(("gutter_crease", buffer_row.0), !folded)
19514                    .toggle_state(folded)
19515                    .on_click(window.listener_for(&editor, move |this, _e, window, cx| {
19516                        if folded {
19517                            this.unfold_at(buffer_row, window, cx);
19518                        } else {
19519                            this.fold_at(buffer_row, window, cx);
19520                        }
19521                    }))
19522                    .into_any_element(),
19523            )
19524        } else {
19525            None
19526        }
19527    }
19528
19529    pub fn render_crease_trailer(
19530        &self,
19531        buffer_row: MultiBufferRow,
19532        window: &mut Window,
19533        cx: &mut App,
19534    ) -> Option<AnyElement> {
19535        let folded = self.is_line_folded(buffer_row);
19536        if let Crease::Inline { render_trailer, .. } = self
19537            .crease_snapshot
19538            .query_row(buffer_row, &self.buffer_snapshot)?
19539        {
19540            let render_trailer = render_trailer.as_ref()?;
19541            Some(render_trailer(buffer_row, folded, window, cx))
19542        } else {
19543            None
19544        }
19545    }
19546}
19547
19548impl Deref for EditorSnapshot {
19549    type Target = DisplaySnapshot;
19550
19551    fn deref(&self) -> &Self::Target {
19552        &self.display_snapshot
19553    }
19554}
19555
19556#[derive(Clone, Debug, PartialEq, Eq)]
19557pub enum EditorEvent {
19558    InputIgnored {
19559        text: Arc<str>,
19560    },
19561    InputHandled {
19562        utf16_range_to_replace: Option<Range<isize>>,
19563        text: Arc<str>,
19564    },
19565    ExcerptsAdded {
19566        buffer: Entity<Buffer>,
19567        predecessor: ExcerptId,
19568        excerpts: Vec<(ExcerptId, ExcerptRange<language::Anchor>)>,
19569    },
19570    ExcerptsRemoved {
19571        ids: Vec<ExcerptId>,
19572    },
19573    BufferFoldToggled {
19574        ids: Vec<ExcerptId>,
19575        folded: bool,
19576    },
19577    ExcerptsEdited {
19578        ids: Vec<ExcerptId>,
19579    },
19580    ExcerptsExpanded {
19581        ids: Vec<ExcerptId>,
19582    },
19583    BufferEdited,
19584    Edited {
19585        transaction_id: clock::Lamport,
19586    },
19587    Reparsed(BufferId),
19588    Focused,
19589    FocusedIn,
19590    Blurred,
19591    DirtyChanged,
19592    Saved,
19593    TitleChanged,
19594    DiffBaseChanged,
19595    SelectionsChanged {
19596        local: bool,
19597    },
19598    ScrollPositionChanged {
19599        local: bool,
19600        autoscroll: bool,
19601    },
19602    Closed,
19603    TransactionUndone {
19604        transaction_id: clock::Lamport,
19605    },
19606    TransactionBegun {
19607        transaction_id: clock::Lamport,
19608    },
19609    Reloaded,
19610    CursorShapeChanged,
19611    PushedToNavHistory {
19612        anchor: Anchor,
19613        is_deactivate: bool,
19614    },
19615}
19616
19617impl EventEmitter<EditorEvent> for Editor {}
19618
19619impl Focusable for Editor {
19620    fn focus_handle(&self, _cx: &App) -> FocusHandle {
19621        self.focus_handle.clone()
19622    }
19623}
19624
19625impl Render for Editor {
19626    fn render(&mut self, _: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
19627        let settings = ThemeSettings::get_global(cx);
19628
19629        let mut text_style = match self.mode {
19630            EditorMode::SingleLine { .. } | EditorMode::AutoHeight { .. } => TextStyle {
19631                color: cx.theme().colors().editor_foreground,
19632                font_family: settings.ui_font.family.clone(),
19633                font_features: settings.ui_font.features.clone(),
19634                font_fallbacks: settings.ui_font.fallbacks.clone(),
19635                font_size: rems(0.875).into(),
19636                font_weight: settings.ui_font.weight,
19637                line_height: relative(settings.buffer_line_height.value()),
19638                ..Default::default()
19639            },
19640            EditorMode::Full { .. } => TextStyle {
19641                color: cx.theme().colors().editor_foreground,
19642                font_family: settings.buffer_font.family.clone(),
19643                font_features: settings.buffer_font.features.clone(),
19644                font_fallbacks: settings.buffer_font.fallbacks.clone(),
19645                font_size: settings.buffer_font_size(cx).into(),
19646                font_weight: settings.buffer_font.weight,
19647                line_height: relative(settings.buffer_line_height.value()),
19648                ..Default::default()
19649            },
19650        };
19651        if let Some(text_style_refinement) = &self.text_style_refinement {
19652            text_style.refine(text_style_refinement)
19653        }
19654
19655        let background = match self.mode {
19656            EditorMode::SingleLine { .. } => cx.theme().system().transparent,
19657            EditorMode::AutoHeight { max_lines: _ } => cx.theme().system().transparent,
19658            EditorMode::Full { .. } => cx.theme().colors().editor_background,
19659        };
19660
19661        EditorElement::new(
19662            &cx.entity(),
19663            EditorStyle {
19664                background,
19665                local_player: cx.theme().players().local(),
19666                text: text_style,
19667                scrollbar_width: EditorElement::SCROLLBAR_WIDTH,
19668                syntax: cx.theme().syntax().clone(),
19669                status: cx.theme().status().clone(),
19670                inlay_hints_style: make_inlay_hints_style(cx),
19671                inline_completion_styles: make_suggestion_styles(cx),
19672                unnecessary_code_fade: ThemeSettings::get_global(cx).unnecessary_code_fade,
19673            },
19674        )
19675    }
19676}
19677
19678impl EntityInputHandler for Editor {
19679    fn text_for_range(
19680        &mut self,
19681        range_utf16: Range<usize>,
19682        adjusted_range: &mut Option<Range<usize>>,
19683        _: &mut Window,
19684        cx: &mut Context<Self>,
19685    ) -> Option<String> {
19686        let snapshot = self.buffer.read(cx).read(cx);
19687        let start = snapshot.clip_offset_utf16(OffsetUtf16(range_utf16.start), Bias::Left);
19688        let end = snapshot.clip_offset_utf16(OffsetUtf16(range_utf16.end), Bias::Right);
19689        if (start.0..end.0) != range_utf16 {
19690            adjusted_range.replace(start.0..end.0);
19691        }
19692        Some(snapshot.text_for_range(start..end).collect())
19693    }
19694
19695    fn selected_text_range(
19696        &mut self,
19697        ignore_disabled_input: bool,
19698        _: &mut Window,
19699        cx: &mut Context<Self>,
19700    ) -> Option<UTF16Selection> {
19701        // Prevent the IME menu from appearing when holding down an alphabetic key
19702        // while input is disabled.
19703        if !ignore_disabled_input && !self.input_enabled {
19704            return None;
19705        }
19706
19707        let selection = self.selections.newest::<OffsetUtf16>(cx);
19708        let range = selection.range();
19709
19710        Some(UTF16Selection {
19711            range: range.start.0..range.end.0,
19712            reversed: selection.reversed,
19713        })
19714    }
19715
19716    fn marked_text_range(&self, _: &mut Window, cx: &mut Context<Self>) -> Option<Range<usize>> {
19717        let snapshot = self.buffer.read(cx).read(cx);
19718        let range = self.text_highlights::<InputComposition>(cx)?.1.first()?;
19719        Some(range.start.to_offset_utf16(&snapshot).0..range.end.to_offset_utf16(&snapshot).0)
19720    }
19721
19722    fn unmark_text(&mut self, _: &mut Window, cx: &mut Context<Self>) {
19723        self.clear_highlights::<InputComposition>(cx);
19724        self.ime_transaction.take();
19725    }
19726
19727    fn replace_text_in_range(
19728        &mut self,
19729        range_utf16: Option<Range<usize>>,
19730        text: &str,
19731        window: &mut Window,
19732        cx: &mut Context<Self>,
19733    ) {
19734        if !self.input_enabled {
19735            cx.emit(EditorEvent::InputIgnored { text: text.into() });
19736            return;
19737        }
19738
19739        self.transact(window, cx, |this, window, cx| {
19740            let new_selected_ranges = if let Some(range_utf16) = range_utf16 {
19741                let range_utf16 = OffsetUtf16(range_utf16.start)..OffsetUtf16(range_utf16.end);
19742                Some(this.selection_replacement_ranges(range_utf16, cx))
19743            } else {
19744                this.marked_text_ranges(cx)
19745            };
19746
19747            let range_to_replace = new_selected_ranges.as_ref().and_then(|ranges_to_replace| {
19748                let newest_selection_id = this.selections.newest_anchor().id;
19749                this.selections
19750                    .all::<OffsetUtf16>(cx)
19751                    .iter()
19752                    .zip(ranges_to_replace.iter())
19753                    .find_map(|(selection, range)| {
19754                        if selection.id == newest_selection_id {
19755                            Some(
19756                                (range.start.0 as isize - selection.head().0 as isize)
19757                                    ..(range.end.0 as isize - selection.head().0 as isize),
19758                            )
19759                        } else {
19760                            None
19761                        }
19762                    })
19763            });
19764
19765            cx.emit(EditorEvent::InputHandled {
19766                utf16_range_to_replace: range_to_replace,
19767                text: text.into(),
19768            });
19769
19770            if let Some(new_selected_ranges) = new_selected_ranges {
19771                this.change_selections(None, window, cx, |selections| {
19772                    selections.select_ranges(new_selected_ranges)
19773                });
19774                this.backspace(&Default::default(), window, cx);
19775            }
19776
19777            this.handle_input(text, window, cx);
19778        });
19779
19780        if let Some(transaction) = self.ime_transaction {
19781            self.buffer.update(cx, |buffer, cx| {
19782                buffer.group_until_transaction(transaction, cx);
19783            });
19784        }
19785
19786        self.unmark_text(window, cx);
19787    }
19788
19789    fn replace_and_mark_text_in_range(
19790        &mut self,
19791        range_utf16: Option<Range<usize>>,
19792        text: &str,
19793        new_selected_range_utf16: Option<Range<usize>>,
19794        window: &mut Window,
19795        cx: &mut Context<Self>,
19796    ) {
19797        if !self.input_enabled {
19798            return;
19799        }
19800
19801        let transaction = self.transact(window, cx, |this, window, cx| {
19802            let ranges_to_replace = if let Some(mut marked_ranges) = this.marked_text_ranges(cx) {
19803                let snapshot = this.buffer.read(cx).read(cx);
19804                if let Some(relative_range_utf16) = range_utf16.as_ref() {
19805                    for marked_range in &mut marked_ranges {
19806                        marked_range.end.0 = marked_range.start.0 + relative_range_utf16.end;
19807                        marked_range.start.0 += relative_range_utf16.start;
19808                        marked_range.start =
19809                            snapshot.clip_offset_utf16(marked_range.start, Bias::Left);
19810                        marked_range.end =
19811                            snapshot.clip_offset_utf16(marked_range.end, Bias::Right);
19812                    }
19813                }
19814                Some(marked_ranges)
19815            } else if let Some(range_utf16) = range_utf16 {
19816                let range_utf16 = OffsetUtf16(range_utf16.start)..OffsetUtf16(range_utf16.end);
19817                Some(this.selection_replacement_ranges(range_utf16, cx))
19818            } else {
19819                None
19820            };
19821
19822            let range_to_replace = ranges_to_replace.as_ref().and_then(|ranges_to_replace| {
19823                let newest_selection_id = this.selections.newest_anchor().id;
19824                this.selections
19825                    .all::<OffsetUtf16>(cx)
19826                    .iter()
19827                    .zip(ranges_to_replace.iter())
19828                    .find_map(|(selection, range)| {
19829                        if selection.id == newest_selection_id {
19830                            Some(
19831                                (range.start.0 as isize - selection.head().0 as isize)
19832                                    ..(range.end.0 as isize - selection.head().0 as isize),
19833                            )
19834                        } else {
19835                            None
19836                        }
19837                    })
19838            });
19839
19840            cx.emit(EditorEvent::InputHandled {
19841                utf16_range_to_replace: range_to_replace,
19842                text: text.into(),
19843            });
19844
19845            if let Some(ranges) = ranges_to_replace {
19846                this.change_selections(None, window, cx, |s| s.select_ranges(ranges));
19847            }
19848
19849            let marked_ranges = {
19850                let snapshot = this.buffer.read(cx).read(cx);
19851                this.selections
19852                    .disjoint_anchors()
19853                    .iter()
19854                    .map(|selection| {
19855                        selection.start.bias_left(&snapshot)..selection.end.bias_right(&snapshot)
19856                    })
19857                    .collect::<Vec<_>>()
19858            };
19859
19860            if text.is_empty() {
19861                this.unmark_text(window, cx);
19862            } else {
19863                this.highlight_text::<InputComposition>(
19864                    marked_ranges.clone(),
19865                    HighlightStyle {
19866                        underline: Some(UnderlineStyle {
19867                            thickness: px(1.),
19868                            color: None,
19869                            wavy: false,
19870                        }),
19871                        ..Default::default()
19872                    },
19873                    cx,
19874                );
19875            }
19876
19877            // Disable auto-closing when composing text (i.e. typing a `"` on a Brazilian keyboard)
19878            let use_autoclose = this.use_autoclose;
19879            let use_auto_surround = this.use_auto_surround;
19880            this.set_use_autoclose(false);
19881            this.set_use_auto_surround(false);
19882            this.handle_input(text, window, cx);
19883            this.set_use_autoclose(use_autoclose);
19884            this.set_use_auto_surround(use_auto_surround);
19885
19886            if let Some(new_selected_range) = new_selected_range_utf16 {
19887                let snapshot = this.buffer.read(cx).read(cx);
19888                let new_selected_ranges = marked_ranges
19889                    .into_iter()
19890                    .map(|marked_range| {
19891                        let insertion_start = marked_range.start.to_offset_utf16(&snapshot).0;
19892                        let new_start = OffsetUtf16(new_selected_range.start + insertion_start);
19893                        let new_end = OffsetUtf16(new_selected_range.end + insertion_start);
19894                        snapshot.clip_offset_utf16(new_start, Bias::Left)
19895                            ..snapshot.clip_offset_utf16(new_end, Bias::Right)
19896                    })
19897                    .collect::<Vec<_>>();
19898
19899                drop(snapshot);
19900                this.change_selections(None, window, cx, |selections| {
19901                    selections.select_ranges(new_selected_ranges)
19902                });
19903            }
19904        });
19905
19906        self.ime_transaction = self.ime_transaction.or(transaction);
19907        if let Some(transaction) = self.ime_transaction {
19908            self.buffer.update(cx, |buffer, cx| {
19909                buffer.group_until_transaction(transaction, cx);
19910            });
19911        }
19912
19913        if self.text_highlights::<InputComposition>(cx).is_none() {
19914            self.ime_transaction.take();
19915        }
19916    }
19917
19918    fn bounds_for_range(
19919        &mut self,
19920        range_utf16: Range<usize>,
19921        element_bounds: gpui::Bounds<Pixels>,
19922        window: &mut Window,
19923        cx: &mut Context<Self>,
19924    ) -> Option<gpui::Bounds<Pixels>> {
19925        let text_layout_details = self.text_layout_details(window);
19926        let gpui::Size {
19927            width: em_width,
19928            height: line_height,
19929        } = self.character_size(window);
19930
19931        let snapshot = self.snapshot(window, cx);
19932        let scroll_position = snapshot.scroll_position();
19933        let scroll_left = scroll_position.x * em_width;
19934
19935        let start = OffsetUtf16(range_utf16.start).to_display_point(&snapshot);
19936        let x = snapshot.x_for_display_point(start, &text_layout_details) - scroll_left
19937            + self.gutter_dimensions.width
19938            + self.gutter_dimensions.margin;
19939        let y = line_height * (start.row().as_f32() - scroll_position.y);
19940
19941        Some(Bounds {
19942            origin: element_bounds.origin + point(x, y),
19943            size: size(em_width, line_height),
19944        })
19945    }
19946
19947    fn character_index_for_point(
19948        &mut self,
19949        point: gpui::Point<Pixels>,
19950        _window: &mut Window,
19951        _cx: &mut Context<Self>,
19952    ) -> Option<usize> {
19953        let position_map = self.last_position_map.as_ref()?;
19954        if !position_map.text_hitbox.contains(&point) {
19955            return None;
19956        }
19957        let display_point = position_map.point_for_position(point).previous_valid;
19958        let anchor = position_map
19959            .snapshot
19960            .display_point_to_anchor(display_point, Bias::Left);
19961        let utf16_offset = anchor.to_offset_utf16(&position_map.snapshot.buffer_snapshot);
19962        Some(utf16_offset.0)
19963    }
19964}
19965
19966trait SelectionExt {
19967    fn display_range(&self, map: &DisplaySnapshot) -> Range<DisplayPoint>;
19968    fn spanned_rows(
19969        &self,
19970        include_end_if_at_line_start: bool,
19971        map: &DisplaySnapshot,
19972    ) -> Range<MultiBufferRow>;
19973}
19974
19975impl<T: ToPoint + ToOffset> SelectionExt for Selection<T> {
19976    fn display_range(&self, map: &DisplaySnapshot) -> Range<DisplayPoint> {
19977        let start = self
19978            .start
19979            .to_point(&map.buffer_snapshot)
19980            .to_display_point(map);
19981        let end = self
19982            .end
19983            .to_point(&map.buffer_snapshot)
19984            .to_display_point(map);
19985        if self.reversed {
19986            end..start
19987        } else {
19988            start..end
19989        }
19990    }
19991
19992    fn spanned_rows(
19993        &self,
19994        include_end_if_at_line_start: bool,
19995        map: &DisplaySnapshot,
19996    ) -> Range<MultiBufferRow> {
19997        let start = self.start.to_point(&map.buffer_snapshot);
19998        let mut end = self.end.to_point(&map.buffer_snapshot);
19999        if !include_end_if_at_line_start && start.row != end.row && end.column == 0 {
20000            end.row -= 1;
20001        }
20002
20003        let buffer_start = map.prev_line_boundary(start).0;
20004        let buffer_end = map.next_line_boundary(end).0;
20005        MultiBufferRow(buffer_start.row)..MultiBufferRow(buffer_end.row + 1)
20006    }
20007}
20008
20009impl<T: InvalidationRegion> InvalidationStack<T> {
20010    fn invalidate<S>(&mut self, selections: &[Selection<S>], buffer: &MultiBufferSnapshot)
20011    where
20012        S: Clone + ToOffset,
20013    {
20014        while let Some(region) = self.last() {
20015            let all_selections_inside_invalidation_ranges =
20016                if selections.len() == region.ranges().len() {
20017                    selections
20018                        .iter()
20019                        .zip(region.ranges().iter().map(|r| r.to_offset(buffer)))
20020                        .all(|(selection, invalidation_range)| {
20021                            let head = selection.head().to_offset(buffer);
20022                            invalidation_range.start <= head && invalidation_range.end >= head
20023                        })
20024                } else {
20025                    false
20026                };
20027
20028            if all_selections_inside_invalidation_ranges {
20029                break;
20030            } else {
20031                self.pop();
20032            }
20033        }
20034    }
20035}
20036
20037impl<T> Default for InvalidationStack<T> {
20038    fn default() -> Self {
20039        Self(Default::default())
20040    }
20041}
20042
20043impl<T> Deref for InvalidationStack<T> {
20044    type Target = Vec<T>;
20045
20046    fn deref(&self) -> &Self::Target {
20047        &self.0
20048    }
20049}
20050
20051impl<T> DerefMut for InvalidationStack<T> {
20052    fn deref_mut(&mut self) -> &mut Self::Target {
20053        &mut self.0
20054    }
20055}
20056
20057impl InvalidationRegion for SnippetState {
20058    fn ranges(&self) -> &[Range<Anchor>] {
20059        &self.ranges[self.active_index]
20060    }
20061}
20062
20063pub fn diagnostic_block_renderer(
20064    diagnostic: Diagnostic,
20065    max_message_rows: Option<u8>,
20066    allow_closing: bool,
20067) -> RenderBlock {
20068    let (text_without_backticks, code_ranges) =
20069        highlight_diagnostic_message(&diagnostic, max_message_rows);
20070
20071    Arc::new(move |cx: &mut BlockContext| {
20072        let group_id: SharedString = cx.block_id.to_string().into();
20073
20074        let mut text_style = cx.window.text_style().clone();
20075        text_style.color = diagnostic_style(diagnostic.severity, cx.theme().status());
20076        let theme_settings = ThemeSettings::get_global(cx);
20077        text_style.font_family = theme_settings.buffer_font.family.clone();
20078        text_style.font_style = theme_settings.buffer_font.style;
20079        text_style.font_features = theme_settings.buffer_font.features.clone();
20080        text_style.font_weight = theme_settings.buffer_font.weight;
20081
20082        let multi_line_diagnostic = diagnostic.message.contains('\n');
20083
20084        let buttons = |diagnostic: &Diagnostic| {
20085            if multi_line_diagnostic {
20086                v_flex()
20087            } else {
20088                h_flex()
20089            }
20090            .when(allow_closing, |div| {
20091                div.children(diagnostic.is_primary.then(|| {
20092                    IconButton::new("close-block", IconName::XCircle)
20093                        .icon_color(Color::Muted)
20094                        .size(ButtonSize::Compact)
20095                        .style(ButtonStyle::Transparent)
20096                        .visible_on_hover(group_id.clone())
20097                        .on_click(move |_click, window, cx| {
20098                            window.dispatch_action(Box::new(Cancel), cx)
20099                        })
20100                        .tooltip(|window, cx| {
20101                            Tooltip::for_action("Close Diagnostics", &Cancel, window, cx)
20102                        })
20103                }))
20104            })
20105            .child(
20106                IconButton::new("copy-block", IconName::Copy)
20107                    .icon_color(Color::Muted)
20108                    .size(ButtonSize::Compact)
20109                    .style(ButtonStyle::Transparent)
20110                    .visible_on_hover(group_id.clone())
20111                    .on_click({
20112                        let message = diagnostic.message.clone();
20113                        move |_click, _, cx| {
20114                            cx.write_to_clipboard(ClipboardItem::new_string(message.clone()))
20115                        }
20116                    })
20117                    .tooltip(Tooltip::text("Copy diagnostic message")),
20118            )
20119        };
20120
20121        let icon_size = buttons(&diagnostic).into_any_element().layout_as_root(
20122            AvailableSpace::min_size(),
20123            cx.window,
20124            cx.app,
20125        );
20126
20127        h_flex()
20128            .id(cx.block_id)
20129            .group(group_id.clone())
20130            .relative()
20131            .size_full()
20132            .block_mouse_down()
20133            .pl(cx.gutter_dimensions.width)
20134            .w(cx.max_width - cx.gutter_dimensions.full_width())
20135            .child(
20136                div()
20137                    .flex()
20138                    .w(cx.anchor_x - cx.gutter_dimensions.width - icon_size.width)
20139                    .flex_shrink(),
20140            )
20141            .child(buttons(&diagnostic))
20142            .child(div().flex().flex_shrink_0().child(
20143                StyledText::new(text_without_backticks.clone()).with_default_highlights(
20144                    &text_style,
20145                    code_ranges.iter().map(|range| {
20146                        (
20147                            range.clone(),
20148                            HighlightStyle {
20149                                font_weight: Some(FontWeight::BOLD),
20150                                ..Default::default()
20151                            },
20152                        )
20153                    }),
20154                ),
20155            ))
20156            .into_any_element()
20157    })
20158}
20159
20160fn inline_completion_edit_text(
20161    current_snapshot: &BufferSnapshot,
20162    edits: &[(Range<Anchor>, String)],
20163    edit_preview: &EditPreview,
20164    include_deletions: bool,
20165    cx: &App,
20166) -> HighlightedText {
20167    let edits = edits
20168        .iter()
20169        .map(|(anchor, text)| {
20170            (
20171                anchor.start.text_anchor..anchor.end.text_anchor,
20172                text.clone(),
20173            )
20174        })
20175        .collect::<Vec<_>>();
20176
20177    edit_preview.highlight_edits(current_snapshot, &edits, include_deletions, cx)
20178}
20179
20180pub fn highlight_diagnostic_message(
20181    diagnostic: &Diagnostic,
20182    mut max_message_rows: Option<u8>,
20183) -> (SharedString, Vec<Range<usize>>) {
20184    let mut text_without_backticks = String::new();
20185    let mut code_ranges = Vec::new();
20186
20187    if let Some(source) = &diagnostic.source {
20188        text_without_backticks.push_str(source);
20189        code_ranges.push(0..source.len());
20190        text_without_backticks.push_str(": ");
20191    }
20192
20193    let mut prev_offset = 0;
20194    let mut in_code_block = false;
20195    let has_row_limit = max_message_rows.is_some();
20196    let mut newline_indices = diagnostic
20197        .message
20198        .match_indices('\n')
20199        .filter(|_| has_row_limit)
20200        .map(|(ix, _)| ix)
20201        .fuse()
20202        .peekable();
20203
20204    for (quote_ix, _) in diagnostic
20205        .message
20206        .match_indices('`')
20207        .chain([(diagnostic.message.len(), "")])
20208    {
20209        let mut first_newline_ix = None;
20210        let mut last_newline_ix = None;
20211        while let Some(newline_ix) = newline_indices.peek() {
20212            if *newline_ix < quote_ix {
20213                if first_newline_ix.is_none() {
20214                    first_newline_ix = Some(*newline_ix);
20215                }
20216                last_newline_ix = Some(*newline_ix);
20217
20218                if let Some(rows_left) = &mut max_message_rows {
20219                    if *rows_left == 0 {
20220                        break;
20221                    } else {
20222                        *rows_left -= 1;
20223                    }
20224                }
20225                let _ = newline_indices.next();
20226            } else {
20227                break;
20228            }
20229        }
20230        let prev_len = text_without_backticks.len();
20231        let new_text = &diagnostic.message[prev_offset..first_newline_ix.unwrap_or(quote_ix)];
20232        text_without_backticks.push_str(new_text);
20233        if in_code_block {
20234            code_ranges.push(prev_len..text_without_backticks.len());
20235        }
20236        prev_offset = last_newline_ix.unwrap_or(quote_ix) + 1;
20237        in_code_block = !in_code_block;
20238        if first_newline_ix.map_or(false, |newline_ix| newline_ix < quote_ix) {
20239            text_without_backticks.push_str("...");
20240            break;
20241        }
20242    }
20243
20244    (text_without_backticks.into(), code_ranges)
20245}
20246
20247fn diagnostic_style(severity: DiagnosticSeverity, colors: &StatusColors) -> Hsla {
20248    match severity {
20249        DiagnosticSeverity::ERROR => colors.error,
20250        DiagnosticSeverity::WARNING => colors.warning,
20251        DiagnosticSeverity::INFORMATION => colors.info,
20252        DiagnosticSeverity::HINT => colors.info,
20253        _ => colors.ignored,
20254    }
20255}
20256
20257pub fn styled_runs_for_code_label<'a>(
20258    label: &'a CodeLabel,
20259    syntax_theme: &'a theme::SyntaxTheme,
20260) -> impl 'a + Iterator<Item = (Range<usize>, HighlightStyle)> {
20261    let fade_out = HighlightStyle {
20262        fade_out: Some(0.35),
20263        ..Default::default()
20264    };
20265
20266    let mut prev_end = label.filter_range.end;
20267    label
20268        .runs
20269        .iter()
20270        .enumerate()
20271        .flat_map(move |(ix, (range, highlight_id))| {
20272            let style = if let Some(style) = highlight_id.style(syntax_theme) {
20273                style
20274            } else {
20275                return Default::default();
20276            };
20277            let mut muted_style = style;
20278            muted_style.highlight(fade_out);
20279
20280            let mut runs = SmallVec::<[(Range<usize>, HighlightStyle); 3]>::new();
20281            if range.start >= label.filter_range.end {
20282                if range.start > prev_end {
20283                    runs.push((prev_end..range.start, fade_out));
20284                }
20285                runs.push((range.clone(), muted_style));
20286            } else if range.end <= label.filter_range.end {
20287                runs.push((range.clone(), style));
20288            } else {
20289                runs.push((range.start..label.filter_range.end, style));
20290                runs.push((label.filter_range.end..range.end, muted_style));
20291            }
20292            prev_end = cmp::max(prev_end, range.end);
20293
20294            if ix + 1 == label.runs.len() && label.text.len() > prev_end {
20295                runs.push((prev_end..label.text.len(), fade_out));
20296            }
20297
20298            runs
20299        })
20300}
20301
20302pub(crate) fn split_words(text: &str) -> impl std::iter::Iterator<Item = &str> + '_ {
20303    let mut prev_index = 0;
20304    let mut prev_codepoint: Option<char> = None;
20305    text.char_indices()
20306        .chain([(text.len(), '\0')])
20307        .filter_map(move |(index, codepoint)| {
20308            let prev_codepoint = prev_codepoint.replace(codepoint)?;
20309            let is_boundary = index == text.len()
20310                || !prev_codepoint.is_uppercase() && codepoint.is_uppercase()
20311                || !prev_codepoint.is_alphanumeric() && codepoint.is_alphanumeric();
20312            if is_boundary {
20313                let chunk = &text[prev_index..index];
20314                prev_index = index;
20315                Some(chunk)
20316            } else {
20317                None
20318            }
20319        })
20320}
20321
20322pub trait RangeToAnchorExt: Sized {
20323    fn to_anchors(self, snapshot: &MultiBufferSnapshot) -> Range<Anchor>;
20324
20325    fn to_display_points(self, snapshot: &EditorSnapshot) -> Range<DisplayPoint> {
20326        let anchor_range = self.to_anchors(&snapshot.buffer_snapshot);
20327        anchor_range.start.to_display_point(snapshot)..anchor_range.end.to_display_point(snapshot)
20328    }
20329}
20330
20331impl<T: ToOffset> RangeToAnchorExt for Range<T> {
20332    fn to_anchors(self, snapshot: &MultiBufferSnapshot) -> Range<Anchor> {
20333        let start_offset = self.start.to_offset(snapshot);
20334        let end_offset = self.end.to_offset(snapshot);
20335        if start_offset == end_offset {
20336            snapshot.anchor_before(start_offset)..snapshot.anchor_before(end_offset)
20337        } else {
20338            snapshot.anchor_after(self.start)..snapshot.anchor_before(self.end)
20339        }
20340    }
20341}
20342
20343pub trait RowExt {
20344    fn as_f32(&self) -> f32;
20345
20346    fn next_row(&self) -> Self;
20347
20348    fn previous_row(&self) -> Self;
20349
20350    fn minus(&self, other: Self) -> u32;
20351}
20352
20353impl RowExt for DisplayRow {
20354    fn as_f32(&self) -> f32 {
20355        self.0 as f32
20356    }
20357
20358    fn next_row(&self) -> Self {
20359        Self(self.0 + 1)
20360    }
20361
20362    fn previous_row(&self) -> Self {
20363        Self(self.0.saturating_sub(1))
20364    }
20365
20366    fn minus(&self, other: Self) -> u32 {
20367        self.0 - other.0
20368    }
20369}
20370
20371impl RowExt for MultiBufferRow {
20372    fn as_f32(&self) -> f32 {
20373        self.0 as f32
20374    }
20375
20376    fn next_row(&self) -> Self {
20377        Self(self.0 + 1)
20378    }
20379
20380    fn previous_row(&self) -> Self {
20381        Self(self.0.saturating_sub(1))
20382    }
20383
20384    fn minus(&self, other: Self) -> u32 {
20385        self.0 - other.0
20386    }
20387}
20388
20389trait RowRangeExt {
20390    type Row;
20391
20392    fn len(&self) -> usize;
20393
20394    fn iter_rows(&self) -> impl DoubleEndedIterator<Item = Self::Row>;
20395}
20396
20397impl RowRangeExt for Range<MultiBufferRow> {
20398    type Row = MultiBufferRow;
20399
20400    fn len(&self) -> usize {
20401        (self.end.0 - self.start.0) as usize
20402    }
20403
20404    fn iter_rows(&self) -> impl DoubleEndedIterator<Item = MultiBufferRow> {
20405        (self.start.0..self.end.0).map(MultiBufferRow)
20406    }
20407}
20408
20409impl RowRangeExt for Range<DisplayRow> {
20410    type Row = DisplayRow;
20411
20412    fn len(&self) -> usize {
20413        (self.end.0 - self.start.0) as usize
20414    }
20415
20416    fn iter_rows(&self) -> impl DoubleEndedIterator<Item = DisplayRow> {
20417        (self.start.0..self.end.0).map(DisplayRow)
20418    }
20419}
20420
20421/// If select range has more than one line, we
20422/// just point the cursor to range.start.
20423fn collapse_multiline_range(range: Range<Point>) -> Range<Point> {
20424    if range.start.row == range.end.row {
20425        range
20426    } else {
20427        range.start..range.start
20428    }
20429}
20430pub struct KillRing(ClipboardItem);
20431impl Global for KillRing {}
20432
20433const UPDATE_DEBOUNCE: Duration = Duration::from_millis(50);
20434
20435enum BreakpointPromptEditAction {
20436    Log,
20437    Condition,
20438    HitCondition,
20439}
20440
20441struct BreakpointPromptEditor {
20442    pub(crate) prompt: Entity<Editor>,
20443    editor: WeakEntity<Editor>,
20444    breakpoint_anchor: Anchor,
20445    breakpoint: Breakpoint,
20446    edit_action: BreakpointPromptEditAction,
20447    block_ids: HashSet<CustomBlockId>,
20448    gutter_dimensions: Arc<Mutex<GutterDimensions>>,
20449    _subscriptions: Vec<Subscription>,
20450}
20451
20452impl BreakpointPromptEditor {
20453    const MAX_LINES: u8 = 4;
20454
20455    fn new(
20456        editor: WeakEntity<Editor>,
20457        breakpoint_anchor: Anchor,
20458        breakpoint: Breakpoint,
20459        edit_action: BreakpointPromptEditAction,
20460        window: &mut Window,
20461        cx: &mut Context<Self>,
20462    ) -> Self {
20463        let base_text = match edit_action {
20464            BreakpointPromptEditAction::Log => breakpoint.message.as_ref(),
20465            BreakpointPromptEditAction::Condition => breakpoint.condition.as_ref(),
20466            BreakpointPromptEditAction::HitCondition => breakpoint.hit_condition.as_ref(),
20467        }
20468        .map(|msg| msg.to_string())
20469        .unwrap_or_default();
20470
20471        let buffer = cx.new(|cx| Buffer::local(base_text, cx));
20472        let buffer = cx.new(|cx| MultiBuffer::singleton(buffer, cx));
20473
20474        let prompt = cx.new(|cx| {
20475            let mut prompt = Editor::new(
20476                EditorMode::AutoHeight {
20477                    max_lines: Self::MAX_LINES as usize,
20478                },
20479                buffer,
20480                None,
20481                window,
20482                cx,
20483            );
20484            prompt.set_soft_wrap_mode(language::language_settings::SoftWrap::EditorWidth, cx);
20485            prompt.set_show_cursor_when_unfocused(false, cx);
20486            prompt.set_placeholder_text(
20487                match edit_action {
20488                    BreakpointPromptEditAction::Log => "Message to log when a breakpoint is hit. Expressions within {} are interpolated.",
20489                    BreakpointPromptEditAction::Condition => "Condition when a breakpoint is hit. Expressions within {} are interpolated.",
20490                    BreakpointPromptEditAction::HitCondition => "How many breakpoint hits to ignore",
20491                },
20492                cx,
20493            );
20494
20495            prompt
20496        });
20497
20498        Self {
20499            prompt,
20500            editor,
20501            breakpoint_anchor,
20502            breakpoint,
20503            edit_action,
20504            gutter_dimensions: Arc::new(Mutex::new(GutterDimensions::default())),
20505            block_ids: Default::default(),
20506            _subscriptions: vec![],
20507        }
20508    }
20509
20510    pub(crate) fn add_block_ids(&mut self, block_ids: Vec<CustomBlockId>) {
20511        self.block_ids.extend(block_ids)
20512    }
20513
20514    fn confirm(&mut self, _: &menu::Confirm, window: &mut Window, cx: &mut Context<Self>) {
20515        if let Some(editor) = self.editor.upgrade() {
20516            let message = self
20517                .prompt
20518                .read(cx)
20519                .buffer
20520                .read(cx)
20521                .as_singleton()
20522                .expect("A multi buffer in breakpoint prompt isn't possible")
20523                .read(cx)
20524                .as_rope()
20525                .to_string();
20526
20527            editor.update(cx, |editor, cx| {
20528                editor.edit_breakpoint_at_anchor(
20529                    self.breakpoint_anchor,
20530                    self.breakpoint.clone(),
20531                    match self.edit_action {
20532                        BreakpointPromptEditAction::Log => {
20533                            BreakpointEditAction::EditLogMessage(message.into())
20534                        }
20535                        BreakpointPromptEditAction::Condition => {
20536                            BreakpointEditAction::EditCondition(message.into())
20537                        }
20538                        BreakpointPromptEditAction::HitCondition => {
20539                            BreakpointEditAction::EditHitCondition(message.into())
20540                        }
20541                    },
20542                    cx,
20543                );
20544
20545                editor.remove_blocks(self.block_ids.clone(), None, cx);
20546                cx.focus_self(window);
20547            });
20548        }
20549    }
20550
20551    fn cancel(&mut self, _: &menu::Cancel, window: &mut Window, cx: &mut Context<Self>) {
20552        self.editor
20553            .update(cx, |editor, cx| {
20554                editor.remove_blocks(self.block_ids.clone(), None, cx);
20555                window.focus(&editor.focus_handle);
20556            })
20557            .log_err();
20558    }
20559
20560    fn render_prompt_editor(&self, cx: &mut Context<Self>) -> impl IntoElement {
20561        let settings = ThemeSettings::get_global(cx);
20562        let text_style = TextStyle {
20563            color: if self.prompt.read(cx).read_only(cx) {
20564                cx.theme().colors().text_disabled
20565            } else {
20566                cx.theme().colors().text
20567            },
20568            font_family: settings.buffer_font.family.clone(),
20569            font_fallbacks: settings.buffer_font.fallbacks.clone(),
20570            font_size: settings.buffer_font_size(cx).into(),
20571            font_weight: settings.buffer_font.weight,
20572            line_height: relative(settings.buffer_line_height.value()),
20573            ..Default::default()
20574        };
20575        EditorElement::new(
20576            &self.prompt,
20577            EditorStyle {
20578                background: cx.theme().colors().editor_background,
20579                local_player: cx.theme().players().local(),
20580                text: text_style,
20581                ..Default::default()
20582            },
20583        )
20584    }
20585}
20586
20587impl Render for BreakpointPromptEditor {
20588    fn render(&mut self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
20589        let gutter_dimensions = *self.gutter_dimensions.lock();
20590        h_flex()
20591            .key_context("Editor")
20592            .bg(cx.theme().colors().editor_background)
20593            .border_y_1()
20594            .border_color(cx.theme().status().info_border)
20595            .size_full()
20596            .py(window.line_height() / 2.5)
20597            .on_action(cx.listener(Self::confirm))
20598            .on_action(cx.listener(Self::cancel))
20599            .child(h_flex().w(gutter_dimensions.full_width() + (gutter_dimensions.margin / 2.0)))
20600            .child(div().flex_1().child(self.render_prompt_editor(cx)))
20601    }
20602}
20603
20604impl Focusable for BreakpointPromptEditor {
20605    fn focus_handle(&self, cx: &App) -> FocusHandle {
20606        self.prompt.focus_handle(cx)
20607    }
20608}
20609
20610fn all_edits_insertions_or_deletions(
20611    edits: &Vec<(Range<Anchor>, String)>,
20612    snapshot: &MultiBufferSnapshot,
20613) -> bool {
20614    let mut all_insertions = true;
20615    let mut all_deletions = true;
20616
20617    for (range, new_text) in edits.iter() {
20618        let range_is_empty = range.to_offset(&snapshot).is_empty();
20619        let text_is_empty = new_text.is_empty();
20620
20621        if range_is_empty != text_is_empty {
20622            if range_is_empty {
20623                all_deletions = false;
20624            } else {
20625                all_insertions = false;
20626            }
20627        } else {
20628            return false;
20629        }
20630
20631        if !all_insertions && !all_deletions {
20632            return false;
20633        }
20634    }
20635    all_insertions || all_deletions
20636}
20637
20638struct MissingEditPredictionKeybindingTooltip;
20639
20640impl Render for MissingEditPredictionKeybindingTooltip {
20641    fn render(&mut self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
20642        ui::tooltip_container(window, cx, |container, _, cx| {
20643            container
20644                .flex_shrink_0()
20645                .max_w_80()
20646                .min_h(rems_from_px(124.))
20647                .justify_between()
20648                .child(
20649                    v_flex()
20650                        .flex_1()
20651                        .text_ui_sm(cx)
20652                        .child(Label::new("Conflict with Accept Keybinding"))
20653                        .child("Your keymap currently overrides the default accept keybinding. To continue, assign one keybinding for the `editor::AcceptEditPrediction` action.")
20654                )
20655                .child(
20656                    h_flex()
20657                        .pb_1()
20658                        .gap_1()
20659                        .items_end()
20660                        .w_full()
20661                        .child(Button::new("open-keymap", "Assign Keybinding").size(ButtonSize::Compact).on_click(|_ev, window, cx| {
20662                            window.dispatch_action(zed_actions::OpenKeymap.boxed_clone(), cx)
20663                        }))
20664                        .child(Button::new("see-docs", "See Docs").size(ButtonSize::Compact).on_click(|_ev, _window, cx| {
20665                            cx.open_url("https://zed.dev/docs/completions#edit-predictions-missing-keybinding");
20666                        })),
20667                )
20668        })
20669    }
20670}
20671
20672#[derive(Debug, Clone, Copy, PartialEq)]
20673pub struct LineHighlight {
20674    pub background: Background,
20675    pub border: Option<gpui::Hsla>,
20676}
20677
20678impl From<Hsla> for LineHighlight {
20679    fn from(hsla: Hsla) -> Self {
20680        Self {
20681            background: hsla.into(),
20682            border: None,
20683        }
20684    }
20685}
20686
20687impl From<Background> for LineHighlight {
20688    fn from(background: Background) -> Self {
20689        Self {
20690            background,
20691            border: None,
20692        }
20693    }
20694}
20695
20696fn render_diff_hunk_controls(
20697    row: u32,
20698    status: &DiffHunkStatus,
20699    hunk_range: Range<Anchor>,
20700    is_created_file: bool,
20701    line_height: Pixels,
20702    editor: &Entity<Editor>,
20703    _window: &mut Window,
20704    cx: &mut App,
20705) -> AnyElement {
20706    h_flex()
20707        .h(line_height)
20708        .mr_1()
20709        .gap_1()
20710        .px_0p5()
20711        .pb_1()
20712        .border_x_1()
20713        .border_b_1()
20714        .border_color(cx.theme().colors().border_variant)
20715        .rounded_b_lg()
20716        .bg(cx.theme().colors().editor_background)
20717        .gap_1()
20718        .occlude()
20719        .shadow_md()
20720        .child(if status.has_secondary_hunk() {
20721            Button::new(("stage", row as u64), "Stage")
20722                .alpha(if status.is_pending() { 0.66 } else { 1.0 })
20723                .tooltip({
20724                    let focus_handle = editor.focus_handle(cx);
20725                    move |window, cx| {
20726                        Tooltip::for_action_in(
20727                            "Stage Hunk",
20728                            &::git::ToggleStaged,
20729                            &focus_handle,
20730                            window,
20731                            cx,
20732                        )
20733                    }
20734                })
20735                .on_click({
20736                    let editor = editor.clone();
20737                    move |_event, _window, cx| {
20738                        editor.update(cx, |editor, cx| {
20739                            editor.stage_or_unstage_diff_hunks(
20740                                true,
20741                                vec![hunk_range.start..hunk_range.start],
20742                                cx,
20743                            );
20744                        });
20745                    }
20746                })
20747        } else {
20748            Button::new(("unstage", row as u64), "Unstage")
20749                .alpha(if status.is_pending() { 0.66 } else { 1.0 })
20750                .tooltip({
20751                    let focus_handle = editor.focus_handle(cx);
20752                    move |window, cx| {
20753                        Tooltip::for_action_in(
20754                            "Unstage Hunk",
20755                            &::git::ToggleStaged,
20756                            &focus_handle,
20757                            window,
20758                            cx,
20759                        )
20760                    }
20761                })
20762                .on_click({
20763                    let editor = editor.clone();
20764                    move |_event, _window, cx| {
20765                        editor.update(cx, |editor, cx| {
20766                            editor.stage_or_unstage_diff_hunks(
20767                                false,
20768                                vec![hunk_range.start..hunk_range.start],
20769                                cx,
20770                            );
20771                        });
20772                    }
20773                })
20774        })
20775        .child(
20776            Button::new(("restore", row as u64), "Restore")
20777                .tooltip({
20778                    let focus_handle = editor.focus_handle(cx);
20779                    move |window, cx| {
20780                        Tooltip::for_action_in(
20781                            "Restore Hunk",
20782                            &::git::Restore,
20783                            &focus_handle,
20784                            window,
20785                            cx,
20786                        )
20787                    }
20788                })
20789                .on_click({
20790                    let editor = editor.clone();
20791                    move |_event, window, cx| {
20792                        editor.update(cx, |editor, cx| {
20793                            let snapshot = editor.snapshot(window, cx);
20794                            let point = hunk_range.start.to_point(&snapshot.buffer_snapshot);
20795                            editor.restore_hunks_in_ranges(vec![point..point], window, cx);
20796                        });
20797                    }
20798                })
20799                .disabled(is_created_file),
20800        )
20801        .when(
20802            !editor.read(cx).buffer().read(cx).all_diff_hunks_expanded(),
20803            |el| {
20804                el.child(
20805                    IconButton::new(("next-hunk", row as u64), IconName::ArrowDown)
20806                        .shape(IconButtonShape::Square)
20807                        .icon_size(IconSize::Small)
20808                        // .disabled(!has_multiple_hunks)
20809                        .tooltip({
20810                            let focus_handle = editor.focus_handle(cx);
20811                            move |window, cx| {
20812                                Tooltip::for_action_in(
20813                                    "Next Hunk",
20814                                    &GoToHunk,
20815                                    &focus_handle,
20816                                    window,
20817                                    cx,
20818                                )
20819                            }
20820                        })
20821                        .on_click({
20822                            let editor = editor.clone();
20823                            move |_event, window, cx| {
20824                                editor.update(cx, |editor, cx| {
20825                                    let snapshot = editor.snapshot(window, cx);
20826                                    let position =
20827                                        hunk_range.end.to_point(&snapshot.buffer_snapshot);
20828                                    editor.go_to_hunk_before_or_after_position(
20829                                        &snapshot,
20830                                        position,
20831                                        Direction::Next,
20832                                        window,
20833                                        cx,
20834                                    );
20835                                    editor.expand_selected_diff_hunks(cx);
20836                                });
20837                            }
20838                        }),
20839                )
20840                .child(
20841                    IconButton::new(("prev-hunk", row as u64), IconName::ArrowUp)
20842                        .shape(IconButtonShape::Square)
20843                        .icon_size(IconSize::Small)
20844                        // .disabled(!has_multiple_hunks)
20845                        .tooltip({
20846                            let focus_handle = editor.focus_handle(cx);
20847                            move |window, cx| {
20848                                Tooltip::for_action_in(
20849                                    "Previous Hunk",
20850                                    &GoToPreviousHunk,
20851                                    &focus_handle,
20852                                    window,
20853                                    cx,
20854                                )
20855                            }
20856                        })
20857                        .on_click({
20858                            let editor = editor.clone();
20859                            move |_event, window, cx| {
20860                                editor.update(cx, |editor, cx| {
20861                                    let snapshot = editor.snapshot(window, cx);
20862                                    let point =
20863                                        hunk_range.start.to_point(&snapshot.buffer_snapshot);
20864                                    editor.go_to_hunk_before_or_after_position(
20865                                        &snapshot,
20866                                        point,
20867                                        Direction::Prev,
20868                                        window,
20869                                        cx,
20870                                    );
20871                                    editor.expand_selected_diff_hunks(cx);
20872                                });
20873                            }
20874                        }),
20875                )
20876            },
20877        )
20878        .into_any_element()
20879}